Show() public static méthode

public static Show ( IWin32Window owner, string text ) : DialogResult
owner IWin32Window
text string
Résultat DialogResult
Exemple #1
0
        private void SubmitScenarioButton_Click(object sender, RibbonControlEventArgs e)
        {
            // validate and show warnings

            #region validate

            var emptyInputs        = ScenarioCore.ScenarioUICreator.Instance.GetEmptyEntrysCount(typeof(InputCell));
            var emptyIntermediates =
                ScenarioCore.ScenarioUICreator.Instance.GetEmptyEntrysCount(typeof(IntermediateCell));
            var emptyResults = ScenarioCore.ScenarioUICreator.Instance.GetEmptyEntrysCount(typeof(OutputCell));

            if (emptyInputs > 0 | emptyIntermediates > 0 | emptyResults > 0)
            {
                // FIXME: q&d temporary fix without translations: Do not allow creating scenarios when not all cells are filled
                MessageBox.Show(
                    Resources.tl_Scenario_Notallcellsfilled, Resources.tl_Scenario_CantCreate,
                    MessageBoxButtons.OK);
                return;
            }
            if (ScenarioCore.ScenarioUICreator.Instance.NoValue(typeof(InputCell)))
            {
                //message for no result cell values
                MessageBox.Show(Resources.tl_Scenario_MinOneInput, Resources.tl_MessageBox_Error, MessageBoxButtons.OK);

                //back to the scenario editor
                return;
            }
            else if (ScenarioCore.ScenarioUICreator.Instance.NoValue(typeof(IntermediateCell)) &&
                     ScenarioCore.ScenarioUICreator.Instance.NoValue(typeof(OutputCell)))
            {
                //message for no input cell values
                MessageBox.Show(Resources.tl_Scenario_MinOneOutput, Resources.tl_MessageBox_Error, MessageBoxButtons.OK);

                //back to the scenario editor
                return;
            }
            //else if (emptyInputs > 0 | emptyIntermediates > 0 | emptyResults > 0)
            //{
            // FIXME: Re-enable logic and remove hotfix once the issue has been solved (some inputs made by the user are missing in created scenarios when continuing with incomplete scenario)

            //// message for some empty fields
            //#region create message
            //var messageList = new List<Tuple<string, int>>();
            //if (emptyInputs > 0) messageList.Add(new Tuple<string, int>("input cells", emptyInputs));
            //if (emptyIntermediates > 0) messageList.Add(new Tuple<string, int>("intermediate cells", emptyIntermediates));
            //if (emptyResults > 0) messageList.Add(new Tuple<string, int>("result cells", emptyResults));

            //var message = new StringBuilder();
            //message.Append("Maybe your scenario isn't complete. ");
            //message.Append("The scenario has ");
            //foreach (var p in messageList)
            //{
            //    message.Append(p.Item2 + " empty fields for " + p.Item1);
            //    if (messageList.IndexOf(p) < messageList.Count - 2)
            //    {
            //        message.Append(", ");
            //    }
            //    else if (messageList.IndexOf(p) == messageList.Count - 2)
            //    {
            //        message.Append(" and ");
            //    }
            //}
            //message.Append(".");

            //#endregion

            //var result = MessageBox.Show(
            //    message.ToString(),
            //    "warning",
            //    MessageBoxButtons.OKCancel);

            ////back to the scenario editor
            //if (result == DialogResult.Cancel) return;

            //}

            #endregion

            // end scenario creation
            var newScenario = ScenarioCore.ScenarioUICreator.Instance.End();

            if (newScenario != null)
            {
                DataModel.Instance.CurrentWorkbook.Scenarios.Add(newScenario);
            }

            // set button styles
            SetScenarioCreationButtonStyles(false);
        }
Exemple #2
0
        public Result OnStartup(UIControlledApplication application)
        {
            try
            {
                //TAF load english_us TODO add a way to localize
                res = Resource_en_us.ResourceManager;
                // Create new ribbon panel
                RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description"));

                //Create a push button in the ribbon panel
                var pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo",
                                                                        res.GetString("App_Name"), m_AssemblyName,
                                                                        "Dynamo.Applications.DynamoRevit")) as
                                 PushButton;

                Bitmap dynamoIcon = Resources.logo_square_32x32;


                BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                    dynamoIcon.GetHbitmap(),
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                pushButton.LargeImage = bitmapSource;
                pushButton.Image      = bitmapSource;

                IdlePromise.RegisterIdle(application);

                Updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication);
                if (!UpdaterRegistry.IsUpdaterRegistered(Updater.GetUpdaterId()))
                {
                    UpdaterRegistry.RegisterUpdater(Updater);
                }

                var SpatialFieldFilter           = new ElementClassFilter(typeof(SpatialFieldManager));
                var familyFilter                 = new ElementClassFilter(typeof(FamilyInstance));
                var refPointFilter               = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints);
                var modelCurveFilter             = new ElementClassFilter(typeof(CurveElement));
                var sunFilter                    = new ElementClassFilter(typeof(SunAndShadowSettings));
                IList <ElementFilter> filterList = new List <ElementFilter>();

                filterList.Add(SpatialFieldFilter);
                filterList.Add(familyFilter);
                filterList.Add(modelCurveFilter);
                filterList.Add(refPointFilter);
                filterList.Add(sunFilter);

                ElementFilter filter = new LogicalOrFilter(filterList);

                UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeAny());
                UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion());
                UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition());

                env = new ExecutionEnvironment();

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(Result.Failed);
            }
        }
        static void Main(string[] args)
        {
            bool   hasArgs    = args.Count() > 0;
            string file       = "";
            string exportPath = "";
            string user       = Settings.Default.DefaultUser;
            string password   = Settings.Default.DefaultPassword;


            Project prj = null;

            if (!hasArgs)
            {
                Application app = new Application();
                var         ask = new AskOpen();
                app.Run(ask);
                var res = ask.Result;
                resetSetpoints     = ask.chkResetSetpoints.IsChecked == true;
                removeCodeFromXml  = ask.chkRemoveCode.IsChecked == true;
                removeAllBlanks    = ask.rbRemoveAllBlanks.IsChecked == true;
                removeOnlyOneBlank = ask.rbRemoveOnlyOneBlank.IsChecked == true;
                removeNoBlanks     = ask.rbRemoveNoBlanks.IsChecked == true;

                DisableQuickEdit();

                if (object.Equals(res, false))
                {
                    OpenFileDialog op = new OpenFileDialog();
                    op.Filter          = "TIA-Portal Project|*.ap13;*.ap14;*.ap15;*.ap15_1;*.ap16";
                    op.CheckFileExists = false;
                    op.ValidateNames   = false;
                    var ret = op.ShowDialog();
                    if (ret == true)
                    {
                        file = op.FileName;
                    }
                    else
                    {
                        Console.WriteLine("Bitte S7 projekt als Parameter angeben!");
                        return;
                    }

                    if (Path.GetExtension(file) == ".ap15_1" || Path.GetExtension(file) == ".ap16")
                    {
                        if (InputBox.Show("Credentials", "Enter Username (or cancel if not used)", ref user) !=
                            DialogResult.Cancel)
                        {
                            if (InputBox.Show("Credentials", "Enter Password", ref password) != DialogResult.Cancel)
                            {
                            }
                            else
                            {
                                user     = "";
                                password = "";
                            }
                        }
                        else
                        {
                            user     = "";
                            password = "";
                        }
                    }

                    exportPath = Path.GetDirectoryName(file);
                    exportPath = Path.GetFullPath(Path.Combine(exportPath, "..\\Export"));
                }
                else if (res != null)
                {
                    var ver = ask.Result as string;
                    prj = Projects.AttachProject(ver);

                    exportPath = Path.GetDirectoryName(prj.ProjectFile);
                    exportPath = Path.GetFullPath(Path.Combine(exportPath, "..\\Export"));
                }
                else
                {
                    Environment.Exit(0);
                }

                if (Directory.Exists(exportPath))
                {
                    if (
                        MessageBox.Show(exportPath + " wird gelöscht. Möchten Sie fortfahren?",
                                        "Sicherheitsabfrage",
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        DeleteDirectory(exportPath);
                    }
                    else
                    {
                        Environment.Exit(-1);
                    }
                }

                Directory.CreateDirectory(exportPath);
            }
            else
            {
                file = args[0];
                if (args.Length > 1)
                {
                    user = args[1];
                }
                if (args.Length > 2)
                {
                    password = args[2];
                }
            }

            if (prj == null)
            {
                Credentials credentials = null;
                if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(password))
                {
                    credentials = new Credentials()
                    {
                        Username = user, Password = new SecureString()
                    };
                    foreach (char c in password)
                    {
                        credentials.Password.AppendChar(c);
                    }
                }

                prj = Projects.LoadProject(file, false, credentials);
            }

            _projectType = prj.ProjectType;

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Opened Project - " + prj.ProjectType.ToString());
            Console.WriteLine("Exporting to Folder: " + exportPath);
            Console.WriteLine();
            List <string> skippedBlocksList = new List <string>();

            ParseFolder(prj.ProjectStructure, exportPath, skippedBlocksList);

            Console.WriteLine();
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Red;
            skippedBlocksList.ForEach(i => Console.WriteLine("{0}", i));
            Console.WriteLine();
            Console.WriteLine(skippedBlocksList.Count() + " blocks were skipped");
            if (!hasArgs)
            {
                Console.ReadKey();
            }
        }
        private static void WriteAutoTranslatorLangIni(string language)
        {
            var configPath = Path.Combine(GameRootDirectory, @"BepInEx/Config/AutoTranslatorConfig.ini");

            var disable = language.Equals("jp-JP", StringComparison.OrdinalIgnoreCase);

            if (language != "zh-CN" && language != "zh-TW")
            {
                language = language.Split('-')[0];
            }

            try
            {
                var contents = (File.Exists(configPath) ? File.ReadAllLines(configPath) : Enumerable.Empty <string>()).ToList();

                {
                    var categoryIndex = contents.FindIndex(s => s.ToLower().Contains("[General]".ToLower()));
                    if (categoryIndex >= 0)
                    {
                        var i = contents.FindIndex(categoryIndex, s => s.StartsWith("Language"));
                        if (i > categoryIndex)
                        {
                            contents[i] = $"Language={language}";
                        }
                        else
                        {
                            contents.Insert(categoryIndex + 1, $"Language={language}");
                        }
                    }
                    else
                    {
                        contents.Add("");
                        contents.Add("[General]");
                        contents.Add($"Language={language}");
                    }
                }

                {
                    var categoryIndex = contents.FindIndex(s => s.ToLower().Contains("[Service]".ToLower()));
                    if (categoryIndex >= 0)
                    {
                        var i = contents.FindIndex(categoryIndex, s => s.StartsWith("Endpoint"));
                        if (i > categoryIndex)
                        {
                            contents[i] = disable ? "Endpoint=" : "Endpoint=GoogleTranslate";
                        }
                        else
                        {
                            contents.Insert(categoryIndex + 1, disable ? "Endpoint=" : "Endpoint=GoogleTranslate");
                        }
                    }
                    else
                    {
                        contents.Add("");
                        contents.Add("[Service]");
                        contents.Add(disable ? "Endpoint=" : "Endpoint=GoogleTranslate");
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(configPath));
                File.WriteAllLines(configPath, contents.ToArray());
            }
            catch (Exception e)
            {
                MessageBox.Show("Something went wrong when writing AutoTranslator config file: " + e);
            }
        }
Exemple #5
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            if (revit.JournalData != null &&
                revit.JournalData.ContainsKey("debug"))
            {
                if (bool.Parse(revit.JournalData["debug"]))
                {
                    Debugger.Launch();
                }
            }

            AppDomain.CurrentDomain.AssemblyResolve += Analyze.Render.AssemblyHelper.ResolveAssemblies;

            //Add an assembly load step for the System.Windows.Interactivity assembly
            //Revit owns a version of this as well. Adding our step here prevents a duplicative
            //load of the dll at a later time.
            var interactivityPath = Path.Combine(DynamoPaths.MainExecPath, "System.Windows.Interactivity.dll");

            if (File.Exists(interactivityPath))
            {
                Assembly.LoadFrom(interactivityPath);
            }

            DynamoRevitApp.dynamoButton.Enabled = false;

            try
            {
                #region default level

                var fecLevel = new FilteredElementCollector(revit.Application.ActiveUIDocument.Document);
                fecLevel.OfClass(typeof(Level));
                var defaultLevel = fecLevel.ToElements()[0] as Level;

                #endregion

                var logger = new DynamoLogger();
                dynSettings.DynamoLogger = logger;

                if (DocumentManager.Instance.CurrentUIApplication == null)
                {
                    DocumentManager.Instance.CurrentUIApplication = revit.Application;
                }

                DocumentManager.OnLogError += dynSettings.DynamoLogger.Log;

                dynRevitSettings.DefaultLevel = defaultLevel;

                //TODO: has to be changed when we handle multiple docs
                Updater = new RevitServicesUpdater(DynamoRevitApp.ControlledApplication, DynamoRevitApp.Updaters);
                Updater.ElementAddedForID += ElementMappingCache.GetInstance().WatcherMethodForAdd;
                Updater.ElementsDeleted   += ElementMappingCache.GetInstance().WatcherMethodForDelete;

                RevThread.IdlePromise.ExecuteOnIdleAsync(
                    delegate
                {
                    //get window handle
                    IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;

                    var r          = new Regex(@"\b(Autodesk |Structure |MEP |Architecture )\b");
                    string context = r.Replace(revit.Application.Application.VersionName, "");

                    //they changed the application version name conventions for vasari
                    //it no longer has a version year so we can't compare it to other versions
                    //TODO:come up with a more stable way to test for Vasari beta 3
                    if (context == "Vasari")
                    {
                        context = "Vasari 2014";
                    }

                    dynamoController = CreateDynamoRevitControllerAndViewModel(Updater, logger, context);

                    var dynamoView = new DynamoView {
                        DataContext = dynamoController.DynamoViewModel
                    };
                    dynamoController.UIDispatcher = dynamoView.Dispatcher;

                    //set window handle and show dynamo
                    new WindowInteropHelper(dynamoView).Owner = mwHandle;

                    handledCrash = false;

                    dynamoView.Show();

                    if (revit.JournalData != null &&
                        revit.JournalData.ContainsKey("dynPath"))
                    {
                        dynamoController.DynamoModel.OpenWorkspace(revit.JournalData["dynPath"]);
                    }

                    dynamoView.Dispatcher.UnhandledException += DispatcherOnUnhandledException;
                    dynamoView.Closing += dynamoView_Closing;
                    dynamoView.Closed  += dynamoView_Closed;

                    revit.Application.ViewActivating += Application_ViewActivating;
                });
            }
            catch (Exception ex)
            {
                //isRunning = false;
                MessageBox.Show(ex.ToString());

                dynSettings.DynamoLogger.LogError(ex.Message);
                dynSettings.DynamoLogger.LogError(ex.StackTrace);
                dynSettings.DynamoLogger.LogError("Dynamo log ended " + DateTime.Now);

                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Exemple #6
0
        //internal void BuildFileNameDataTable()
        //{
        //    FileNameDataTable = new DataTable("DrwgFileNameData");

        //    #region DataTable Definition
        //    DataColumn column;

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._Number.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._Title.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._FileNameFormat.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._Scale.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._Date.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._Revision.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._RevisionDate.ColumnName;
        //    FileNameDataTable.Columns.Add(column);

        //    column = new DataColumn();
        //    column.DataType = typeof(string);
        //    column.ColumnName = fs._Extension.ColumnName;
        //    FileNameDataTable.Columns.Add(column);
        //    #endregion
        //}
        //internal void PopulateFileNameDataTable()
        //{
        //    foreach (Drwg drwg in drwgListFiles)
        //    {
        //        DataRow row = FileNameDataTable.NewRow();

        //        row[fs._Number.ColumnName] = drwg.GetValue(Source.FileName, FieldName.Number);
        //        row[fs._Title.ColumnName] = drwg.GetValue(Source.FileName, FieldName.Title);
        //        row[fs._FileNameFormat.ColumnName] = drwg.GetValue(Source.FileName, FieldName.FileNameFormat);
        //        row[fs._Revision.ColumnName] = drwg.GetValue(Source.FileName, FieldName.Revision);
        //        row[fs._Extension.ColumnName] = drwg.GetValue(Source.FileName, FieldName.Extension);

        //        FileNameDataTable.Rows.Add(row);
        //    }
        //    FileNameDataTable.AcceptChanges();
        //}
        internal void ScanExcelFile(string pathToDwgList)
        {
            //Fields for Excel Interop
            Microsoft.Office.Interop.Excel.Workbook    wb;
            Microsoft.Office.Interop.Excel.Sheets      wss;
            Microsoft.Office.Interop.Excel.Worksheet   ws;
            Microsoft.Office.Interop.Excel.Application oXL;
            object misVal = System.Reflection.Missing.Value;

            oXL               = new Microsoft.Office.Interop.Excel.Application();
            oXL.Visible       = false;
            oXL.DisplayAlerts = false;
            wb = oXL.Workbooks.Open(pathToDwgList, 0, false, 5, "", "", false,
                                    Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, false, false,
                                    Microsoft.Office.Interop.Excel.XlCorruptLoad.xlNormalLoad);

            wss = wb.Worksheets;
            ws  = (Microsoft.Office.Interop.Excel.Worksheet)wss.Item[1];

            Range usedRange   = ws.UsedRange;
            int   usedRows    = usedRange.Rows.Count;
            int   usedCols    = usedRange.Columns.Count;
            int   rowStartIdx = 0;
            //Detect first row of the drawingslist
            //Assumes that Drawing data starts with a field containing string "Tegningsnr." -- subject to change
            string firstColumnValue = "Tegningsnr."; //<-- Here be the string that triggers the start of data.

            for (int row = 1; row < usedRows + 1; row++)
            {
                var cellValue = (string)(ws.Cells[row, 1] as Range).Value;
                if (cellValue == firstColumnValue)
                {
                    rowStartIdx = row; break;
                }
            }

            if (rowStartIdx == 0)
            {
                MsgBox.Show($"Excel file did not find a cell in the first column\n" +
                            $"containing the first column keyword: {firstColumnValue}");
                return;
            }

            //int lastColIdx = fs.GetAllFields().MaxBy(x => x.ExcelColumnIdx).Select(x => x.ExcelColumnIdx).FirstOrDefault();
            //Range drwgUsedRange = oXL.Range[ws.Cells[rowStartIdx, 1], ws.Cells[usedRows, lastColIdx]];

            //myRange.Select();
            //MsgBox.Show(myRange.Address);

            #region BuildDataTableFromExcel
            ExcelDataSet = new DataSet("ExcelDrwgData");
            DataTable table = null;

            //Main loop creating DataTables for DataSet
            for (int i = rowStartIdx; i < usedRows + 1; i++)
            {
                //Detect start of the table
                var cellValue = (string)(ws.Cells[i, 1] as Range).Value;
                if (cellValue == firstColumnValue) //Header row detected
                {
                    //Add previously made dataTable to dataSet except at the first iteration
                    if (i != rowStartIdx)
                    {
                        ExcelDataSet.Tables.Add(table);
                    }

                    //Get the name of DataTable
                    string nameOfDt = (string)(ws.Cells[i, 2] as Range).Value;
                    table = new DataTable(nameOfDt);

                    //Add the header values to the column names
                    DataColumn column;
                    for (int j = 1; j < usedCols + 1; j++)
                    {
                        cellValue         = (string)(ws.Cells[i, j] as Range).Value;
                        column            = new DataColumn();
                        column.DataType   = typeof(string);
                        column.ColumnName = fs.GetExcelColumnField(j).ColumnName;
                        table.Columns.Add(column);
                        //MsgBox.Show(cellValue);
                    }
                }
                else
                {
                    DataRow row = table.NewRow();

                    for (int j = 1; j < usedCols + 1; j++)
                    {
                        string value;
                        var    cellValueRaw = (ws.Cells[i, j] as Range).Value;
                        if (cellValueRaw == null)
                        {
                            value = "";
                        }
                        else if (cellValueRaw is string)
                        {
                            value = (string)cellValueRaw;
                        }
                        else
                        {
                            value = cellValueRaw.ToString();
                        }
                        row[j - 1] = value;
                    }
                    table.Rows.Add(row);
                }
            }
            //Add last made data table to data set.
            ExcelDataSet.Tables.Add(table);
            ExcelDataSet.AcceptChanges();
            #endregion

            wb.Close(true, misVal, misVal);
            oXL.Quit();
        }
        public void ShowDialog(VFVideoCaptureOutputFormat format, IWin32Window parent, VideoCaptureCore core)
        {
            switch (format)
            {
            case VFVideoCaptureOutputFormat.AVI:
            {
                if (aviSettingsDialog == null)
                {
                    aviSettingsDialog = new AVISettingsDialog(core.Video_Codecs().ToArray(), core.Audio_Codecs().ToArray());
                }

                aviSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.WMV:
            {
                if (wmvSettingsDialog == null)
                {
                    wmvSettingsDialog = new WMVSettingsDialog(core);
                }

                wmvSettingsDialog.WMA = false;
                wmvSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.DV:
            {
                if (dvSettingsDialog == null)
                {
                    dvSettingsDialog = new DVSettingsDialog();
                }

                dvSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.MKVv1:
            {
                if (mkvSettingsDialog == null)
                {
                    mkvSettingsDialog = new AVISettingsDialog(core.Video_Codecs().ToArray(), core.Audio_Codecs().ToArray());
                }

                mkvSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.PCM_ACM:
            {
                if (pcmSettingsDialog == null)
                {
                    pcmSettingsDialog = new PCMSettingsDialog(core.Audio_Codecs().ToArray());
                }

                pcmSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.WMA:
            {
                if (wmaSettingsDialog == null)
                {
                    wmaSettingsDialog = new WMVSettingsDialog(core);
                }

                wmaSettingsDialog.WMA = true;
                wmaSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.MP3:
            {
                if (mp3SettingsDialog == null)
                {
                    mp3SettingsDialog = new MP3SettingsDialog();
                }

                mp3SettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.Custom:
            {
                if (customFormatSettingsDialog == null)
                {
                    customFormatSettingsDialog = new CustomFormatSettingsDialog(core.Video_Codecs().ToArray(), core.Audio_Codecs().ToArray(), core.DirectShow_Filters().ToArray());
                }

                customFormatSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.DirectCaptureDV:
            case VFVideoCaptureOutputFormat.DirectCaptureMPEG:
            case VFVideoCaptureOutputFormat.DirectCaptureAVI:
            case VFVideoCaptureOutputFormat.DirectCaptureMKV:
            {
                MessageBox.Show("No settings available for selected output format.");

                break;
            }

            case VFVideoCaptureOutputFormat.FFMPEG_DLL:
            {
                if (ffmpegDLLSettingsDialog == null)
                {
                    ffmpegDLLSettingsDialog = new FFMPEGDLLSettingsDialog();
                }

                ffmpegDLLSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.WebM:
            {
                if (webmSettingsDialog == null)
                {
                    webmSettingsDialog = new WebMSettingsDialog();
                }

                webmSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.DirectCaptureMP4_GDCL:
            case VFVideoCaptureOutputFormat.DirectCaptureMP4_Monogram:
            {
                MessageBox.Show("No settings available for selected output format.");

                break;
            }

            case VFVideoCaptureOutputFormat.DirectCaptureCustom:
            {
                if (customFormatSettingsDialog == null)
                {
                    customFormatSettingsDialog = new CustomFormatSettingsDialog(core.Video_Codecs().ToArray(), core.Audio_Codecs().ToArray(), core.DirectShow_Filters().ToArray());
                }

                customFormatSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.MP4_CUDA:
            {
                if (mp4V10SettingsDialog == null)
                {
                    mp4V10SettingsDialog = new MP4v10SettingsDialog();
                }

                mp4V10SettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.MP4v8v10:
            {
                if (mp4V10SettingsDialog == null)
                {
                    mp4V10SettingsDialog = new MP4v10SettingsDialog();
                }

                mp4V10SettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.MP4v11:
            {
                if (mfSettingsDialog == null)
                {
                    mfSettingsDialog = new MFSettingsDialog(MFSettingsDialogMode.MP4v11);
                }

                mfSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.Encrypted:
            {
                if (mp4V10SettingsDialog == null)
                {
                    mp4V10SettingsDialog = new MP4v10SettingsDialog();
                }

                mp4V10SettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.FLAC:
            {
                if (flacSettingsDialog == null)
                {
                    flacSettingsDialog = new FLACSettingsDialog();
                }

                flacSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.OggVorbis:
            {
                if (oggVorbisSettingsDialog == null)
                {
                    oggVorbisSettingsDialog = new OggVorbisSettingsDialog();
                }

                oggVorbisSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.Speex:
            {
                if (speexSettingsDialog == null)
                {
                    speexSettingsDialog = new SpeexSettingsDialog();
                }

                speexSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.FFMPEG_EXE:
            {
                if (ffmpegEXESettingsDialog == null)
                {
                    ffmpegEXESettingsDialog = new FFMPEGEXESettingsDialog();
                }

                ffmpegEXESettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.M4A:
            {
                if (m4aSettingsDialog == null)
                {
                    m4aSettingsDialog = new M4ASettingsDialog();
                }

                m4aSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.AnimatedGIF:
            {
                if (gifSettingsDialog == null)
                {
                    gifSettingsDialog = new GIFSettingsDialog();
                }

                gifSettingsDialog.ShowDialog(parent);

                break;
            }

            case VFVideoCaptureOutputFormat.VLC_EXE:
            {
                MessageBox.Show("No settings available for selected output format.");

                break;
            }

            default:
                throw new ArgumentOutOfRangeException(nameof(format), format, null);
            }
        }
Exemple #8
0
        /// <summary>
        /// Load a Character and open the correct window.
        /// </summary>
        /// <param name="strFileName">File to load.</param>
        /// <param name="blnIncludeInMRU">Whether or not the file should appear in the MRU list.</param>
        /// <param name="strNewName">New name for the character.</param>
        /// <param name="blnClearFileName">Whether or not the name of the save file should be cleared.</param>
        public void LoadCharacter(string strFileName, bool blnIncludeInMRU = true, string strNewName = "", bool blnClearFileName = false)
        {
            if (File.Exists(strFileName) && strFileName.EndsWith("chum5"))
            {
                Timekeeper.Start("loading");
                bool      blnLoaded    = false;
                Character objCharacter = new Character();
                objCharacter.FileName = strFileName;

                XmlDocument objXmlDocument = new XmlDocument();
                //StreamReader is used to prevent encoding errors
                using (StreamReader sr = new StreamReader(strFileName, true))
                {
                    objXmlDocument.Load(sr);
                }
                XmlNode objXmlCharacter = objXmlDocument.SelectSingleNode("/character");
                if (!string.IsNullOrEmpty(objXmlCharacter?["appversion"]?.InnerText))
                {
                    Version verSavedVersion;
                    Version verCorrectedVersion;
                    string  strVersion = objXmlCharacter["appversion"].InnerText;
                    if (strVersion.StartsWith("0."))
                    {
                        strVersion = strVersion.Substring(2);
                    }
                    Version.TryParse(strVersion, out verSavedVersion);
                    Version.TryParse("5.188.34", out verCorrectedVersion);
                    int intResult = verSavedVersion.CompareTo(verCorrectedVersion);
                    //Check for typo in Corrupter quality and correct it
                    if (intResult == -1)
                    {
                        File.WriteAllText(strFileName, Regex.Replace(File.ReadAllText(strFileName), "Corruptor", "Corrupter"));
                    }
                }

                Timekeeper.Start("load_file");
                blnLoaded = objCharacter.Load();
                Timekeeper.Finish("load_file");
                Timekeeper.Start("load_free");
                if (!blnLoaded)
                {
                    return;
                }

                // If a new name is given, set the character's name to match (used in cloning).
                if (!string.IsNullOrEmpty(strNewName))
                {
                    objCharacter.Name = strNewName;
                }
                // Clear the File Name field so that this does not accidentally overwrite the original save file (used in cloning).
                if (blnClearFileName)
                {
                    objCharacter.FileName = string.Empty;
                }

                // Show the character form.
                if (!objCharacter.Created)
                {
                    frmCreate frmCharacter = new frmCreate(objCharacter)
                    {
                        MdiParent   = this,
                        WindowState = FormWindowState.Maximized,
                        Loading     = true
                    };
                    frmCharacter.Show();
                }
                else
                {
                    frmCareer frmCharacter = new frmCareer(objCharacter)
                    {
                        MdiParent   = this,
                        WindowState = FormWindowState.Maximized,
                        Loading     = true
                    };
                    frmCharacter.DiceRollerOpened    += objCareer_DiceRollerOpened;
                    frmCharacter.DiceRollerOpenedInt += objCareer_DiceRollerOpenedInt;
                    frmCharacter.Show();
                }

                if (blnIncludeInMRU)
                {
                    GlobalOptions.Instance.AddToMRUList(strFileName);
                }

                objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
                objCharacter_CharacterNameChanged(objCharacter);
            }
            else
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_FileNotFound").Replace("{0}", strFileName), LanguageManager.Instance.GetString("MessageTitle_FileNotFound"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #9
0
 private void objCareer_DiceRollerOpened(Object sender)
 {
     MessageBox.Show("This feature is currently disabled. Please open a ticket if this makes the world burn, otherwise it will get re-enabled when somebody gets around to it");
     //TODO: IMPLEMENT THIS SHIT
 }
Exemple #10
0
        private void StartButton_Click(object sender, RoutedEventArgs e)
        {
            string accountName = this.username_textbox.Text;
            string password    = this.password_box.Password;

            if (CommonUtils.IsEmptyString(accountName))
            {
                MessageBox.Show("User Name or Password cannot be empty!", "Error");
                return;
            }

            List <ShareSettings> sharesSettings = this.GetShareSettings();

            if (sharesSettings == null || sharesSettings.Count == 0)
            {
                MessageBox.Show("Please add directories for sharing!", "Error");
                return;
            }

            int port = SettingsHelper.DefaultPort;

            try
            {
                port = int.Parse(this.port_textbox.Text);
                SettingsHelper.WriteServerPort(port);
            }
            catch
            {
                MessageBox.Show("Invalid port number!", "Error");
                return;
            }

            UserCollection users = new UserCollection();

            users.Add(new User(accountName, password));
            // Save account if necessary
            if (this.NeedUpdateUserCollection())
            {
                SettingsHelper.WriteUserSettings(users);
            }

            bool runAsService = this.service_checkbox.IsChecked ?? false;

            if (runAsService)
            {
                if (!this.IsInAdminRole())
                {
                    MessageBox.Show("To start the service, please run application as administrator.", "Info");
                    return;
                }

                try
                {
                    ServiceController serviceController = new ServiceController("RedfishService");
                    serviceController.Start();
                    this.start_button.IsEnabled = false;
                    this.stop_button.IsEnabled  = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
            else
            {
                KeyValuePair <string, IPAddress> selectedValue = (KeyValuePair <string, IPAddress>) this.address_combobox.SelectedValue;
                IPAddress        serverAddress = selectedValue.Value;
                SMBTransportType transportType = SMBTransportType.DirectTCPTransport;

                NTLMAuthenticationProviderBase authenticationMechanism = new IndependentNTLMAuthenticationProvider(users.GetUserPassword);

                SMBShareCollection shares = new SMBShareCollection();
                foreach (ShareSettings shareSettings in sharesSettings)
                {
                    FileSystemShare share = shareSettings.InitializeShare();
                    shares.Add(share);
                }

                GSSProvider securityProvider = new GSSProvider(authenticationMechanism);
                m_server    = new SMBLibrary.Server.SMBServer(shares, securityProvider);
                m_logWriter = new LogWriter();
                // The provided logging mechanism will synchronously write to the disk during server activity.
                // To maximize server performance, you can disable logging by commenting out the following line.
                m_server.LogEntryAdded += new EventHandler <LogEntry>(m_logWriter.OnLogEntryAdded);

                try
                {
                    SMBServer.DirectTCPPort = port;
                    m_server.Start(serverAddress, transportType);
                    if (transportType == SMBTransportType.NetBiosOverTCP)
                    {
                        if (serverAddress.AddressFamily == AddressFamily.InterNetwork && !IPAddress.Equals(serverAddress, IPAddress.Any))
                        {
                            IPAddress subnetMask = NetworkInterfaceHelper.GetSubnetMask(serverAddress);
                            m_nameServer = new NameServer(serverAddress, subnetMask);
                            m_nameServer.Start();
                        }
                    }

                    this.start_button.IsEnabled = false;
                    this.stop_button.IsEnabled  = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error");
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Create a new character and show the Create Form.
        /// </summary>
        private void ShowNewForm(object sender, EventArgs e)
        {
            string strFilePath = Path.Combine(Application.StartupPath, "settings", "default.xml");

            if (!File.Exists(strFilePath))
            {
                if (MessageBox.Show(LanguageManager.Instance.GetString("Message_CharacterOptions_OpenOptions"), LanguageManager.Instance.GetString("MessageTitle_CharacterOptions_OpenOptions"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    frmOptions frmOptions = new frmOptions();
                    frmOptions.ShowDialog();
                }
            }
            Character objCharacter = new Character();
            string    settingsPath = Path.Combine(Application.StartupPath, "settings");

            string[] settingsFiles = Directory.GetFiles(settingsPath, "*.xml");

            if (settingsFiles.Length > 1)
            {
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = settingsFiles[0];
                objCharacter.SettingsFile = Path.GetFileName(strSettingsFile);
            }

            // Show the BP selection window.
            frmSelectBuildMethod frmBP = new frmSelectBuildMethod(objCharacter);

            frmBP.ShowDialog();

            if (frmBP.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            if (objCharacter.BuildMethod == CharacterBuildMethod.Karma || objCharacter.BuildMethod == CharacterBuildMethod.LifeModule)
            {
                frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            // Show the Metatype selection window.
            else if (objCharacter.BuildMethod == CharacterBuildMethod.Priority || objCharacter.BuildMethod == CharacterBuildMethod.SumtoTen)
            {
                frmPriorityMetatype frmSelectMetatype = new frmPriorityMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }

            // Add the Unarmed Attack Weapon to the character.
            XmlDocument objXmlDocument = XmlManager.Instance.Load("weapons.xml");
            XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]");

            if (objXmlWeapon != null)
            {
                TreeNode objDummy  = new TreeNode();
                Weapon   objWeapon = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, objCharacter, objDummy, null, null);
                objCharacter.Weapons.Add(objWeapon);
            }

            frmCreate frmNewCharacter = new frmCreate(objCharacter);

            frmNewCharacter.MdiParent   = this;
            frmNewCharacter.WindowState = FormWindowState.Maximized;
            frmNewCharacter.Show();

            OpenCharacters.Add(objCharacter);
            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
        }
 private void _lnkHelpFields_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     MessageBox.Show(this, _helpMessage, Resources.TitleHelpSpecialFields);
 }
Exemple #13
0
 private void FormMenu_Load_1(object sender, EventArgs e)
 {
     MessageBox.Show("Bienvenido/a al sistema", "TEJAGG", MessageBoxButtons.OK, MessageBoxIcon.Information);
     BtnIni_Click(null, e);
     CargaUser();
 }
        public MainWindow()
        {
            try
            {
                _suppressEvents = true;

                // Initialize code -------------------------------------
                EnvironmentHelper.Initialize(_builtinLanguages);

                _mainGameExists = File.Exists(EnvironmentHelper.GameRootDirectory + ExecutableGame);
                _studioExists   = File.Exists(EnvironmentHelper.GameRootDirectory + ExecutableStudio);

                if (_studioExists)
                {
                    SettingManager.Initialize(EnvironmentHelper.GetConfigFilePath(), RegistryKeyGame, RegistryKeyStudio);
                }
                else
                {
                    SettingManager.Initialize(EnvironmentHelper.GetConfigFilePath(), RegistryKeyGame);
                }

                SettingManager.LoadSettings();

                // Initialize interface --------------------------------
                InitializeComponent();

                WindowStartupLocation = WindowStartupLocation.CenterScreen;
                CustomRes.Visibility  = Visibility.Hidden;

                if (string.IsNullOrEmpty((string)labelTranslated.Content))
                {
                    labelTranslated.Visibility       = Visibility.Hidden;
                    labelTranslatedBorder.Visibility = Visibility.Hidden;
                }

                if (!EnvironmentHelper.KKmanExist)
                {
                    gridUpdate.Visibility = Visibility.Hidden;
                }

                // Launcher Customization: Defining Warning, background and character
                if (!string.IsNullOrEmpty(EnvironmentHelper.VersionString))
                {
                    labelDist.Content = EnvironmentHelper.VersionString;
                }

                if (!string.IsNullOrEmpty(EnvironmentHelper.WarningString))
                {
                    warningText.Text = EnvironmentHelper.WarningString;
                }

                if (EnvironmentHelper.CustomCharacterImage != null)
                {
                    PackChara.Source = EnvironmentHelper.CustomCharacterImage;
                }
                if (EnvironmentHelper.CustomBgImage != null)
                {
                    appBG.ImageSource = EnvironmentHelper.CustomBgImage;
                }


                var primaryDisplay = Localizable.PrimaryDisplay;
                var subDisplay     = Localizable.SubDisplay;
                for (var i = 0; i < Screen.AllScreens.Length; i++)
                {
                    // 0 is primary
                    var newItem = i == 0 ? primaryDisplay : $"{subDisplay} : " + i;
                    dropDisplay.Items.Add(newItem);
                }

                PluginToggleManager.CreatePluginToggles(Toggleables);

                _suppressEvents = false;

                UpdateDisplaySettings(SettingManager.CurrentSettings.FullScreen);

                Closed    += (sender, args) => SettingManager.SaveSettings();
                MouseDown += (sender, args) => { if (args.ChangedButton == MouseButton.Left)
                                                 {
                                                     DragMove();
                                                 }
                };
                buttonClose.Click += (sender, args) => Close();
            }
            catch (Exception e)
            {
                MessageBox.Show("Failed to start the launcher, please consider reporting this error to the developers.\n\nError that caused the crash: " + e, "Launcher crash", MessageBoxButtons.OK, MessageBoxIcon.Error);
                File.WriteAllText(Path.Combine(EnvironmentHelper.GameRootDirectory, "launcher_crash.log"), e.ToString());
                Close();
            }
        }
Exemple #15
0
        //Commision Dialog Host Accept
        public void ADD_COMMISSION_ACCEPT_BUTTON_Click(object sender, RoutedEventArgs e)
        {
            title    = COMMISSION_Title.Text;
            cost     = "$" + COMMISSION_Cost.Text;
            client   = COMMISSION_Client.Text;
            deadline = COMMISSION_Deadline.Text;
            notes    = COMMISSION_Notes.Text;

            if (COMMISSION_Title.Text == "")
            {
                COMMISSION_Title.Foreground = Brushes.Yellow;
            }
            else if (COMMISSION_Title.Text != "")
            {
                COMMISSION_Title.Foreground = Brushes.Black;
            }

            if (COMMISSION_Cost.Text == "")
            {
                COMMISSION_Cost.Foreground = Brushes.Red;
            }
            else if (COMMISSION_Cost.Text != "")
            {
                COMMISSION_Cost.Foreground = Brushes.Black;
            }

            if (COMMISSION_Client.Text == "")
            {
                COMMISSION_Client.Foreground = Brushes.Red;;
            }
            else if (COMMISSION_Client.Text != "")
            {
                COMMISSION_Client.Foreground = Brushes.Black;
            }

            if (COMMISSION_Deadline.Text == "")
            {
                COMMISSION_Deadline.Foreground = Brushes.Red;;
            }
            else if (COMMISSION_Deadline.Text != "")
            {
                COMMISSION_Deadline.Foreground = Brushes.Black;
            }

            if (op.FileName == "")
            {
                op.FileName = @"Resources\Profile_Unknown.png";
            }

            MessageBox.Show(op.FileName);

            if (title != "")
            {
                if (cost != "")
                {
                    if (client != "")
                    {
                        if (deadline != "")
                        {
                            DialogHost.CloseDialogCommand.Execute(new object(), null);
                            instances.compage.lstbox_commission.Items.Add(new TodoItem()
                            {
                                Title = title, Completion = 45, Cost = cost, Client = client, Deadline = deadline, Notes = notes, imagepath = op.FileName, outline = setoutlinecolour, setcolour = Brushes.White
                            });
                            txt_warning.Visibility = Visibility.Hidden;
                            op.FileName            = "";
                        }
                    }
                }
            }
            else
            {
                txt_warning.Visibility = Visibility.Visible;
            }

            //savexml();
        }
Exemple #16
0
        private void LoadConnection(object sender, DoWorkEventArgs e)
        {
            if (_clientChangelogDownloader.IsBusy)
            {
                return;
            }
            bool   blnChummerVersionGotten = true;
            string strError = LanguageManager.GetString("String_Error", GlobalOptions.Language).Trim();

            _strExceptionString = string.Empty;
            LatestVersion       = strError;
            string strUpdateLocation = _blnPreferNightly
                ? "https://api.github.com/repos/chummer5a/chummer5a/releases"
                : "https://api.github.com/repos/chummer5a/chummer5a/releases/latest";

            HttpWebRequest request = null;

            try
            {
                WebRequest objTemp = WebRequest.Create(strUpdateLocation);
                request = objTemp as HttpWebRequest;
            }
            catch (System.Security.SecurityException)
            {
                blnChummerVersionGotten = false;
            }
            if (request == null)
            {
                blnChummerVersionGotten = false;
            }
            if (blnChummerVersionGotten)
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)";
                request.Accept    = "application/json";
                request.Timeout   = 5000;

                // Get the response.
                HttpWebResponse response = null;
                try
                {
                    response = request.GetResponse() as HttpWebResponse;
                }
                catch (WebException ex)
                {
                    blnChummerVersionGotten = false;
                    string strException       = ex.ToString();
                    int    intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (intNewLineLocation == -1)
                    {
                        intNewLineLocation = strException.IndexOf('\n');
                    }
                    if (intNewLineLocation != -1)
                    {
                        strException = strException.Substring(0, intNewLineLocation);
                    }
                    _strExceptionString = strException;
                }

                if (_workerConnectionLoader.CancellationPending)
                {
                    e.Cancel = true;
                    response?.Close();
                    return;
                }

                // Get the stream containing content returned by the server.
                Stream dataStream = response?.GetResponseStream();
                if (dataStream == null)
                {
                    blnChummerVersionGotten = false;
                }
                if (blnChummerVersionGotten)
                {
                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        dataStream.Close();
                        response.Close();
                        return;
                    }
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream, Encoding.UTF8, true);
                    // Read the content.

                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        reader.Close();
                        response.Close();
                        return;
                    }

                    string responseFromServer = reader.ReadToEnd();

                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        reader.Close();
                        response.Close();
                        return;
                    }

                    string[] stringSeparators = { "," };

                    if (_workerConnectionLoader.CancellationPending)
                    {
                        e.Cancel = true;
                        reader.Close();
                        response.Close();
                        return;
                    }

                    string[] result = responseFromServer.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                    bool blnFoundTag     = false;
                    bool blnFoundArchive = false;
                    foreach (string line in result)
                    {
                        if (_workerConnectionLoader.CancellationPending)
                        {
                            e.Cancel = true;
                            reader.Close();
                            response.Close();
                            return;
                        }
                        if (!blnFoundTag && line.Contains("tag_name"))
                        {
                            _strLatestVersion = line.Split(':')[1];
                            LatestVersion     = _strLatestVersion.Split('}')[0].FastEscape('\"').Trim();
                            blnFoundTag       = true;
                            if (blnFoundArchive)
                            {
                                break;
                            }
                        }
                        if (!blnFoundArchive && line.Contains("browser_download_url"))
                        {
                            _strDownloadFile = line.Split(':')[2];
                            _strDownloadFile = _strDownloadFile.Substring(2);
                            _strDownloadFile = _strDownloadFile.Split('}')[0].FastEscape('\"');
                            _strDownloadFile = "https://" + _strDownloadFile;
                            blnFoundArchive  = true;
                            if (blnFoundTag)
                            {
                                break;
                            }
                        }
                    }
                    if (!blnFoundArchive || !blnFoundTag)
                    {
                        blnChummerVersionGotten = false;
                    }
                    // Cleanup the streams and the response.
                    reader.Close();
                }
                dataStream?.Close();
                response?.Close();
            }
            if (!blnChummerVersionGotten || LatestVersion == strError)
            {
                MessageBox.Show(
                    string.IsNullOrEmpty(_strExceptionString)
                        ? LanguageManager.GetString("Warning_Update_CouldNotConnect", GlobalOptions.Language)
                        : string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), _strExceptionString), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                _blnIsConnected = false;
                e.Cancel        = true;
            }
            else
            {
                if (File.Exists(_strTempUpdatePath))
                {
                    if (File.Exists(_strTempUpdatePath + ".old"))
                    {
                        File.Delete(_strTempUpdatePath + ".old");
                    }
                    File.Move(_strTempUpdatePath, _strTempUpdatePath + ".old");
                }
                string strURL = "https://raw.githubusercontent.com/chummer5a/chummer5a/" + LatestVersion + "/Chummer/changelog.txt";
                try
                {
                    Uri uriConnectionAddress = new Uri(strURL);
                    if (File.Exists(_strTempUpdatePath + ".tmp"))
                    {
                        File.Delete(_strTempUpdatePath + ".tmp");
                    }
                    _clientChangelogDownloader.DownloadFileAsync(uriConnectionAddress, _strTempUpdatePath + ".tmp");
                    while (_clientChangelogDownloader.IsBusy)
                    {
                        if (_workerConnectionLoader.CancellationPending)
                        {
                            _clientChangelogDownloader.CancelAsync();
                            e.Cancel = true;
                            return;
                        }
                    }
                    File.Move(_strTempUpdatePath + ".tmp", _strTempUpdatePath);
                }
                catch (WebException ex)
                {
                    string strException       = ex.ToString();
                    int    intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (intNewLineLocation == -1)
                    {
                        intNewLineLocation = strException.IndexOf('\n');
                    }
                    if (intNewLineLocation != -1)
                    {
                        strException = strException.Substring(0, intNewLineLocation);
                    }
                    _strExceptionString = strException;
                    MessageBox.Show(string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), strException), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _blnIsConnected = false;
                    e.Cancel        = true;
                }
                catch (UriFormatException ex)
                {
                    string strException       = ex.ToString();
                    int    intNewLineLocation = strException.IndexOf(Environment.NewLine, StringComparison.Ordinal);
                    if (intNewLineLocation == -1)
                    {
                        intNewLineLocation = strException.IndexOf('\n');
                    }
                    if (intNewLineLocation != -1)
                    {
                        strException = strException.Substring(0, intNewLineLocation);
                    }
                    _strExceptionString = strException;
                    MessageBox.Show(string.Format(LanguageManager.GetString("Warning_Update_CouldNotConnectException", GlobalOptions.Language), strException), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _blnIsConnected = false;
                    e.Cancel        = true;
                }
            }
        }
Exemple #17
0
    void Update()
    {
        //整体初始位置
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        //从摄像机发出到点击坐标的射线
        RaycastHit hitInfo;

        if (Input.GetMouseButtonDown(0))
        {
            if (Physics.Raycast(ray, out hitInfo))
            {
                //划出射线,只有在scene视图中才能看到
                Debug.DrawLine(ray.origin, hitInfo.point);
                if (cishu == 0)
                {
                    go      = hitInfo.collider.gameObject;
                    btnName = go.name;
                    print(btnName);
                    cishu++;

                    if (GameObject.Find(btnName).tag == "good")
                    {
                        MsgBoxBase.Show("该部件完好", GetType().Name, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Asterisk);
                        score1 = score.ToString();
                        print(score1);
                        RawImage Score = GameObject.Find(score1).GetComponent <RawImage>();
                        Score.color = Color.white;
                        score       = score - 10;
                        cishu--;
                    }
                }
                else if (cishu == 1)
                {
                    go1      = hitInfo.collider.gameObject;
                    btnName1 = go1.name;
                    if (btnName.Equals(btnName1))
                    {
                        num_shengyu--;
                        num_bad--;
                        if (num_bad == 0)
                        {
                            GameObject gos;
                            gos       = GameObject.Find("zhuban/zhuban");
                            gos.layer = LayerMask.NameToLayer("Default");
                        }
                        go.layer  = LayerMask.NameToLayer("Ignore Raycast");
                        go1.layer = LayerMask.NameToLayer("Ignore Raycast");
                        if (go.name.Equals("cpu"))
                        {
                            GameObject gos;
                            gos       = GameObject.Find("zhuban/zhuban/sanreqi");
                            gos.layer = LayerMask.NameToLayer("Default");
                        }

                        GameObject gof;                        //判断两个物体设谁动;
                        gof = go1.transform.parent.gameObject;
                        if (gof.name == "jixiang")
                        {
                            go.transform.position = go1.transform.position;
                        }
                        if (gof.name.Equals("zhuban"))
                        {
                            if (go.name.Equals("xianka"))
                            {
                                go.transform.rotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);
                            }
                            go.transform.position = go1.transform.position;
                        }
                        else
                        {
                            if (go1.name.Equals("xianka"))
                            {
                                go1.transform.rotation = Quaternion.Euler(0.0f, 180.0f, 360.0f);
                            }
                            go1.transform.position = go.transform.position;
                        }
                    }
                    else
                    {
                        print("shibai");
                    }
                    if (num_shengyu == 0)
                    {
                        print(num_shengyu);
                        score1 = score.ToString();
                        MsgBoxBase.Show("故障已排除,你的得分:" + score1, GetType().Name, WinForms.MessageBoxButtons.OK, WinForms.MessageBoxIcon.Asterisk);
                        lurufenshu.jilu("Assets/fenshu", "guzahng5.txt", score);
                        SceneManager.LoadScene(7);
                    }
                    cishu = 0;
                    print(num_shengyu);
                }
            }
        }
    }
        private void FillPatternTriangle(Bitmap cbmp, Triangle t, Matrix4x4 M)
        {
            int N = t.vertices.Length;
            var P = t.vertices.ToList();

            List <ActiveEdge> AET = new List <ActiveEdge>();

            int[] indices = new int[N];
            for (int j = 0; j < N; j++)
            {
                indices[j] = j;
            }

            indices = BubbleSortVertices(indices, P);

            int k = 0;
            int i = indices[k];

            int y = (int)P[indices[0]].pv.Y;

            int ymin = (int)P[indices[0]].pv.Y;
            int ymax = (int)P[indices[N - 1]].pv.Y;

            while (y != ymax)
            {
                while ((int)P[i].pv.Y == y)
                {
                    if (P[((i - 1) % N + N) % N].pv.Y > P[i].pv.Y)
                    {
                        ActiveEdge newEdge = new ActiveEdge(P[((i - 1) % N + N) % N].pv, P[i].pv, P[((i - 1) % N + N) % N], P[i]);
                        if (!newEdge.horizontal)
                        {
                            AET.Add(newEdge);
                        }
                    }
                    if (P[((i + 1) % N + N) % N].pv.Y > P[i].pv.Y)
                    {
                        ActiveEdge newEdge = new ActiveEdge(P[((i + 1) % N + N) % N].pv, P[i].pv, P[((i + 1) % N + N) % N], P[i]);
                        if (!newEdge.horizontal)
                        {
                            AET.Add(newEdge);
                        }
                    }

                    ++k;
                    i = indices[k];
                }

                AET = AET.OrderBy(e => e.x).ToList();

                if (y != ymin)
                {
                    for (int j = 0; j < AET.Count; j += 2)
                    {
                        if (j + 1 < AET.Count)
                        {
                            for (int x = (int)AET[j].x + 1; x < (int)AET[j + 1].x; x++)
                            {
                                //Vector2 textureCoord = TextureCoordToTexturePixel()

                                try
                                {
                                    cbmp.SetPixel(x, y, texture.GetPixel(dx, dy));
                                }
                                catch
                                {
                                    if (x < 0)
                                    {
                                        x *= -1;
                                    }
                                    cbmp.SetPixel(x % width, y, System.Drawing.Color.Red);
                                    MessageBox.Show("Error drawing");
                                    //MessageBox.Show(AET[j].x + " " + AET[j].ymax + "\n" + AET[j+1].x + " " + AET[j+1].ymax);
                                    //MessageBox.Show(AET[j].up.pv.X + " " + AET[j].up.pv.Y + "\n" +
                                    //                AET[j].down.pv.X + " " + AET[j].down.pv.Y + "\n" +
                                    //                AET[j+1].up.pv.X + " " + AET[j+1].up.pv.Y + "\n" +
                                    //                AET[j+1].down.pv.X + " " + AET[j+1].down.pv.Y);
                                }
                            }
                        }
                    }
                }

                y++;

                AET.RemoveAll(e => e.ymax == y);

                foreach (var edge in AET)
                {
                    edge.x += edge.m;
                }
            }
        }
        private async void bJoinGroup_Click(object sender, EventArgs e)
        {
            if (MyCE == null)
            {
                return;
            }
            if (tvGroupSearchResult.SelectedNode == null)
            {
                return;
            }

            try
            {
                using (new CursorWait(false, this))
                {
                    SINnerSearchGroup item = tvGroupSearchResult.SelectedNode.Tag as SINnerSearchGroup;
                    if (MyCE.MySINnerFile.MyGroup != null)
                    {
                        await LeaveGroupTask(MyCE.MySINnerFile, MyCE.MySINnerFile.MyGroup, item != null);
                    }

                    if (item == null)
                    {
                        return;
                    }

                    //var uploadtask = MyCE.Upload();
                    //await uploadtask.ContinueWith(b =>
                    //{
                    using (new CursorWait(false, this))
                    {
                        var task = JoinGroupTask(item, MyCE);
                        await task.ContinueWith(a =>
                        {
                            using (new CursorWait(false, this))
                            {
                                if (a.IsFaulted)
                                {
                                    string msg = "JoinGroupTask returned faulted!";
                                    if ((a.Exception != null) && (a.Exception is AggregateException))
                                    {
                                        msg = "";
                                        foreach (var exp in (a.Exception as AggregateException).InnerExceptions)
                                        {
                                            msg += exp.Message + Environment.NewLine;
                                        }
                                    }
                                    else
                                    {
                                        if (a.Exception != null)
                                        {
                                            msg = a.Exception.Message;
                                        }
                                    }

                                    MessageBox.Show(msg);
                                    return;
                                }

                                if (!String.IsNullOrEmpty(a.Result?.ErrorText))
                                {
                                    Log.Error(a.Result.ErrorText);
                                }
                                else if (a.Result == null)
                                {
                                    MyCE.MySINnerFile.MyGroup = null;
                                    string msg = "Char " + MyCE.MyCharacter.CharacterName + " did not join group " +
                                                 item.Groupname +
                                                 ".";
                                    Log.Info(msg);
                                    this.DoThreadSafe(() =>
                                    {
                                        MessageBox.Show(msg, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        TlpGroupSearch_VisibleChanged(null, new EventArgs());
                                    });
                                }
                                else
                                {
                                    MyCE.MySINnerFile.MyGroup = new SINnerGroup(item);
                                    //if (OnGroupJoinCallback != null)
                                    //    OnGroupJoinCallback(this, MyCE.MySINnerFile.MyGroup);
                                    string msg = "Char " + MyCE.MyCharacter.CharacterName + " joined group " +
                                                 item.Groupname +
                                                 ".";
                                    Log.Info(msg);
                                    this.DoThreadSafe(() =>
                                    {
                                        MessageBox.Show(msg, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        TlpGroupSearch_VisibleChanged(null, new EventArgs());
                                    });
                                    PluginHandler.MainForm.CharacterRoster.DoThreadSafe(() =>
                                    {
                                        PluginHandler.MainForm.CharacterRoster.LoadCharacters(false, false, false, true);
                                    });
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
        }
Exemple #20
0
 private void ShowPromptNotImplement()
 {
     MessageBox.Show("501 Not Implemented:\n    非常抱歉,该功能正在上线中,敬请期待!", "Coming soon!", MessageBoxButtons.OK, MessageBoxIcon.Stop);
 }
        public static void SetLanguage(string language)
        {
            try
            {
                using (var writetext = new StreamWriter(GameRootDirectory + _mCustomDir + _decideLang, false))
                    writetext.WriteLine(language);

                string LangQ_a = "Do you want to set the ingame language to the selected language as well?";
                string LangQ_b = "Question";

                switch (language)
                {
                case "ja-JP":
                    LangQ_a = "ゲームにこの言語の選択を反映させたいですか?";
                    LangQ_b = "質問";
                    break;

                case "zh-CN":
                    LangQ_a = "您是否希望游戏中的语言反映这项语言选择?";
                    LangQ_b = "问题";
                    break;

                case "zh-TW":
                    LangQ_a = "您是否希望遊戲中的語言反映這項語言選擇?";
                    LangQ_b = "問題";
                    break;

                case "ko-KR":
                    LangQ_a = "게임 언어를 선택한 언어로 설정 하시겠습니까?";
                    LangQ_b = "질문";
                    break;

                case "es-ES":
                    LangQ_a = "¿Desea configurar el idioma del juego al idioma seleccionado también?";
                    LangQ_b = "Pregunta";
                    break;

                case "pt-PT":
                    LangQ_a = "Deseja também definir o idioma do jogo para o idioma selecionado?";
                    LangQ_b = "Questão";
                    break;

                case "fr-FR":
                    LangQ_a = "Voulez-vous également définir la langue du jeu sur la langue sélectionnée?";
                    LangQ_b = "Question";
                    break;

                case "de-DE":
                    LangQ_a = "Möchten Sie die Spielsprache auch auf die ausgewählte Sprache einstellen?";
                    LangQ_b = "Frage";
                    break;

                case "no-NB":
                    LangQ_a = "Ønsker du å endre språket i spillet også?";
                    LangQ_b = "Spørsmål";
                    break;

                default:
                    LangQ_a = "Do you want to set the ingame language to the selected language as well?";
                    LangQ_b = "Question";
                    break;
                }

                if (System.Windows.MessageBox.Show(LangQ_a,
                                                   LangQ_b, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    var builtinIndex = _builtinLanguages.ToList()
                                       .FindIndex(x => language.Equals(x, StringComparison.OrdinalIgnoreCase));

                    // Set built-in game language if supported
                    if (builtinIndex >= 0)
                    {
                        SettingManager.CurrentSettings.Language = builtinIndex;
                        SettingManager.SaveSettings();
                    }
                    else
                    {
                        MessageBox.Show(Localizable.InstructDecideLang);
                    }

                    WriteAutoTranslatorLangIni(language);
                }

                Application.Restart();
            }
            catch (Exception e)
            {
                MessageBox.Show("Something went wrong when changing language: " + e);
            }
        }
 //說明->傳送意見反應
 private void Some_idear(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("不可以有意見", "想要提供意見嗎?");
 }
        public static void Initialize(string[] builtinLanguages)
        {
            _builtinLanguages = builtinLanguages ?? throw new ArgumentNullException(nameof(builtinLanguages));

            InitializeDirectories();
            InitializeLanguage();
            CheckDuplicateStartup();

            // Framework test
            IsIpa   = File.Exists($"{GameRootDirectory}\\IPA.exe");
            IsBepIn = Directory.Exists($"{GameRootDirectory}\\BepInEx");

            if (IsIpa && IsBepIn)
            {
                MessageBox.Show(
                    "Both BepInEx and IPA is detected in the game folder!\n\nApplying both frameworks may cause permanent problems when running the game, making a reinstall needed. Consider uninstalling IPA and using the BepInEx.IPALoader plugin to run your IPA plugins instead.\n\nExiting launcher.",
                    "Critical!");

                System.Windows.Application.Current.Shutdown();
            }

            // Updater / kkmanager
            try
            {
                var kkmanFileDir = Path.GetFullPath(GameRootDirectory + _mCustomDir + _kkmdir);
                // If config file doesn't exist try to find kkmanager inside of game directory
                if (!File.Exists(kkmanFileDir))
                {
                    var f = Directory.GetFiles(GameRootDirectory, "KKManager.exe", SearchOption.AllDirectories)
                            .Select(Path.GetDirectoryName)
                            .Select(x => x.Substring(GameRootDirectory.Length).Trim('\\', '/'))
                            .FirstOrDefault();
                    File.WriteAllText(kkmanFileDir, f ?? string.Empty, Encoding.UTF8);
                }

                // Figure out where kkmanager is installed
                var kkmanpath = File.ReadAllLines(kkmanFileDir, Encoding.UTF8)
                                .FirstOrDefault(x => !string.IsNullOrEmpty(x));
                if (!string.IsNullOrEmpty(kkmanpath))
                {
                    kkmanpath = kkmanpath.Trim('\\', '/');
                    if (!Path.IsPathRooted(kkmanpath))
                    {
                        var rootedPath = Path.GetFullPath(GameRootDirectory + '\\' + kkmanpath);
                        kkmanpath = Directory.Exists(rootedPath) ? rootedPath : Path.GetFullPath(kkmanpath);
                    }
                }

                if (Directory.Exists(kkmanpath))
                {
                    _kkmanagerDirectory = kkmanpath;
                }
                else
                {
                    File.Delete(kkmanFileDir);
                }

                if (KKmanExist)
                {
                    var updatecfgPath = Path.Combine(GameRootDirectory, _mCustomDir + _updateLoc);
                    _updateSourcesOverride = File.Exists(updatecfgPath)
                        ? File.ReadAllLines(updatecfgPath, Encoding.UTF8).FirstOrDefault(x => !string.IsNullOrEmpty(x))
                        : null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Failed to initialize KKManager, please consider reporting this error to developers.\n\n" + ex,
                    "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            if (GameRootDirectory.Length >= 75)
            {
                MessageBox.Show(
                    "The game is installed deep in the file system!\n\nThis can cause a variety of errors, so it's recommended that you move it to a shorter path, something like:\n\nC:\\Illusion\\AI.Shoujo",
                    "Critical warning!");
            }

            // Customization options

            var versionPath = Path.GetFullPath(GameRootDirectory + _versioningLoc);

            if (File.Exists(versionPath))
            {
                var verFileStream = new FileStream(versionPath, FileMode.Open, FileAccess.Read);
                using (var streamReader = new StreamReader(verFileStream, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        VersionString = line;
                    }
                }

                verFileStream.Close();
            }

            var warningExists = File.Exists(GameRootDirectory + _mCustomDir + _warningLoc);

            if (warningExists)
            {
                try
                {
                    using (var sr = new StreamReader(GameRootDirectory + _mCustomDir + _warningLoc))
                    {
                        var line = sr.ReadToEnd();
                        WarningString = line;
                    }
                }
                catch (IOException e)
                {
                    WarningString = e.Message;
                }
            }

            var charExists = File.Exists(GameRootDirectory + _mCustomDir + _charLoc);

            if (charExists)
            {
                var urich = new Uri(GameRootDirectory + _mCustomDir + _charLoc, UriKind.RelativeOrAbsolute);
                CustomCharacterImage = BitmapFrame.Create(urich);
            }

            var backgExists = File.Exists(GameRootDirectory + _mCustomDir + _backgLoc);

            if (backgExists)
            {
                var uribg = new Uri(GameRootDirectory + _mCustomDir + _backgLoc, UriKind.RelativeOrAbsolute);
                CustomBgImage = BitmapFrame.Create(uribg);
            }

            var patreonExists = File.Exists(GameRootDirectory + _mCustomDir + _patreonLoc);

            if (patreonExists)
            {
                var verFileStream = new FileStream(GameRootDirectory + _mCustomDir + _patreonLoc, FileMode.Open,
                                                   FileAccess.Read);
                using (var streamReader = new StreamReader(verFileStream, Encoding.UTF8))
                {
                    string line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        PatreonUrl = line;
                    }
                }

                verFileStream.Close();
            }
        }
Exemple #24
0
 /// <summary>
 /// Displays the message as an information box.
 /// </summary>
 /// <param name="s">String message.</param>
 public static void Show(string s)
 {
     //ESITracer.Current.LogInfo(s);
     WinMessageBox.Show(null, s, "Relatório", MessageBoxButtons.OK, MessageBoxIcon.Information);
 }
Exemple #25
0
        public Result Execute(ExternalCommandData revit, ref string message, ElementSet elements)
        {
            AppDomain.CurrentDomain.AssemblyResolve += Dynamo.Utilities.AssemblyHelper.CurrentDomain_AssemblyResolve;

            //Add an assembly load step for the System.Windows.Interactivity assembly
            //Revit owns a version of this as well. Adding our step here prevents a duplicative
            //load of the dll at a later time.
            var assLoc            = Assembly.GetExecutingAssembly().Location;
            var interactivityPath = Path.Combine(Path.GetDirectoryName(assLoc), "System.Windows.Interactivity.dll");
            var interactivityAss  = Assembly.LoadFrom(interactivityPath);

            //When a user double-clicks the Dynamo icon, we need to make
            //sure that we don't create another instance of Dynamo.
            if (isRunning)
            {
                Debug.WriteLine("Dynamo is already running.");
                if (dynamoView != null)
                {
                    dynamoView.Focus();
                }
                return(Result.Succeeded);
            }

            isRunning = true;

            try
            {
                m_revit = revit.Application;
                m_doc   = m_revit.ActiveUIDocument;

                #region default level

                Level defaultLevel = null;
                var   fecLevel     = new FilteredElementCollector(m_doc.Document);
                fecLevel.OfClass(typeof(Level));
                defaultLevel = fecLevel.ToElements()[0] as Level;

                #endregion

                dynRevitSettings.Revit        = m_revit;
                dynRevitSettings.Doc          = m_doc;
                dynRevitSettings.DefaultLevel = defaultLevel;

                IdlePromise.ExecuteOnIdle(delegate
                {
                    //get window handle
                    IntPtr mwHandle = Process.GetCurrentProcess().MainWindowHandle;

                    Regex r        = new Regex(@"\b(Autodesk |Structure |MEP |Architecture )\b");
                    string context = r.Replace(m_revit.Application.VersionName, "");

                    //they changed the application version name conventions for vasari
                    //it no longer has a version year so we can't compare it to other versions
                    //TODO:come up with a more stable way to test for Vasari beta 3
                    if (context == "Vasari")
                    {
                        context = "Vasari 2014";
                    }

                    dynamoController = new DynamoController_Revit(DynamoRevitApp.env, DynamoRevitApp.Updater, typeof(DynamoRevitViewModel), context);

                    dynamoView = new DynamoView {
                        DataContext = dynamoController.DynamoViewModel
                    };
                    dynamoController.UIDispatcher = dynamoView.Dispatcher;

                    //set window handle and show dynamo
                    new WindowInteropHelper(dynamoView).Owner = mwHandle;

                    handledCrash = false;

                    dynamoView.WindowStartupLocation = WindowStartupLocation.Manual;

                    Rectangle bounds  = Screen.PrimaryScreen.Bounds;
                    dynamoView.Left   = dynamoViewX ?? bounds.X;
                    dynamoView.Top    = dynamoViewY ?? bounds.Y;
                    dynamoView.Width  = dynamoViewWidth ?? 1000.0;
                    dynamoView.Height = dynamoViewHeight ?? 800.0;

                    dynamoView.Show();

                    dynamoView.Dispatcher.UnhandledException -= DispatcherOnUnhandledException;
                    dynamoView.Dispatcher.UnhandledException += DispatcherOnUnhandledException;
                    dynamoView.Closing += dynamoView_Closing;
                    dynamoView.Closed  += dynamoView_Closed;

                    //revit.Application.ViewActivated += new EventHandler<Autodesk.Revit.UI.Events.ViewActivatedEventArgs>(Application_ViewActivated);
                    revit.Application.ViewActivating += Application_ViewActivating;
                });
            }
            catch (Exception ex)
            {
                isRunning = false;
                MessageBox.Show(ex.ToString());

                DynamoLogger.Instance.Log(ex.Message);
                DynamoLogger.Instance.Log(ex.StackTrace);
                DynamoLogger.Instance.Log("Dynamo log ended " + DateTime.Now.ToString());

                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Exemple #26
0
 /// <summary>
 /// Displays the message as an error box.
 /// </summary>
 /// <param name="s">String message.</param>
 public static void ShowError(string s)
 {
     //ESITracer.Current.LogError(s);
     WinMessageBox.Show(null, s, "Relatório", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
Exemple #27
0
        private void patchBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (!File.Exists(this.exePath + ".bak"))
                {
                    File.Copy(this.exePath, this.exePath + ".bak");
                    this.backupBtn.Visible = true;
                }

                var resultSb = new StringBuilder("Patcher v2 :: Created by Zaczero\r\n\r\nPatch results:\r\n");
                var buffer   = File.ReadAllBytes(this.exePath);

                if (this.zoomOutCbox.Checked)
                {
                    if (ZoomOut.Process(ref buffer))
                    {
                        resultSb.AppendLine("ZoomHack (max) --> Success");
                    }
                    else
                    {
                        resultSb.AppendLine("ZoomHack (max) --> Fail");
                    }
                }

                if (this.zoomInCbox.Checked)
                {
                    if (ZoomIn.Process(ref buffer))
                    {
                        resultSb.AppendLine("ZoomHack (min) --> Success");
                    }
                    else
                    {
                        resultSb.AppendLine("ZoomHack (min) --> Fail");
                    }
                }

                if (this.oomCbox.Checked)
                {
                    if (OOM.Process(ref buffer))
                    {
                        resultSb.AppendLine("OOM --> Success");
                    }
                    else
                    {
                        resultSb.AppendLine("OOM --> Fail");
                    }
                }

                if (this.fovCbox.Checked)
                {
                    if (FOV.Process(ref buffer))
                    {
                        resultSb.AppendLine("FOV Changer --> Success");
                    }
                    else
                    {
                        resultSb.AppendLine("FOV Changer --> Fail");
                    }
                }

                if (this.topViewCbox.Checked)
                {
                    if (TopView.Process(ref buffer))
                    {
                        resultSb.AppendLine("TOP View --> Success");
                    }
                    else
                    {
                        resultSb.AppendLine("TOP View --> Fail");
                    }
                }

                resultSb.Append("\r\nIf any of these failed, here are the possible reasons:\r\n* Already patched\r\n* Patcher is outdated");

                File.WriteAllBytes(this.exePath, buffer);
                MessageBox.Show(resultSb.ToString(), "Patcher", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // MsgBox
                MessageBox.Show("Patch failed!\r\n" + ex.Message + "\r\n\r\nPossible solutions:\r\n* Run as administrator\r\n* Pause anti-virus\r\n* Exit all LoL processes", "Patcher", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #28
0
 public static DialogResult ShowWarningOK(string s)
 {
     //ESITracer.Current.LogError(s);
     return(WinMessageBox.Show(null, s, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning));
 }
Exemple #29
0
        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="window"></param>
        private void UploadHeaderPic(Window window)
        {
            OpenFileDialog openFileDialog = null;
            FileStream     fileStream     = null;

            try
            {
                openFileDialog        = new OpenFileDialog();
                openFileDialog.Filter = "(png,jpg,bmp)|*.png;*.jpg;*.bmp";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    FileInfo info          = new FileInfo(openFileDialog.FileName);
                    var      fileExtension = info.Extension;
                    if (!info.Exists)
                    {
                        ShowTip("文件不存在", window);
                        return;
                    }
                    if (fileExtension == ".png" || fileExtension == ".jpg" || fileExtension == ".bmp")
                    {
                        using (fileStream = new FileStream(openFileDialog.FileName, FileMode.Open))
                        {
                            //判断照片的大小
                            if (info.Length > 1048576)
                            {
                                ShowTip("图片大于1M", window);
                                return;
                            }
                            Bitmap bitmap      = new Bitmap(fileStream);
                            var    newFileName = (info.Name.Split('.'))[0] + "_" + Guid.NewGuid().ToString() + fileExtension;
                            //var root = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;
                            bitmap.Save(@"HeaderPic/" + newFileName);
                            if (window is EditUser)
                            {
                                EditUserData.Icon = @"HeaderPic/" + newFileName;
                            }
                            else if (window is AddUser)
                            {
                                AddUserData.Icon = @"HeaderPic/" + newFileName;
                            }
                            else if (window is Home)
                            {
                                (window.DataContext as HomeViewModel).User.Icon = @"HeaderPic/" + newFileName;
                            }

                            //EditUserData.ImaSource = new BitmapImage(new Uri(@"/Image/" + newFileName, UriKind.Relative));
                            ShowTip("上传成功", window);
                        }
                    }
                    else
                    {
                        ShowTip("请选择正确的图像文件", window);
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                openFileDialog.Dispose();
                fileStream.Close();
                fileStream.Dispose();
                MessageBox.Show(e.Message);
            }
        }
Exemple #30
0
        private void LoadStructure_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                Model model = null;

                StringBuilder sb = new StringBuilder();
                sb.Append("All molecule files (*.mol, *.sdf, *.cml)|*.mol;*.sdf;*.cml");
                sb.Append("|CML molecule files (*.cml)|*.cml");
                sb.Append("|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf");

                openFileDialog1.Title            = "Open Structure";
                openFileDialog1.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
                openFileDialog1.Filter           = sb.ToString();
                openFileDialog1.FileName         = "";
                openFileDialog1.ShowHelp         = false;

                DialogResult dr = openFileDialog1.ShowDialog();

                if (dr == DialogResult.OK)
                {
                    string fileType = Path.GetExtension(openFileDialog1.FileName).ToLower();
                    string filename = Path.GetFileName(openFileDialog1.FileName);
                    string mol      = File.ReadAllText(openFileDialog1.FileName);

                    CMLConverter    cmlConvertor    = new CMLConverter();
                    SdFileConverter sdFileConverter = new SdFileConverter();

                    switch (fileType)
                    {
                    case ".mol":
                    case ".sdf":
                        model = sdFileConverter.Import(mol);
                        break;

                    case ".cml":
                    case ".xml":
                        model = cmlConvertor.Import(mol);
                        break;
                    }

                    if (model != null)
                    {
                        model.EnsureBondLength(20, false);
                        if (string.IsNullOrEmpty(model.CustomXmlPartGuid))
                        {
                            model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                        }

                        if (!string.IsNullOrEmpty(_lastCml))
                        {
                            var clone = cmlConvertor.Import(_lastCml);
                            Debug.WriteLine(
                                $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack");
                            _undoStack.Push(clone);
                        }

                        _lastCml = cmlConvertor.Export(model);

                        _telemetry.Write(module, "Information", $"File: {filename}");
                        ShowChemistry(filename, model);
                    }
                }
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }