Example #1
0
 public void Create()
 {
     Close();
     frm = new LoadingForm();
     loadingThread = new Thread(s => Application.Run(frm));
     loadingThread.Start();
 }
		void Search_btnClick(object sender, EventArgs e)
		{
			if(search_textBox.Text != "")
			{
				LoadingForm load_frm = new LoadingForm();
				
				load_frm.StartPosition = FormStartPosition.CenterScreen;
				load_frm.Show();
				load_frm.Update();

				WebClient webClient = new WebClient();
				
				Debug.WriteLine(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, search_textBox.Text));
				load_frm.Update();
				string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, search_textBox.Text));
				load_frm.Update();
			    var jsonData = JObject.Parse(result);
			    load_frm.Update();
			    //logger_richTextBox.AppendText(jsonData["items"].ToString());
			    load_frm.Update();
			    logger_richTextBox.Clear();
			    load_frm.Update();
			    int link_counter = 1;
			    foreach(JObject obj in (JArray)jsonData["items"])
			    {
			    	load_frm.Update();
			    	logger_richTextBox.AppendText("لينك" + link_counter + ": " + obj["link"].ToString() + Environment.NewLine);
			    	link_counter++;
			    	load_frm.Update();
			    }
			    load_frm.Update();
			    load_frm.Close();
			}
			
		}
 private async void PerformEncode()
 {
     //====================================
     LoadingForm loadingform = new LoadingForm("Encoding File into Base64");
     this.Enabled = false;
     loadingform.Show(this);
     //====================================
     this._EncodedValue = await TestController.EncodeBase64Async(this.txtParameterValue.Text);
     //====================================
     loadingform.Close();
     this.Enabled = true;
     this.Focus();
 }
Example #4
0
        public void Start()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            logger.InfoFormat("Start");

            try
            {
                var loadingForm = new LoadingForm();
                loadingForm.Start();

                var builder = new ContainerBuilder();
                builder.RegisterModule(new NHibernateModule());
                builder.RegisterModule(new EventStoreModule());
                builder.RegisterModule(new ProjectModule());
                builder.RegisterModule(new CatalogModule());
                builder.RegisterModule(new ChiffrageModule());

                var container = builder.Build();

                container.Resolve<CatalogSessionManagerService>();
                container.Resolve<ProjectSessionManagerService>();

                this.eventBroker = container.Resolve<IEventBroker>();
                this.eventBroker.Start();

                loadingForm.Stop();

                var applicationForm = container.Resolve<IApplicationView>();

                this.eventBroker.Publish(new ApplicationStartAction(), Topics.UI);

                Application.Run((ApplicationForm)applicationForm);
                this.eventBroker.Stop();
            }
            catch (Exception ex)
            {
                logger.Fatal("Fatal error", ex);
                Application.OnThreadException(ex);
                if (this.eventBroker != null)
                {
                    this.eventBroker.Stop();
                }
            }
        }
Example #5
0
        public void LoadLevel(string path)
        {
            UnloadLevel();
            LoadedLevel = new Level(path, -1);
            //Populate szs file list
            int index = 0;
            List <ToolStripMenuItem> Files = new List <ToolStripMenuItem>();

            foreach (var f in LoadedLevel.SzsFiles)
            {
                ToolStripMenuItem btn = new ToolStripMenuItem();
                btn.Name   = "LoadFile" + index.ToString();
                btn.Text   = f.Key;
                btn.Click += OpenSzsFile_click;
                Files.Add(btn);
                index++;
            }
            OtherLevelDataMenu.DropDownItems.AddRange(Files.ToArray());
            //LoadedLevel.OpenBymlViewer();
            //Load models
            LoadingForm.ShowLoading(this, "Loading models...\r\nOpening a level for the first time will take longer");
            foreach (string k in LoadedLevel.objs.Keys.ToArray())
            {
                LoadObjListModels(LoadedLevel.objs[k], k);
            }
            if (LoadedLevel.HasList("AreaList"))
            {
                HideList(LoadedLevel.objs["AreaList"], true);
            }
            if (LoadedLevel.HasList("SkyList"))
            {
                HideList(LoadedLevel.objs["SkyList"], true);
            }
            HideGroup_CB.CheckedChanged += HideGroup_CB_CheckedChanged;
            //Populate combobox
            comboBox1.Items.AddRange(LoadedLevel.objs.Keys.ToArray());
            comboBox1.SelectedIndex         = 0;
            splitContainer2.Enabled         = true;
            findToolStripMenuItem.Visible   = true;
            saveAsToolStripMenuItem.Enabled = true;
            saveToolStripMenuItem.Enabled   = true;
            LoadingForm.EndLoading();
        }
Example #6
0
        public form1()
        {
            InitializeComponent();

            //   doWork();
            dataSourceManager = new DataSourceManager();
            LoadingForm loadingForm = new LoadingForm();

            loadingForm.Show();
            var getBeaconMacTask = dataSourceManager.upDateBeaconQue();
            var getPhoneMacTask  = dataSourceManager.upDatePhoneMac();

            Task.WaitAll(getBeaconMacTask, getPhoneMacTask);
            loadingForm.Close();
            this.WindowState = FormWindowState.Maximized;
            Console.WriteLine("Done");

            //initForm();
        }
        protected virtual void InvokeAction()
        {
            LoadingForm loadingForm = null;

            if (willUseLoading)
            {
                loadingForm = new LoadingForm();
                loadingForm.StartPosition = FormStartPosition.CenterParent;
                loadingForm.Show();
                loadingForm.Top  = parent.Top + ((parent.Height / 2) - (loadingForm.Height / 2));
                loadingForm.Left = parent.Left + ((parent.Width / 2) - (loadingForm.Width / 2));
                loadingForm.Refresh();
            }
            formAction.Invoke(GetThis());
            if (willUseLoading)
            {
                loadingForm.Close();
            }
        }
Example #8
0
            public static bool PutDown()
            {
                if (handle == IntPtr.Zero)
                {
                    return(true);
                }
                LoadingForm splash        = LoadingForm.Create("Disconnecting from \"" + FriendlyName + "\" ...");
                uint        bytesReturned = 0;
                IntPtr      pBuffer       = Marshal.AllocHGlobal(4);

                Marshal.Copy(BitConverter.GetBytes(0), 0, pBuffer, 4);
                bool deviceStatus = Kernel32.DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, pBuffer, 4, pBuffer, 4, ref bytesReturned, IntPtr.Zero);

                Marshal.FreeHGlobal(pBuffer);
                Kernel32.CloseHandle(handle);
                handle = IntPtr.Zero;
                splash.Stop();
                return(deviceStatus);
            }
        // |---------------Métodos Públicos---------------|

        public void EjecutarTareaEnSegundoPlano(Boolean displayLoadingForm, Object obj, String asyncMethod, String finishCallback, params String[] parameters)
        {
            this.obj            = obj;
            this.asyncMethod    = asyncMethod;
            this.finishCallback = finishCallback;

            bgWorker = new BackgroundWorker();
            bgWorker.RunWorkerCompleted        += BgWorker_RunWorkerCompleted;
            bgWorker.DoWork                    += BgWorker_DoWork;
            bgWorker.WorkerSupportsCancellation = false;

            if (displayLoadingForm)
            {
                (loadingForm = new LoadingForm()).Show();
            }


            bgWorker.RunWorkerAsync();
        }
Example #10
0
        private LoadingForm ShowSplash(string rom)
        {
            if (rom == null)
            {
                return(null);
            }

            if (Misc.IsWindowsEightOrTen && !Misc.IsDeveloperModeEnabled)
            {
                var controller = Controllers.FirstOrDefault(c => c.PlayerIndex == 1 && c.Config != null && c.Config.Type != "keyboard");
                if (controller != null)
                {
                    LoadingForm frm = new LoadingForm();
                    frm.WarningText = "Warning : Future Pinball requires developper mode enabled in Windows settings";
                    frm.Show();
                }
            }

            return(null);
        }
Example #11
0
        private void ReloadResults()
        {
            if (_grid.Rows.Count > _grid.FixedRows)
            {
                _grid.Rows.RemoveRange(_grid.FixedRows, _grid.Rows.Count - _grid.FixedRows);
            }

            _resultSets.Clear();

            LoadingForm.Show(this, async p =>
            {
                p.LoadingText = $"Loading {Constants.PageSize} results...";

                _query = _api.CreateQuery(_entity);
                _query.Filters.AddRange(_filters);
                _query.Count = Constants.PageSize;

                LoadResultSet(await _query.ExecuteReaderAsync());
            });
        }
Example #12
0
        static void Main()
        {
            if (CheckInternet() == false)
            {
                DialogResult dialog = dialog = MessageBox.Show("Błąd połączenia z internetem! Połączenie internetowe jest niezbędne do uruchomienia tego programu. W celu ustalenia problemów z łączem internetowym skontaktuj się ze swoim dostawcą internetowym w celu wykrycia przyczyny awarii.", "Scruter", MessageBoxButtons.OK);
                Application.Exit();
            }

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

            FormsController formsController = FormsControllerImpl.GetInstance();

            MainForm.MainForm mainForm = formsController.GetMainForm();

            LoadingForm loadingForm = new LoadingForm();

            loadingForm.StartDownload(true);

            Application.Run(mainForm);
        }
Example #13
0
 private async Task<bool> processParallelSynchronization(DateTime? pDrawDate = null, long pDrawType = 0, int pSyncType = 0)
 {
     this.setSyncStatusText(LabelConstants.SYNC_PENDING_TRANSACTIONS_LABEL_TEXT);
     this.displaySyncStatusComponents(true);
     LoadingForm loading = new LoadingForm();
     loading.Show(this);
     SynchronizeService service = new SynchronizeService();
     bool syncResult = await service.syncPendingListNumberToServerAsync(pDrawDate, pDrawType);
     this.setSyncStatusText(LabelConstants.COMPLETED_SYNC_TRANSACTIONS_LABEL_TEXT);
     loading.Dispose();
     if (syncResult)
     {
         MessageService.displayInfoMessage("La sincronización ha finalizado de manera exitosa", "RESULTADO DE LA SINCRONIZACIÓN");
     }
     else
     {
         MessageService.displayErrorMessage("No fue posible realizar la sincronización.\nPor favor intente más tarde.", "RESULTADO DE LA SINCRONIZACIÓN");
     }
     this.displaySyncStatusComponents(false);
     return syncResult;
 }
Example #14
0
        public void FormLoaded()
        {
            if (!Directory.Exists(ModelsFolder))
            {
                Directory.CreateDirectory(ModelsFolder);
                ZipArchive z = new ZipArchive(new MemoryStream(Properties.Resources.baseModels));
                z.ExtractToDirectory(ModelsFolder);
            }
            if (!Directory.Exists($"{ModelsFolder}/GameTextures"))
            {
                if (GameFolder == "" || !Directory.Exists(GameFolder))
                {
                    MessageBox.Show("The game path is not set or not valid, can't extract texture archives");
                }
                else
                {
                    MessageBox.Show($"The game texture archives will be extracted in {ModelsFolder}/GameTextures, this might take a while");
                    LoadingForm.ShowLoading(ViewForm as Form, "Extracting textures...\r\nThis might take a while");
                    foreach (var a in Directory.GetFiles($"{GameFolder}ObjectData\\").Where(x => x.EndsWith("Texture.szs")))
                    {
                        BfresLib.BfresConverter.GetTextures(
                            BfresFromSzs(Path.GetFileNameWithoutExtension(a)),
                            ModelsFolder);
                    }
                    LoadingForm.EndLoading();
                }
            }

            if (ObjsDB == null)
            {
                if (File.Exists(ModelsFolder + "/OdysseyDB.json"))
                {
                    ObjsDB = ObjectDatabase.Deserialize(File.ReadAllText(ModelsFolder + "/OdysseyDB.json"));
                }
                else
                {
                    ObjsDB = ObjectDatabase.Deserialize(Properties.Resources.OdysseyDB);
                }
            }
        }
Example #15
0
        public ReportPresenter(Connection conn, IReportParametersForm parameters, IMainForm mainForm, Report report)
        {
            this.conn                         = conn;
            this.parameters                   = parameters;
            this.mainForm                     = mainForm;
            this.report                       = report;
            parameters.OK                    += view_OK;
            this.worker                       = new BackgroundWorker();
            this.worker.DoWork               += new DoWorkEventHandler(OnExecuteReport);
            this.worker.RunWorkerCompleted   += new RunWorkerCompletedEventHandler(OnCompleteReport);
            this.worker.WorkerReportsProgress = true;

            var lf = new LoadingForm
            {
                WaitForThis = new Task(() =>
                {
                    InitExport();
                })
            };

            lf.ShowDialog();
        }
Example #16
0
        public override System.Diagnostics.ProcessStartInfo Generate(string system, string emulator, string core, string rom, string playersControllers, ScreenResolution resolution)
        {
            string path = AppConfig.GetFullPath("fpinball");

            _rom    = rom;
            _splash = ShowSplash(rom);

            if ("bam".Equals(emulator, StringComparison.InvariantCultureIgnoreCase) || "bam".Equals(core, StringComparison.InvariantCultureIgnoreCase))
            {
                _bam = Path.Combine(path, "BAM", "FPLoader.exe");
            }

            string exe = Path.Combine(path, "Future Pinball.exe");

            if (!File.Exists(exe))
            {
                exe = Path.Combine(path, "FuturePinball.exe");
                if (!File.Exists(exe))
                {
                    return(null);
                }
            }

            if (_bam != null && File.Exists(_bam))
            {
                ScreenResolution.SetHighDpiAware(_bam);
            }

            ScreenResolution.SetHighDpiAware(exe);

            SetupOptions(resolution);

            return(new ProcessStartInfo()
            {
                FileName = _bam != null && File.Exists(_bam) ? _bam : exe,
                Arguments = "/open \"" + rom + "\" /play /exit",
            });
        }
        public ReportDesignerPresenter(
            Connection conn, IMainForm mainForm, IReportDesignerForm view, Report reportData)
        {
            this.conn                         = conn;
            this.mainForm                     = mainForm;
            this.view                         = view;
            this.reportData                   = reportData;
            this.worker                       = new BackgroundWorker();
            this.worker.DoWork               += new DoWorkEventHandler(OnExecuteReport);
            this.worker.RunWorkerCompleted   += new RunWorkerCompletedEventHandler(OnCompleteReport);
            this.worker.WorkerReportsProgress = true;
            view.CreateReport                += view_CreateReport;

            var lf = new LoadingForm
            {
                WaitForThis = new Task(() =>
                {
                    InitExport();
                })
            };

            lf.ShowDialog();
        }
Example #18
0
        private async void LootTemplateControl_VisibleChanged(object sender, EventArgs e)
        {
            if (!Visible)
            {
                return;
            }

            var loading = new LoadingForm
            {
                ProgressText = { Text = @"Loading: Mobs" }
            };

            loading.Show();

            BindingService.ToggleEnabled(this);
            _items = await _itemService.GetItems();

            _mobs = await _mobService.GetMobs();

            BindingService.ToggleEnabled(this);

            loading.Close();
        }
 // Используем данные с таблицы чтобы заполнить таблицу Lesson в бд.
 private void btnFillSchedule_Click(object sender, RoutedEventArgs e)
 {
     if (MessageBox.Show("Ви підтверджуєте прийняття розкладу?\nУ разі, якщо існує розклад на цей семестр, " +
         "він буде перезаписаний новими даними.", "Підтвердження", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
     {
         if (Schedule.isSchedulesCorrect(scheduleList.ToList()))
         {
             BackgroundWorker bg = new BackgroundWorker();
             bg.DoWork += new DoWorkEventHandler(bg_DoWork);
             bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);
             // Запуск worker.
             bg.RunWorkerAsync();
             // Отображаем loading form.
             loadingForm = new LoadingForm("Заповнення журналу занять");
             loadingForm.ShowDialog();
         }
         else
         {
             MessageBox.Show("Ви невірно заповнили розклад!" +
                 "\nВикладач не може знаходитися в двух місцях одночасно.", "Похибка");
         }
     }
 }
        private async void LootTemplateControl_VisibleChanged(object sender, EventArgs e)
        {
            if (!Visible)
            {
                return;
            }

            var loading = new LoadingForm
            {
                ProgressText = { Text = @"Loading: Mobs" }
            };

            loading.Show();

            BindingService.ToggleEnabled(this);
            _items = await _itemService.GetItems();

            _mobs = await Task.Run(() => DatabaseManager.Database.SelectAllObjects <Mob>().ToList());

            BindingService.ToggleEnabled(this);

            loading.Close();
        }
Example #21
0
        public override void RunAndWait(ProcessStartInfo path)
        {
            if (path.FileName == "WARNING")
            {
                using (LoadingForm frm = new LoadingForm())
                {
                    frm.WarningText = path.Arguments;
                    frm.Show();

                    int ticks = Environment.TickCount;

                    while (Environment.TickCount - ticks < 4000)
                    {
                        Application.DoEvents();
                        Thread.Sleep(1);
                    }
                }

                return;
            }

            base.RunAndWait(path);

            KillProcessTree("TeknoParrotUI");

            if (Process.GetProcessesByName("OpenParrotLoader").Length > 0 || Process.GetProcessesByName("OpenParrotLoader64").Length > 0)
            {
                Thread.Sleep(1000);

                KillProcessTree("OpenParrotLoader");
                KillProcessTree("OpenParrotLoader64");
            }

            KillProcessTree("BudgieLoader");
            KillProcessTree("OpenParrotKonamiLoader");
            killIDZ();
        }
Example #22
0
        private async Task Guardar()
        {
            if (IsValid())
            {
                var loading = new LoadingForm();
                BeginInvoke((Action)(() => loading.ShowDialog()));

                var entity = new Idioma()
                {
                    IdiomaId = idSelected,
                    Nombre   = txtNombre.Text,
                    Estado   = true
                };

                db.Idiomas.AddOrUpdate(entity);
                await db.SaveChangesAsync();

                Clean();
                LoadEntities();
                idSelected = 0;

                loading.Close();
            }
        }
Example #23
0
        private void _update_Click(object sender, EventArgs e)
        {
            LoadingForm.Show(this, async p =>
            {
                _gridManager.Reset();

                _dataSet = null;

                string request = BuildRequest(_columns.Items.Cast <ReportField>(), _rows.Items.Cast <ReportField>(), _values.Items.Cast <ReportField>());

                string[] valueLabels = _values.Items.Cast <ReportField>().Select(p1 => p1.ToString()).ToArray();

                int cookie = ++_cookie;

                string response = await _api.ExecuteRawAsync(_entity.Name + "/$cube", null, "POST", request);

                if (IsDisposed || cookie != _cookie)
                {
                    return;
                }

                JObject result;

                using (var reader = new StringReader(response))
                    using (var json = new JsonTextReader(reader))
                    {
                        json.DateParseHandling = DateParseHandling.None;

                        result = (JObject)JToken.ReadFrom(json);
                    }

                _dataSet = new ReportDataSet(result, valueLabels);

                _gridManager.Load(_dataSet);
            });
        }
Example #24
0
        private async Task Guardar()
        {
            if (IsValid())
            {
                var loading = new LoadingForm();
                BeginInvoke((Action)(() => loading.ShowDialog()));

                var entity = new Competencia()
                {
                    CompetenciaId = idSelected,
                    Descripcion   = txtNombre.Text,
                    Estado        = comboBox1.SelectedItem.Equals("Activo")
                };

                db.Competencias.AddOrUpdate(entity);
                await db.SaveChangesAsync();

                Clean();
                LoadEntities();
                idSelected = 0;

                loading.Close();
            }
        }
Example #25
0
        /// <summary>
        /// Läd eine XML Datei und versucht daraus den gespeicherten Zustand wiederherzustellen
        /// </summary>
        /// <param name="xd">XmlDocument mit den zu ladenden Daten</param>
        /// <param name="nodesList">Liste von allen existierenden LineNodes</param>
        /// <param name="lf">LoadingForm für Statusinformationen</param>
        public void LoadFromFile(XmlDocument xd, List<LineNode> nodesList, LoadingForm.LoadingForm lf)
        {
            lf.SetupLowerProgess("Parsing XML...", 1);

            int saveVersion = 0;

            // erstma alles vorhandene löschen
            foreach (TimelineGroup tg in _groups)
                {
                foreach (TimelineEntry te in tg.entries)
                    {
                    // Löschen vorbereiten
                    te.Dispose();
                    }
                tg.entries.Clear();
                }
            _groups.Clear();

            XmlNode mainNode = xd.SelectSingleNode("//CityTrafficSimulator");
            XmlNode saveVersionNode = mainNode.Attributes.GetNamedItem("saveVersion");
            if (saveVersionNode != null)
                saveVersion = Int32.Parse(saveVersionNode.Value);
            else
                saveVersion = 0;

            lf.StepLowerProgress();

            if (saveVersion >= 4)
                {
                XmlNode xnlTrafficLights = xd.SelectSingleNode("//CityTrafficSimulator/TrafficLights");
                XmlNode cycleTimeNode = xnlTrafficLights.Attributes.GetNamedItem("cycleTime");
                if (cycleTimeNode != null)
                    maxTime = Double.Parse(cycleTimeNode.Value);
                }
            else
                {
                maxTime = 50;
                }

            if (saveVersion >= 3)
                {
                // entsprechenden Node auswählen
                XmlNodeList xnlLineNode = xd.SelectNodes("//CityTrafficSimulator/TrafficLights/TimelineGroup");
                Type[] extraTypes = { typeof(TrafficLight) };
                foreach (XmlNode aXmlNode in xnlLineNode)
                    {
                    // Node in einen TextReader packen
                    TextReader tr = new StringReader(aXmlNode.OuterXml);
                    // und Deserializen
                    XmlSerializer xs = new XmlSerializer(typeof(TimelineGroup), extraTypes);
                    TimelineGroup tg = (TimelineGroup)xs.Deserialize(tr);

                    // ab in die Liste
                    tg.GroupChanged += new TimelineGroup.GroupChangedEventHandler(tg_GroupChanged);
                    _groups.Add(tg);
                    }
                }
            else
                {
                TimelineGroup unsortedGroup = new TimelineGroup("Unsorted Signals", false);

                // entsprechenden Node auswählen
                XmlNodeList xnlLineNode = xd.SelectNodes("//CityTrafficSimulator/Layout/LineNode/tLight");
                foreach (XmlNode aXmlNode in xnlLineNode)
                    {
                    // der XMLNode darf nicht tLight heißen, sondern muss TrafficLight heißen. Das müssen wir mal anpassen:
                    XmlDocument doc = new XmlDocument();
                    XmlElement elem = doc.CreateElement("TrafficLight");
                    elem.InnerXml = aXmlNode.InnerXml;
                    doc.AppendChild(elem);
                    // so, das war nicht wirklich hübsch und schnell, aber es funktioniert ;)

                    // Node in einen TextReader packen
                    StringReader tr = new StringReader(doc.InnerXml);

                    // und Deserializen
                    XmlSerializer xs = new XmlSerializer(typeof(TrafficLight));
                    TrafficLight tl = (TrafficLight)xs.Deserialize(tr);

                    XmlNode pnhNode = doc.SelectSingleNode("//TrafficLight/parentNodeHash");
                    tl.parentNodeHash = Int32.Parse(pnhNode.InnerXml);
                    unsortedGroup.AddEntry(tl);
                    }

                // ab in die Liste
                _groups.Add(unsortedGroup);
                }

            lf.SetupLowerProgess("Restoring Signals...", _groups.Count);

            // Abschließende Arbeiten: Referenzen auflösen
            foreach (TimelineGroup tg in _groups)
                {
                tg.RecoverFromLoad(saveVersion, nodesList);
                lf.StepLowerProgress();
                }

            OnGroupsChanged();
        }
Example #26
0
            public static bool PutUp()
            {
                if (!Check())
                {
                    return(false);
                }
                if (handle != IntPtr.Zero)
                {
                    return(true);
                }
                LoadingForm splash = LoadingForm.Create("Connecting to \"" + FriendlyName + "\" ...");
                string      duplicateName;

                if ((duplicateName = NetworkInterface.CheckIfIPv4Used(Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address, Guid)) != null)
                {
                    splash.Stop();
                    Global.WriteLog("TAP Interface: IP address " + Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address + " already used by \"" + duplicateName + "\"");
                    MessageBox.Show("\"" + FriendlyName + "\" can't use the IP address " + Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address + " because it's already used by \"" + duplicateName + "\".\n\n Set a different IPv4 address in Control Panel>Tools>Load balancing>Advanced.", "TAP Interface", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return(false);
                }
                handle = Kernel32.CreateFile(@"\\.\Global\{" + Guid + "}.tap",
                                             Kernel32.FILE_READ_DATA | Kernel32.FILE_WRITE_DATA,
                                             Kernel32.FILE_SHARE_READ | Kernel32.FILE_SHARE_WRITE,
                                             IntPtr.Zero,
                                             Kernel32.OPEN_EXISTING,
                                             Kernel32.FILE_ATTRIBUTE_SYSTEM | Kernel32.FILE_FLAG_OVERLAPPED,
                                             IntPtr.Zero);
                if (handle == Kernel32.INVALID_HANDLE_VALUE)
                {
                    uint errorCode = Kernel32.GetLastError();
                    splash.Stop();
                    Global.WriteLog("TAP Interface: failed to connect to " + FriendlyName + ": " + Kernel32.GetLastErrorMessage(errorCode));
                    MessageBox.Show("Failed to connect to " + FriendlyName + ":\n" + Kernel32.GetLastErrorMessage(errorCode), "TAP Interface", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }
                // set TAP status to connected
                uint   bytesReturned = 0;
                IntPtr pStatus       = Marshal.AllocHGlobal(4);

                Marshal.Copy(BitConverter.GetBytes(1), 0, pStatus, 4);
                bool deviceStatus = Kernel32.DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS, pStatus, 4, pStatus, 4, ref bytesReturned, IntPtr.Zero);

                Marshal.FreeHGlobal(pStatus);
                // get TAP MAC address
                bytesReturned = 0;
                IntPtr pMac         = Marshal.AllocHGlobal(8);
                bool   macRetrieved = Kernel32.DeviceIoControl(handle, TAP_IOCTL_GET_MAC, pMac, 12, pMac, 12, ref bytesReturned, IntPtr.Zero);

                byte[] mac = new byte[bytesReturned];
                Marshal.Copy(pMac, mac, 0, (int)bytesReturned);
                Mac = BitConverter.ToString(mac).Replace('-', ':');
                Marshal.FreeHGlobal(pMac);
                // configure TAP
                splash.UpdateStatus("Configuring " + FriendlyName + " ...");
                List <Iphlpapi.Adapter> adapters = Iphlpapi.GetAdapters(Iphlpapi.FAMILY.AF_UNSPEC);

                Iphlpapi.Adapter tap = adapters.Find(i => i.Guid == Guid);
                if (tap == null)
                {
                    splash.Stop();
                    Global.WriteLog("TAP Interface: couldn't find " + FriendlyName + " index");
                    MessageBox.Show("Couldn't find " + FriendlyName + " index.", "TAP Interface", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    PutDown();
                    return(false);
                }
                Index = tap.InterfaceIndex;
                if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0)
                {
                    NetworkInterface.SetInterfaceMetric(Mac, "1");
                }
                else
                {
                    NetworkInterface.SetInterfaceMetric(Index, "1");
                }
                NetworkInterface.SetNetBios(Guid, false);
                NetworkInterface.ClearIPv4Addresses(Mac, Global.Config.LoadBalancer.IPv4LocalAddresses[0].Address, Global.Config.LoadBalancer.IPv4LocalAddresses[0].Subnet);
                NetworkInterface.ClearGateways(Index);
                NetworkInterface.ClearIPv4DnsServers(Mac);
                if (Environment.OSVersion.Version.CompareTo(new Version("6.0")) < 0)
                {
                    NetworkInterface.AddIPv4Gateway(Mac, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].Address, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].GatewayMetric.ToString());
                }
                else
                {
                    NetworkInterface.AddIPv4Gateway(Index, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].Address, Global.Config.LoadBalancer.IPv4GatewayAddresses[0].GatewayMetric.ToString());
                }
                NetworkInterface.SetIPv4DnsServer(FriendlyName, Global.Config.LoadBalancer.IPv4DnsAddresses[0]);
                splash.Stop();
                if (handle != IntPtr.Zero && handle != Kernel32.INVALID_HANDLE_VALUE && deviceStatus && macRetrieved)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
Example #27
0
        /// <summary>
        /// Loads the traffic volume setup from the given XML file
        /// </summary>
        /// <param name="xd">XmlDocument to parse</param>
        /// <param name="nodesList">List of all existing LineNodes</param>
        /// <param name="lf">LoadingForm for status updates</param>
        public void LoadFromFile(XmlDocument xd, List<LineNode> nodesList, LoadingForm.LoadingForm lf)
        {
            lf.SetupLowerProgess("Parsing XML...", 3);

            // clear everything first
            _trafficVolumes.Clear();
            _startPoints.Clear();
            _destinationPoints.Clear();

            // parse save file version (currently not needed, but probably in future)
            int saveVersion = 0;
            XmlNode mainNode = xd.SelectSingleNode("//CityTrafficSimulator");
            XmlNode saveVersionNode = mainNode.Attributes.GetNamedItem("saveVersion");
            if (saveVersionNode != null)
                saveVersion = Int32.Parse(saveVersionNode.Value);
            else
                saveVersion = 0;

            // Load start points:
            lf.StepLowerProgress();
            // get corresponding XML nodes
            XmlNodeList xnlStartNodes = xd.SelectNodes("//CityTrafficSimulator/TrafficVolumes/StartPoints/BunchOfNodes");
            foreach (XmlNode aXmlNode in xnlStartNodes)
                {
                // Deserialize each node
                TextReader tr = new StringReader(aXmlNode.OuterXml);
                XmlSerializer xs = new XmlSerializer(typeof(BunchOfNodes));
                BunchOfNodes bof = (BunchOfNodes)xs.Deserialize(tr);
                bof.RecoverFromLoad(saveVersion, nodesList);
                _startPoints.Add(bof);
                }

            // Load destination points:
            lf.StepLowerProgress();
            // get corresponding XML nodes
            XmlNodeList xnlDestinationNodes = xd.SelectNodes("//CityTrafficSimulator/TrafficVolumes/DestinationPoints/BunchOfNodes");
            foreach (XmlNode aXmlNode in xnlDestinationNodes)
                {
                // Deserialize each node
                TextReader tr = new StringReader(aXmlNode.OuterXml);
                XmlSerializer xs = new XmlSerializer(typeof(BunchOfNodes));
                BunchOfNodes bof = (BunchOfNodes)xs.Deserialize(tr);
                bof.RecoverFromLoad(saveVersion, nodesList);
                // ensure that no hashcode is assigned twice
                BunchOfNodes.hashcodeIndex = Math.Max(bof.hashcode + 1, BunchOfNodes.hashcodeIndex);
                _destinationPoints.Add(bof);
                }

            // Load traffic volumes:
            lf.StepLowerProgress();
            // get corresponding XML nodes
            XmlNodeList xnlTrafficVolumes = xd.SelectNodes("//CityTrafficSimulator/TrafficVolumes/TrafficVolume");
            foreach (XmlNode aXmlNode in xnlTrafficVolumes)
                {
                // Deserialize each node
                TextReader tr = new StringReader(aXmlNode.OuterXml);
                XmlSerializer xs = new XmlSerializer(typeof(TrafficVolume));
                TrafficVolume tv = (TrafficVolume)xs.Deserialize(tr);

                tv.RecoverFromLoad(saveVersion, startPoints, destinationPoints);
                if (tv.startNodes != null && tv.destinationNodes != null)
                    {
                    _trafficVolumes.Add(tv);
                    tv.VehicleSpawned += new TrafficVolume.VehicleSpawnedEventHandler(newTV_VehicleSpawned);
                    }
                else
                    {
                    lf.Log("Error during traffic volume deserialization: Could not dereference start-/end nodes. Traffic volume was dismissed.");
                    }
                }

            OnStartPointsChanged(new StartPointsChangedEventArgs());
            OnDestinationPointsChanged(new DestinationPointsChangedEventArgs());
        }
        /// <summary>
        /// This method is called upon selecting a new Medal Data Profile.
        /// It loads the new medal data, and calls the parser to parse it.
        /// </summary>
        private void ProfileSelector_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Make sure we have an index! Also make sure we didnt select the same profile again
            if (ProfileSelector.SelectedIndex == -1 || ProfileSelector.SelectedItem.ToString() == LastSelectedProfile)
            {
                return;
            }

            // Get current profile
            string Profile = ProfileSelector.SelectedItem.ToString();

            // Make sure the user wants to commit without saving changes
            if (ChangesMade && MessageBox.Show("Some changes have not been saved. Are you sure you want to continue?",
                                               "Confirm", MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                ProfileSelector.SelectedIndex = Profiles.IndexOf(LastSelectedProfile.ToLower());
                return;
            }

            // Disable the form to prevent errors. Show loading screen
            this.Enabled = false;
            LoadingForm.ShowScreen(this);

            // Suppress repainting the TreeView until all the objects have been created.
            AwardConditionsTree.Nodes.Clear();
            AwardTree.BeginUpdate();

            // Remove old medal data if applicable
            for (int i = 0; i < 4; i++)
            {
                AwardTree.Nodes[i].Nodes.Clear();
                AwardTree.Nodes[i].ForeColor = Color.Black;
            }

            // Get Medal Data
            try
            {
                MedalDataParser.LoadMedalDataFile(Path.Combine(PythonPath, "medal_data_" + Profile + ".py"));
            }
            catch (Exception ex)
            {
                AwardTree.EndUpdate();
                MessageBox.Show(ex.Message, "Medal Data Parse Error");
                ProfileSelector.SelectedIndex = -1;
                this.Enabled = true;
                LoadingForm.CloseForm();
                return;
            }

            // Iterator for badges
            int itr = -1;

            // Add all awards to the corresponding Node
            foreach (Award A in AwardCache.GetBadges())
            {
                if (Award.GetBadgeLevel(A.Id) == BadgeLevel.Bronze)
                {
                    AwardTree.Nodes[0].Nodes.Add(A.Id, A.Name.Replace("Basic ", ""));
                    ++itr;
                }

                AwardTree.Nodes[0].Nodes[itr].Nodes.Add(A.Id, A.Name.Split(' ')[0]);
            }

            foreach (Award A in AwardCache.GetMedals())
            {
                AwardTree.Nodes[1].Nodes.Add(A.Id, A.Name);
            }

            foreach (Award A in AwardCache.GetRibbons())
            {
                AwardTree.Nodes[2].Nodes.Add(A.Id, A.Name);
            }

            foreach (Rank R in AwardCache.GetRanks())
            {
                AwardTree.Nodes[3].Nodes.Add(R.Id.ToString(), R.Name);
            }

            // Begin repainting the TreeView.
            AwardTree.CollapseAll();
            AwardTree.EndUpdate();

            // Reset current award data
            AwardNameBox.Text     = null;
            AwardTypeBox.Text     = null;
            AwardPictureBox.Image = null;

            // Process Active profile button
            if (Profile == ActiveProfile)
            {
                ActivateProfileBtn.Text            = "Current Server Profile";
                ActivateProfileBtn.BackgroundImage = Resources.check;
            }
            else
            {
                ActivateProfileBtn.Text            = "Set as Server Profile";
                ActivateProfileBtn.BackgroundImage = Resources.power;
            }

            // Apply inital highlighting of condition nodes
            ValidateConditions();

            // Enable form controls
            AwardTree.Enabled           = true;
            AwardConditionsTree.Enabled = true;
            DelProfileBtn.Enabled       = true;
            ActivateProfileBtn.Enabled  = true;
            SaveBtn.Enabled             = true;
            this.Enabled = true;
            LoadingForm.CloseForm();

            // Set this profile as the last selected profile
            LastSelectedProfile = Profile;
            ChangesMade         = false;
        }
 public static void Show()
 {
     var loader = new LoadingForm();
 }
        /// <summary>
        /// Click event for Save File button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSaveFile_Click(object sender, EventArgs e)
        {
            LoadingForm loadingForm = new LoadingForm();
            try
            {
                if (this.lstFileContents.SelectedItems != null && this.lstFileContents.SelectedItems.Count == 1)
                {
                    // only 1 file selected

                    // find selected FileContent in array
                    FileContent selectedFileContent = null;
                    foreach (FileContent fileContent in this._FileContentDetail.FileContent)
                    {
                        if (fileContent._Sequence == this.lstFileContents.SelectedItem.ToString())
                        {
                            selectedFileContent = fileContent;
                            continue;
                        }
                    }

                    // save file dialog
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.DefaultExt = "tif";
                    sfd.Filter = "TIF Image files (*.tif)|*.tif|All files (*.*)|*.*";
                    sfd.AddExtension = true;
                    sfd.OverwritePrompt = true;

                    if (sfd.ShowDialog(this) == DialogResult.OK)
                    {
                        string filePath = sfd.FileName;
                        // do decode
                        loadingForm.DisplayText = "Decoding file";
                        await TestController.DecodeBase64File(selectedFileContent.FileBuffer, filePath);
                        loadingForm.Hide();
                        MessageBox.Show(this, string.Format("Successfully saved to file [{0}]", filePath), "File Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "ERROR");
            }
            finally
            {
                loadingForm.Hide();
                loadingForm.Dispose();
            }
        }
Example #31
0
        public static void SaveXML(string save, LoadingForm loadingForm, string saveFormat)
        {
            XmlSerializer serializerV = new XmlSerializer(typeof(List <Vertex>));
            XmlSerializer serializerE = new XmlSerializer(typeof(List <Edge>));

            File.Delete(save + "Vertices.xml");
            using (FileStream fileV = new FileStream(save + "Vertices.xml", FileMode.OpenOrCreate))
            {
                serializerV.Serialize(fileV, Data.V);
                Console.WriteLine("Объект сериализован");
                fileV.Close();
            }
            File.Delete(save + "Edges.xml");
            using (FileStream fileE = new FileStream(save + "Edges.xml", FileMode.OpenOrCreate))
            {
                serializerE.Serialize(fileE, Data.E);
                Console.WriteLine("Объект сериализован");
                fileE.Close();
            }
            File.Delete(save + "Buses.xml");
            XmlSerializer serializerAllBuses = new XmlSerializer(typeof(List <Bus>));

            using (FileStream fileB = new FileStream(save + "Buses.xml", FileMode.OpenOrCreate))
            {
                serializerAllBuses.Serialize(fileB, Data.Buses);
                Console.WriteLine("Объект сериализован");
            }

            File.Delete(save + "AllCoordinates.xml");
            XmlSerializer serializerAllCoor = new XmlSerializer(typeof(SerializableDictionary <string, List <Point> >));

            using (FileStream fileA = new FileStream(save + "AllCoordinates.xml", FileMode.OpenOrCreate))
            {
                serializerAllCoor.Serialize(fileA, Data.AllCoordinates);
                Console.WriteLine("Объект сериализован");
            }
            File.Delete(save + "AllGridsInRoutes.xml");
            XmlSerializer serializerAllGridsInRoutes = new XmlSerializer(typeof(SerializableDictionary <string, List <int> >));

            using (FileStream fileAG = new FileStream(save + "AllGridsInRoutes.xml", FileMode.OpenOrCreate))
            {
                serializerAllGridsInRoutes.Serialize(fileAG, Data.AllGridsInRoutes);
                Console.WriteLine("Объект сериализован");
            }
            XmlSerializer Ver   = new XmlSerializer(typeof(SerializableDictionary <string, List <Vertex> >));
            XmlSerializer Edge  = new XmlSerializer(typeof(SerializableDictionary <string, List <Edge> >));
            XmlSerializer stopV = new XmlSerializer(typeof(SerializableDictionary <string, List <BusStop> >));

            File.Delete(save + "vertexRoutes.xml");
            using (FileStream fileV = new FileStream(save + "vertexRoutes.xml", FileMode.OpenOrCreate))
            {
                Ver.Serialize(fileV, Data.Routes);
                Console.WriteLine("Объект сериализован");
            }
            File.Delete(save + "StopPoints.xml");
            using (FileStream fileV = new FileStream(save + "StopPoints.xml", FileMode.OpenOrCreate))
            {
                stopV.Serialize(fileV, Data.StopPoints);
                Console.WriteLine("Объект сериализован");
            }
            File.Delete(save + "allStopPoints.xml");
            using (FileStream fileV = new FileStream(save + "allStopPoints.xml", FileMode.OpenOrCreate))
            {
                stopV = new XmlSerializer(typeof(List <BusStop>));
                stopV.Serialize(fileV, Data.AllstopPoints);
                Console.WriteLine("Объект сериализован");
            }

            File.Delete(save + "edgeRoutes.xml");
            using (FileStream fileE = new FileStream(save + "edgeRoutes.xml", FileMode.OpenOrCreate))
            {
                Edge.Serialize(fileE, Data.RoutesEdge);
                Console.WriteLine("Объект сериализован");
            }
            foreach (var tl in Data.TraficLights)
            {
                tl.Stop();
            }
            File.Delete(save + "traficLights.xml");
            using (FileStream fileTL = new FileStream(save + "traficLights.xml", FileMode.OpenOrCreate))
            {
                XmlSerializer tl = new XmlSerializer(typeof(List <TraficLight>));
                tl.Serialize(fileTL, Data.TraficLights);

                Console.WriteLine("Объект сериализован");
            }
            File.Delete(save + "grid.xml");
            using (FileStream fileTL = new FileStream(save + "grid.xml", FileMode.OpenOrCreate))
            {
                XmlSerializer tl = new XmlSerializer(typeof(Classes.Grid));
                tl.Serialize(fileTL, Main.Grid);

                Console.WriteLine("Объект сериализован");
            }

            File.Delete(save + "stations.xml");
            using (FileStream fileTL = new FileStream(save + "stations.xml", FileMode.OpenOrCreate))
            {
                XmlSerializer tl = new XmlSerializer(typeof(List <Vertex>));
                tl.Serialize(fileTL, Data.Staions);

                Console.WriteLine("Объект сериализован");
            }

            Main.SaveF = saveFormat;
            return;
        }
Example #32
0
        static void Main(string[] arguments)
        {
            Application.EnableVisualStyles();

            // Setup //
            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + "unzip.exe");
            psi.Arguments = "-n DevExpress_Setup.zip";
            psi.CreateNoWindow = true;
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            System.Diagnostics.Process unzipProcess = System.Diagnostics.Process.Start(psi);
            unzipProcess.WaitForExit();
            ///////////

            try
            {
                System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("dfsvc");
                foreach (System.Diagnostics.Process proc in processes)
                {
                    try
                    {
                        proc.Kill();
                    }
                    catch { }
                }
                //processes = System.Diagnostics.Process.GetProcesses();
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
                //if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                //{
                //    foreach (System.Diagnostics.Process proc in processes)
                //    {
                //        try
                //        {
                //            SetProcessWorkingSetSize(proc.Handle, -1, -1);
                //        }
                //        catch { }
                //    }
                //}
                //FlushMemory();
            }
            catch { }

            try
            {
                ApplicationDeployment appDeployment = null;

                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    loadingForm = new LoadingForm();
                    isLoading = true;
                    OpenLoadingShell();
                }

                if (loadingForm != null)
                {
                    while (isLoading != false)
                    {
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(1000);
                        //FlushMemory();
                    }
                }

                new ShellApplication().Start(arguments);
                //if (appDeployment != null && appDeployment.CheckForUpdate())
                //{
                //    appDeployment.Update();
                //}
            }
            catch (Exception ex)
            {
                //if (appDeployment != null && appDeployment.CheckForUpdate())
                //{
                //    appDeployment.Update();
                //}

                //DialogResult result = MessageBox.Show("예상하지 못한 오류가 발생하였습니다. 프로그램 재설치시 문제가 해결될 수 있습니다. 프로그램을 삭제하시겠습니까?", "프로그램 오류 발생", MessageBoxButtons.YesNo);
                //if (result == DialogResult.Yes)
                //{
                //    string appsPath = null;
                //    appsPath = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                //    if (String.Compare(appsPath.Substring(appsPath.LastIndexOf('\\') + 1), "Local", true) == 0) appsPath += @"\Apps";
                //    else appsPath = System.IO.Directory.GetParent(appsPath).FullName + @"\Apps";

                //    System.IO.File.Copy(currentPath + @"\DeleteApps.bat", appsPath + @"\DeleteApps.bat", true);

                //    System.Diagnostics.ProcessStartInfo delpsi = new System.Diagnostics.ProcessStartInfo(AppDomain.CurrentDomain.BaseDirectory + "unzip.exe");
                //    delpsi.WorkingDirectory = appsPath;
                //    delpsi.FileName = @"DeleteApps.bat";
                //    delpsi.CreateNoWindow = true;
                //    delpsi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                //    System.Diagnostics.Process.Start(delpsi);
                //    return;
                //}

                throw ex;
            }
            finally
            {
            }
        }
Example #33
0
        public override System.Diagnostics.ProcessStartInfo Generate(string system, string emulator, string core, string rom, string playersControllers, ScreenResolution resolution)
        {
            string path = AppConfig.GetFullPath("fpinball");

            _rom    = rom;
            _splash = ShowSplash(rom);

            if ("bam".Equals(emulator, StringComparison.InvariantCultureIgnoreCase) || "bam".Equals(core, StringComparison.InvariantCultureIgnoreCase))
            {
                _bam = Path.Combine(path, "BAM", "FPLoader.exe");
            }

            string exe = Path.Combine(path, "Future Pinball.exe");

            if (!File.Exists(exe))
            {
                exe = Path.Combine(path, "FuturePinball.exe");
                if (!File.Exists(exe))
                {
                    return(null);
                }
            }

            if (_bam != null && File.Exists(_bam))
            {
                ScreenResolution.SetHighDpiAware(_bam);
            }

            ScreenResolution.SetHighDpiAware(exe);

            SetupOptions(resolution);

            var ret = new ProcessStartInfo()
            {
                FileName  = _bam != null && File.Exists(_bam) ? _bam : exe,
                Arguments = "/open \"" + rom + "\" /play /exit",
            };

            // Check If COM components are well registered. If not : run elevated to register them.
            bool runAs = false;
            var  key   = Registry.ClassesRoot.OpenSubKey("TypeLib\\{FB22A459-4AD0-4CB3-B959-15158F7139F5}\\1.0\\0\\win32", false);

            if (key != null)
            {
                object registeredPath = key.GetValue(null);
                if (registeredPath == null)
                {
                    runAs = true;
                }

                var rp = registeredPath.ToString();
                if (rp != exe)
                {
                    runAs = true;
                }

                key.Close();
            }
            else
            {
                runAs = true;
            }

            if (runAs)
            {
                ret.Verb = "runas";
            }

            return(ret);
        }
Example #34
0
        /// <summary>
        /// Makes sure that the "NetGroup Packet Filter" service status is "Running" and that all specified interfaces are captured.
        /// </summary>
        /// <param name="requiredNics">If this is null it only alerts the user about any non-captured interfaces and returns true</param>
        /// <returns></returns>
        public static bool RunWinPcapService(IEnumerable <NetworkInterface> requiredNics = null, bool verbose = false)
        {
            LoadingForm splash = null;

            if (verbose)
            {
                splash = LoadingForm.Create("Searching \"NetGroup Packet Filter\" service ...");
            }
            if (ServiceController.GetDevices().Where(i => i.ServiceName.ToUpper() == "NPF").Count() == 0)
            {
                if (verbose)
                {
                    splash.Stop();
                }
                MessageBox.Show("\"NetGroup Packet Filter\" service was not installed by WinPcap.", "WinPcap Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            using (ServiceController service = new ServiceController("NPF"))
            {
                bool isCapturingOptional = false;
                if (requiredNics == null)
                {
                    requiredNics        = Global.NetworkInterfaces.Values.ToList();
                    isCapturingOptional = true;
                }
                if (service.Status != ServiceControllerStatus.Running)
                {
                    if (verbose)
                    {
                        splash.UpdateStatus("Starting \"NetGroup Packet Filter\" service ...");
                    }
                    if (!RestartNpfService())
                    {
                        if (verbose)
                        {
                            splash.Stop();
                        }
                        return(false);
                    }
                }
                try { service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(0)); } // update status
                catch { }
                if (service.Status == ServiceControllerStatus.Running)
                {
                    // get captured devices
                    if (verbose)
                    {
                        splash.UpdateStatus("Getting devices captured by WinPcap ...");
                    }
                    WinPcapDevices = GetWinPcapDevs();
                    List <NetworkInterface> nonCapturedNics          = requiredNics.Where(i => WinPcapDevices.Find(j => j.ToUpper().Contains(i.Guid.ToString().ToUpper())) == null).ToList();
                    List <NetworkInterface> capturedNics             = requiredNics.Where(i => WinPcapDevices.Find(j => j.ToUpper().Contains(i.Guid.ToString().ToUpper())) != null).ToList();
                    List <NetworkInterface> supportedNonCapturedNics = nonCapturedNics.Where(i =>
                                                                                             i.Type != NetworkInterface.AdapterType.Ppp &&
                                                                                             i.Type != NetworkInterface.AdapterType.Wwanpp &&
                                                                                             i.Type != NetworkInterface.AdapterType.Wwanpp2).ToList();
                    // if there are NICs not captured by WinPcap that are supported
                    if (supportedNonCapturedNics.Count > 0)
                    {
                        if (verbose)
                        {
                            splash.UpdateStatus("Restarting \"NetGroup Packet Filter\" service ...");
                        }
                        // if WinPcap is not in use
                        if (Dependencies.WinPcapInUse.CurrentCount == 0)
                        {
                            if (!RestartNpfService())
                            {
                                if (verbose)
                                {
                                    splash.Stop();
                                }
                                return(false);
                            }
                        }
                        // get captured devices again
                        if (verbose)
                        {
                            splash.UpdateStatus("Recheck devices captured by WinPcap ...");
                        }
                        WinPcapDevices           = GetWinPcapDevs();
                        nonCapturedNics          = requiredNics.Where(i => WinPcapDevices.Find(j => j.ToUpper().Contains(i.Guid.ToString().ToUpper())) == null).ToList();
                        capturedNics             = requiredNics.Where(i => WinPcapDevices.Find(j => j.ToUpper().Contains(i.Guid.ToString().ToUpper())) != null).ToList();
                        supportedNonCapturedNics = nonCapturedNics.Where(i =>
                                                                         i.Type != NetworkInterface.AdapterType.Ppp &&
                                                                         i.Type != NetworkInterface.AdapterType.Wwanpp &&
                                                                         i.Type != NetworkInterface.AdapterType.Wwanpp2).ToList();
                    }
                    // gat captured devices names list
                    string nonCapturedNicsNames          = null;
                    string capturedNicsNames             = null;
                    string supportedNonCapturedNicsNames = null;
                    foreach (NetworkInterface nic in nonCapturedNics)
                    {
                        nonCapturedNicsNames += nic.Name + "\n";
                    }
                    foreach (NetworkInterface nic in capturedNics)
                    {
                        capturedNicsNames += nic.Name + "\n";
                    }
                    foreach (NetworkInterface nic in supportedNonCapturedNics)
                    {
                        supportedNonCapturedNicsNames += nic.Name + "\n";
                    }
                    if (verbose)
                    {
                        splash.Stop();
                    }

                    // if there are NICs still not captured by WinPcap
                    if (nonCapturedNics.Count > 0)
                    {
                        // if some non-captured NICs are still supported by WinPcap
                        if (supportedNonCapturedNics.Count > 0)
                        {
                            if (isCapturingOptional)
                            {
                                DialogResult result = MessageBox.Show("The following interfaces are not captured by WinPcap:\n\n" +
                                                                      nonCapturedNicsNames + "\n\n" +
                                                                      "Only the following interfaces are captured by WinPcap:\n\n" +
                                                                      capturedNicsNames + "\n\n" +
                                                                      "Do you want to continue?", "WinPcap Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                                if (result == DialogResult.Yes)
                                {
                                    return(true);
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                            else
                            {
                                MessageBox.Show("The following interfaces are not captured by WinPcap and can not continue:\n\n" +
                                                nonCapturedNicsNames + "\n\n" +
                                                "Only the following interfaces are captured by WinPcap:\n\n" +
                                                capturedNicsNames, "WinPcap Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return(false);
                            }
                        }
                        else
                        {
                            if (isCapturingOptional)
                            {
                                DialogResult result = MessageBox.Show("The following interfaces are not captured by WinPcap because WinPcap does not support PPP related interfaces:\n\n" +
                                                                      nonCapturedNicsNames + "\n\n" +
                                                                      "Only the following interfaces are captured by WinPcap:\n\n" +
                                                                      capturedNicsNames + "\n\n" +
                                                                      "Do you want to continue?", "WinPcap Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                                if (result == DialogResult.Yes)
                                {
                                    return(true);
                                }
                                else
                                {
                                    return(false);
                                }
                            }
                            else
                            {
                                MessageBox.Show("The following interfaces are not captured by WinPcap because WinPcap does not support PPP related interfaces, and can not continue:\n\n" +
                                                nonCapturedNicsNames + "\n\n" +
                                                "Only the following interfaces are captured by WinPcap:\n\n" +
                                                capturedNicsNames, "WinPcap Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return(false);
                            }
                        }
                    }
                    // all NICs are captured
                    return(true);
                }
                // should never be reached
                MessageBox.Show("\"NetGroup Packet Filter\" service is not running.", "WinPcap Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
        }
 /// <summary>
 /// Click event for Replace File button
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private async void btnReplaceFile_Click(object sender, EventArgs e)
 {
     LoadingForm loadingForm = new LoadingForm();
     try
     {
         // replace all files
         OpenFileDialog ofd = new OpenFileDialog();
         ofd.Multiselect = true;
         if (ofd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
         {
             string[] filePaths = ofd.FileNames;
             this._FileContentDetail.FileContent = new FileContent[filePaths.Length];
             this.cmbEmbeddedFileType.SelectedItem = this._FileContentDetail.FileContentInfo.EmbeddedFileType.ToString();
             this.numPageCount.Value = decimal.Parse(this._FileContentDetail.FileContentInfo.PageCount);
             this._FileContentDetail.FileContentInfo.ActionCode = (this._FileContentDetail.FileContentInfo.ActionCode == ActionCode.New) ? ActionCode.New : ActionCode.Edit;
             this.txtActionCode.Text = this._FileContentDetail.FileContentInfo.ActionCode.ToString();
             loadingForm.DisplayText = string.Format("Encoding File{0} into Base 64", filePaths.Length == 1 ? string.Empty : "s");
             loadingForm.Show(this);
             int counter = 0;
             foreach (string filePath in filePaths)
             {
                 // encode file
                 //====================================
                 string encodedValue = await TestController.EncodeBase64Async(filePath);
                 // shove encoded value into FileContent
                 //====================================
                 await Task.Run(() =>
                     {
                         this._FileContentDetail.FileContent[counter] = new FileContent()
                         {
                             Encoding = EncodingTypes.Base64,
                             FileBuffer = encodedValue,
                             _Sequence = counter++.ToString()
                         };
                     });
             }
             this.PopulateFileContentList(this._FileContentDetail.FileContent);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "ERROR");
     }
     finally
     {
         loadingForm.Hide();
         loadingForm.Dispose();
     }
 }
Example #36
0
        static void StartLoading()
        {
            ApplicationDeployment appDeployment = ApplicationDeployment.CurrentDeployment;
            loadingForm.Show();
            loadingForm.Update();
            int formCount = Application.OpenForms.Count;
            loadingForm.PerformStep(0, "Downloading setup files...");
            appDeployment.DownloadFileGroupProgressChanged += new DeploymentProgressChangedEventHandler(appDeployment_DownloadFileGroupProgressChanged);
            int totalPercent = 0;
            for (int i = 0; i < GROUPS.Length; i++)
            {
                if (appDeployment.IsFileGroupDownloaded(GROUPS[i].Group) == false)
                {
                    _percent = 0;
                    appDeployment.DownloadFileGroupAsync(GROUPS[i].Group);
                    while (_percent < 100)
                    {
                        System.Threading.Thread.Sleep(100);
                        loadingForm.PerformStep(totalPercent + (((GROUPS[i].Percent) / 100 * _percent)), String.Format("Downloading setup files (GROUP : {0})...", GROUPS[i].Group));
                    }
                    FlushMemory();
                }
                totalPercent += GROUPS[i].Percent;
                loadingForm.PerformStep(totalPercent, "Downloading setup files...");
            }

            loadingForm.PerformStep(totalPercent, "Now prepare to start application.");
            isLoading = false;

            while (isLoading != null)
            {
                Application.DoEvents();
                if (formCount != Application.OpenForms.Count) break;
                System.Threading.Thread.Sleep(200);
                loadingForm.Update();
            }

            loadingForm.Close();
            loadingForm.Dispose();
            loadingForm = null;

            FlushMemory();
        }
Example #37
0
        public static bool Start(IEnumerable <NetworkInterface> requiredNics)
        {
            Global.WriteLog("Load Balancer is starting.", true);
            Status.Update(State.Starting);
            if (requiredNics.Count() == 0)
            {
                Global.WriteLog("Load Balancer can't start without any physical interface.", true);
                Global.ShowTrayTip("Load Balancer", "Can't start whitout any physical interface", System.Windows.Forms.ToolTipIcon.Error);
                Status.Update(State.Failed);
                return(false);
            }
            if (!Jobs.Extensions.Dependencies.Check())
            {
                Status.Update(State.Failed);
                return(false);
            }
            if (!TapInterface.PutUp())
            {
                Global.WriteLog("Load Balancer failed to connect to " + TapInterface.FriendlyName, true);
                Global.ShowTrayTip("Load Balancer", "Failed to connect to " + TapInterface.FriendlyName, System.Windows.Forms.ToolTipIcon.Error);
                Status.Update(State.Failed);
                return(false);
            }
            NetworkInterface tapInterface = new NetworkInterface();

            tapInterface.Guid = TapInterface.Guid;
            tapInterface.Name = TapInterface.FriendlyName;
            if (!Dependencies.RunWinPcapService(requiredNics.Concat(new NetworkInterface[] { tapInterface }), true))
            {
                Global.WriteLog("Load Balancer failed to start because some interfaces were not captured by WinPcap.", true);
                Global.ShowTrayTip("Load Balancer", "Failed to start", System.Windows.Forms.ToolTipIcon.Error);
                TapInterface.PutDown();
                Status.Update(State.Failed);
                return(false);
            }
            Interfaces = requiredNics;
            // start LB threads
            LoadingForm splash = LoadingForm.Create("Initializing ...");

            foreach (NetworkInterface nic in Global.NetworkInterfaces.Values)
            {
                if (nic.Guid != TapInterface.Guid &&
                    (nic.IPv4Gateway.Count > 0 || nic.IPv6Gateway.Count > 0))
                {
                    splash.UpdateStatus("Configuring " + nic.Name + " ...");
                    nic.SetInterfaceMetric("4000");
                    foreach (NetworkInterface.IPGatewayAddress ip in nic.IPv4Gateway)
                    {
                        nic.EditIPv4Gateway(ip.Address, "4000");
                    }
                    foreach (NetworkInterface.IPGatewayAddress ip in nic.IPv6Gateway)
                    {
                        nic.EditIPv6Gateway(ip.Address, "4000");
                    }
                }
            }
            splash.UpdateStatus("Initializing " + TapInterface.FriendlyName + " ...");
            physicalWorkers.Clear();
            tapWorker = new TapWorker(TapInterface.Guid, TapInterface.FriendlyName, TapInterface.Mac,
                                      Global.Config.LoadBalancer.IPv4LocalAddresses.First().Address, Global.Config.LoadBalancer.IPv4GatewayAddresses.First().Address);
            new Thread(new ThreadStart(tapWorker.ReceivePackets)).Start();
            tapWorker.Initialized.Wait(1000);
            foreach (NetworkInterface nic in requiredNics)
            {
                splash.UpdateStatus("Initializing " + nic.Name + " ...");
                physicalWorkers.Add(new PhysicalWorker(nic.Guid, nic.Name, nic.Mac, nic.IPv4Address.First().Address,
                                                       nic.IPv4Address.First().Subnet, nic.DefaultIPv4GatewayMac, nic.DefaultIPv4Gateway));
                new Thread(new ThreadStart(physicalWorkers.Last().ReceivePackets)).Start();
                physicalWorkers.Last().Initialized.Wait(10000);
            }
            MTU = (int)requiredNics.Min((i) => i.IPv4Mtu > 0 ? i.IPv4Mtu : 1500);
            Global.WriteLog("Load Balancer: Negociated MTU = " + MTU);
            MSS = (ushort)(MTU - 40);
            splash.Stop();
            Dependencies.WinPcapInUse.Reset(Dependencies.WinPcapInUse.CurrentCount + 1);
            Global.WriteLog("Load Balancer: started");
            Global.ShowTrayTip("Load Balancer", "Started", System.Windows.Forms.ToolTipIcon.Info);
            Status.Update(State.Running);
            new Thread(new ThreadStart(CheckUp)).Start();
            return(true);
        }
        private async void button1_Click(object sender, EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }
            if (!ValidaCedula(txtCedula.Text.Replace("-", "")))
            {
                return;
            }

            var loading = new LoadingForm();

            BeginInvoke((Action)(() => loading.ShowDialog()));

            candidato = new Candidato()
            {
                CadidatoId   = currentId,
                Cedula       = txtCedula.Text,
                Departamento = comboBox2.Text,
                Estado       = "Activo",
                Recomendado  = txtRecomendado.Text,
                Nombre       = txtNombre.Text,
                PuestoId1    = puestos.FirstOrDefault(x => x.Nombre == comboBox1.SelectedItem.ToString()).PuestoId,
                Salario      = decimal.Parse(txtSalario.Text),
                Telefono     = txtTel.Text,
                Direccion    = txtDir.Text
            };

            db.Candidatos.AddOrUpdate(candidato);
            try
            {
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                loading.Close();
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (checkedListBox1.CheckedItems.Count > 0)
            {
                foreach (var item in checkedListBox1.CheckedItems)
                {
                    var cmpTmp = competencias.FirstOrDefault(x => x.Descripcion == item.ToString());
                    var tmp    = new CompetenciasCandidato()
                    {
                        CandidatoId   = candidato.CadidatoId,
                        CompetenciaId = cmpTmp.CompetenciaId
                    };

                    db.CompetenciasCandidatos.Add(tmp);
                }
            }

            //if (checkedListBox2.CheckedItems.Count > 0)
            //{
            //    foreach (var item in checkedListBox2.CheckedItems)
            //    {
            //        var cmpTmp = capacitaciones.FirstOrDefault(x => x.Descripcion == item.ToString());
            //        var tmp = new CapacitacionesCandidato()
            //        {
            //            CandidatoId = candidato.CadidatoId,
            //            CapacitacionId = cmpTmp.CapacitacionId
            //        };
            //        db.CapacitacionesCandidatos.Add(tmp);
            //    }
            //}

            if (checkedListBox3.CheckedItems.Count > 0)
            {
                foreach (var item in checkedListBox3.CheckedItems)
                {
                    var cmpTmp = idiomas.FirstOrDefault(x => x.Nombre == item.ToString());
                    var tmp    = new IdiomasCandidato()
                    {
                        CandidatoId = candidato.CadidatoId,
                        IdiomaId    = cmpTmp.IdiomaId
                    };
                    db.IdiomasCandidatos.Add(tmp);
                }
            }

            if (Experiencias != null && Experiencias.Count() > 0)
            {
                foreach (var item in Experiencias)
                {
                    item.CandidatoId = candidato.CadidatoId;
                    db.ExperienciasLaborales.Add(item);
                }
            }

            await db.SaveChangesAsync();

            loading.Close();

            this.Close();
        }
Example #39
0
        /// <summary>
        /// Performs any processing or data setup needed before the module is
        /// started.
        /// </summary>
        /// <param name="showLoadingWindow">Whether the module should display a
        /// loading or splash screen while performing initialization.</param>
        /// <param name="isTouchScreen">Whether this module is running on a
        /// touchscreen-based device.</param>
        /// <param name="instanceId">The unique identifier of the running
        /// instance of this module.</param>
        /// <returns>true if the initialization was successful; otherwise,
        /// false.</returns>
        public bool Initialize(bool showLoadingWindow, bool isTouchScreen, int instanceId)
        {
            // Check to see if we are already initialized.
            if (IsInitialized)
            {
                return(IsInitialized);
            }

            InstanceId = instanceId;

            // Create a settings object with the default values.
            Settings = new SessionSummarySettings();

            // Start COM interface to EliteMCP.
            EliteModuleComm modComm   = null;
            int             machineId = 0;
            int             staffId   = 0;

            try
            {
                modComm    = new EliteModuleComm();
                machineId  = modComm.GetMachineId();
                OperatorId = modComm.GetOperatorId();
                staffId    = modComm.GetStaffId();
            }
            catch (Exception ex)
            {
                MessageBoxOptions options = 0;

                if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft)
                {
                    options = MessageBoxOptions.RtlReading | MessageBoxOptions.RightAlign;
                }

                MessageBox.Show(string.Format(CultureInfo.CurrentCulture, Resources.GetDeviceInfoFailed, ex.Message),
                                Resources.SessionSummaryName, MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK, options);

                return(IsInitialized);
            }

            // Session Summary always runs in windowed mode.
            Settings.DisplayMode = DisplayMode.Windowed;

            // Create and show the loading form.
            LoadingForm = new LoadingForm(Settings.DisplayMode);
            LoadingForm.ApplicationName = Resources.SessionSummaryName;
            LoadingForm.Version         = EliteModule.GetVersion(Assembly.GetExecutingAssembly());
            LoadingForm.Copyright       = EliteModule.GetCopyright(Assembly.GetExecutingAssembly());
            LoadingForm.Cursor          = System.Windows.Forms.Cursors.WaitCursor;

            if (showLoadingWindow)
            {
                LoadingForm.Show();
            }

            LoadingForm.Status = Resources.LoadingMachineInfo;

            CreateApplication();

            if (!LoadSettings(OperatorId, machineId))
            {
                return(IsInitialized);
            }

            if (!LoadOperatorData(OperatorId))
            {
                return(IsInitialized);
            }

            if (!LoadStaff(staffId))
            {
                return(IsInitialized);
            }

            if (!CreateLogger())
            {
                return(IsInitialized);
            }

            // Check to see if we only want to display in English.
            if (Settings.ForceEnglish)
            {
                EliteModule.ForceEnglish();
                Logger.Log("Forcing English.", LoggerLevel.Configuration);
            }

            if (!LoadCurrencies())
            {
                return(IsInitialized);
            }

            if (!CreateControllers())
            {
                return(IsInitialized);
            }

            if (!CreateReport())
            {
                return(IsInitialized);
            }

            LoadingForm.Status = Resources.Starting;

            if (!CreateWindows())
            {
                return(IsInitialized);
            }

            // Have the controller notified when the main window opens.
            MainWindow.Loaded += MainWindowLoaded;

            IsInitialized = true;

            Logger.Log("Session Summary initialized!", LoggerLevel.Debug);

            return(IsInitialized);
        }
Example #40
0
        /// <summary>
        /// Läd eine XML Datei und versucht daraus den gespeicherten Zustand wiederherzustellen
        /// </summary>
        /// <param name="xd">XmlDocument mit den zu ladenden Daten</param>
        /// <param name="lf">LoadingForm für Statusinformationen</param>
        public List<Auftrag> LoadFromFile(XmlDocument xd, LoadingForm.LoadingForm lf)
        {
            lf.SetupLowerProgess("Parsing XML...", 3);

            List<Auftrag> toReturn = new List<Auftrag>();
            int saveVersion = 0;

            // erstma alles vorhandene löschen
            nodes.Clear();
            connections.Clear();
            intersections.Clear();
            _networkLayers.Clear();

            XmlNode mainNode = xd.SelectSingleNode("//CityTrafficSimulator");
            XmlNode saveVersionNode = mainNode.Attributes.GetNamedItem("saveVersion");
            if (saveVersionNode != null)
                saveVersion = Int32.Parse(saveVersionNode.Value);
            else
                saveVersion = 0;

            XmlNode titleNode = xd.SelectSingleNode("//CityTrafficSimulator/Layout/title");
            if (titleNode != null)
                {
                m_title = titleNode.InnerText;
                }

            XmlNode infoNode = xd.SelectSingleNode("//CityTrafficSimulator/Layout/infoText");
            if (infoNode != null)
                {
                _infoText = infoNode.InnerText;
                }

            lf.StepLowerProgress();

            // entsprechenden Node auswählen
            XmlNodeList xnlLineNode = xd.SelectNodes("//CityTrafficSimulator/Layout/LineNode");
            foreach (XmlNode aXmlNode in xnlLineNode)
                {
                // Node in einen TextReader packen
                TextReader tr = new StringReader(aXmlNode.OuterXml);
                // und Deserializen
                XmlSerializer xs = new XmlSerializer(typeof(LineNode));
                LineNode ln = (LineNode)xs.Deserialize(tr);

                // ab in die Liste
                nodes.Add(ln);
                }

            lf.StepLowerProgress();

            // entsprechenden Node auswählen
            XmlNodeList xnlNetworkLayer = xd.SelectNodes("//CityTrafficSimulator/Layout/NetworkLayer");
            foreach (XmlNode aXmlNode in xnlNetworkLayer)
                {
                // Node in einen TextReader packen
                TextReader tr = new StringReader(aXmlNode.OuterXml);
                // und Deserializen
                XmlSerializer xs = new XmlSerializer(typeof(NetworkLayer));
                NetworkLayer nl = (NetworkLayer)xs.Deserialize(tr);

                // ab in die Liste
                _networkLayers.Add(nl);
                }

            lf.StepLowerProgress();

            // entsprechenden NodeConnections auswählen
            XmlNodeList xnlNodeConnection = xd.SelectNodes("//CityTrafficSimulator/Layout/NodeConnection");
            foreach (XmlNode aXmlNode in xnlNodeConnection)
                {
                // Node in einen TextReader packen
                TextReader tr = new StringReader(aXmlNode.OuterXml);
                // und Deserializen
                XmlSerializer xs = new XmlSerializer(typeof(NodeConnection));
                NodeConnection ln = (NodeConnection)xs.Deserialize(tr);
                // ab in die Liste
                connections.Add(ln);
                }

            lf.SetupLowerProgess("Restoring LineNodes...", _nodes.Count);

            // Nodes wiederherstellen
            foreach (LineNode ln in _nodes)
                {
                ln.RecoverFromLoad(saveVersion, _nodes);
                lf.StepLowerProgress();
                }

            lf.SetupLowerProgess("Restoring NetworkLayers...", _networkLayers.Count);

            // restore NetworkLayers
            if (saveVersion >= 6)
                {
                foreach (NetworkLayer nl in _networkLayers)
                    {
                    foreach (int hash in nl._nodeHashes)
                        {
                        LineNode tmp = GetLineNodeByHash(nodes, hash);
                        if (tmp != null)
                            tmp.networkLayer = nl;
                        }
                    nl.TitleChanged += new NetworkLayer.TitleChangedEventHandler(nl_TitleChanged);
                    nl.VisibleChanged +=new NetworkLayer.VisibleChangedEventHandler(nl_VisibleChanged);
                    }
                }
            else
                {
                AddNetworkLayer("Layer 1", true);
                foreach (LineNode ln in _nodes)
                    {
                    ln.networkLayer = _networkLayers[0];
                    }
                }
            InvokeNetworkLayersChanged(new NetworkLayersChangedEventArgs(NetworkLayersChangedEventArgs.InvalidationLevel.COLLECTION_CHANGED));

            lf.SetupLowerProgess("Restoring NodeConnections...", _connections.Count);

            // LineNodes wiederherstellen
            foreach (NodeConnection nc in _connections)
                {
                nc.RecoverFromLoad(saveVersion, nodes);
                TellNodesTheirConnection(nc);
                nc.lineSegment = new LineSegment(0, nc.startNode.position, nc.startNode.outSlopeAbs, nc.endNode.inSlopeAbs, nc.endNode.position);

                lf.StepLowerProgress();
                }

            lf.SetupLowerProgess("Calculate Intersections and Line Change Points...", _connections.Count);

            // Intersections wiederherstellen
            foreach (NodeConnection nc in _connections)
                {
                UpdateNodeConnection(nc);

                lf.StepLowerProgress();
                }

            // Fahraufträge laden
            // entsprechenden Node auswählen
            if (saveVersion < 5)
                {
                XmlNodeList xnlAuftrag = xd.SelectNodes("//CityTrafficSimulator/Traffic/Auftrag");

                lf.SetupLowerProgess("Load Old Traffic Volume...", 2 * xnlAuftrag.Count);

                foreach (XmlNode aXmlNode in xnlAuftrag)
                    {
                    // Node in einen TextReader packen
                    TextReader tr = new StringReader(aXmlNode.OuterXml);
                    // und Deserializen
                    XmlSerializer xs = new XmlSerializer(typeof(Auftrag));
                    Auftrag ln = (Auftrag)xs.Deserialize(tr);

                    // in alten Dateien wurde das Feld häufigkeit statt trafficDensity gespeichert. Da es dieses Feld heute nicht mehr gibt, müssen wir konvertieren:
                    if (saveVersion < 1)
                        {
                        // eigentlich wollte ich hier direkt mit aXmlNode arbeiten, das hat jedoch komische Fehler verursacht (SelectSingleNode) wählt immer den gleichen aus)
                        // daher der Umweg über das neue XmlDocument.
                        XmlDocument doc = new XmlDocument();
                        XmlElement elem = doc.CreateElement("Auftrag");
                        elem.InnerXml = aXmlNode.InnerXml;
                        doc.AppendChild(elem);

                        XmlNode haeufigkeitNode = doc.SelectSingleNode("//Auftrag/häufigkeit");
                        if (haeufigkeitNode != null)
                            {
                            ln.trafficDensity = 72000 / Int32.Parse(haeufigkeitNode.InnerXml);
                            }
                        haeufigkeitNode = null;
                        }

                    // ab in die Liste
                    toReturn.Add(ln);

                    lf.StepLowerProgress();
                    }

                // Nodes wiederherstellen
                foreach (Auftrag a in toReturn)
                    {
                    a.RecoverFromLoad(saveVersion, nodes);

                    lf.StepLowerProgress();
                    }

                }

            return toReturn;
        }
Example #41
0
        public void regenerateTextureList()
        {
            using (LoadingForm form = new LoadingForm())
            {
                form.Show();

                //GraphicsManager.DeleteTextures();

                int i = 0;

                //form.loadingBar.Maximum = this.GMXObjects.Count;
                form.loadingBar.Maximum = this.GmsResourceObjectList.Count;
                form.loadingBar.Value   = 0;

                GraphicsManager.LoadTexture(GmsResource.undefined, new Bitmap(Manager.MainWindow.imageListObjects.Images[GmsResource.undefined]));

                //foreach (string file in RegisteredResources)
                // LOAD ONLY SPRITES ASSIGNED TO OBJECTS, SKIP ELSE
                //List<string> objects = renderItemsList("objects");
                foreach (GmsObject gmobject in this.GmsResourceObjectList)
                {
                    //GMSpriteData itm = this.GMXSprites.Find(item => item.Name == file);
                    //GMSpriteData itm = this.GMXObjects.Find(item => item.Name == gmobject).sprite;
                    GmsSprite itm = gmobject.sprite_index;

                    if (itm != null)
                    {
                        // prevent adding duplicates
                        if (!GraphicsManager.Sprites.ContainsKey(itm.name))
                        {
                            if (File.Exists(itm.image))
                            {
                                GraphicsManager.LoadTexture(itm.name, new Bitmap(itm.image));
                            }
                            else// if (itm.name == null)
                            {
                                GraphicsManager.LoadTexture(itm.name, new Bitmap(Manager.MainWindow.imageListObjects.Images[GmsResource.undefined]));
                            }
                        }

                        if (!Manager.MainWindow.imageListObjects.Images.ContainsKey(itm.name))
                        {
                            if (File.Exists(itm.image))
                            {
                                Manager.MainWindow.imageListObjects.Images.Add(itm.name, new Bitmap(itm.image));
                            }
                        }
                    }
                    //Manager.MainWindow.tsProgress.Value++;
                    form.loadingBar.Value++;
                    if (i % 10 == 0 || i == form.loadingBar.Maximum - 1)
                    {
                        form.Refresh();
                    }
                    i++;
                }

                foreach (GmsRoom r in this.GmsResourceRoomList)
                {
                    if (r.background != null && r.background.image != null)
                    {
                        string imgName = "@bg:" + r.background.name;

                        if (!GraphicsManager.Sprites.ContainsKey(imgName))
                        {
                            if (File.Exists(r.background.image))
                            {
                                GraphicsManager.LoadTexture(imgName, new Bitmap(r.background.image));
                            }
                        }
                    }
                }

                //foreach (PlaceableElement elem in PlaceableList)
                //{
                //    elem.textureId = elem.Sprite;
                //}

                form.Close();
            }

            /*using (LoadingForm form = new LoadingForm())
             * {
             *  form.Show();
             *
             *  List<string> objects = renderItemsList("objects");
             *
             *  foreach (string gmobject in objects)
             *  {
             *      //GMSpriteData itm = this.GMXSprites.Find(item => item.Name == file);
             *      GMSpriteData itm = this.GMXObjects.Find(item => item.Name == gmobject).sprite;
             *
             *      if (itm != null)
             *      {
             *          // prevent adding duplicates
             *          //if (!GraphicsManager.Sprites.ContainsKey(itm.Name))
             *
             *      }
             *  }
             *
             *  form.Close();
             * }*/
        }
Example #42
0
        private void InitForms()
        {
            loadingForm = new LoadingForm();
            messageForm = new MessageForm();
            InitForm(instructionForm = new InstructionForm());
            InitForm(maintenanceForm = new MaintenanceForm());
            InitForm(mainFrm = new PB_MainFrm());
            mainFrm.Width = 1280;
            mainFrm.Height = 1024;

            Application.DoEvents();
            loadingForm.Hide();
            messageForm.Hide();
            instructionForm.Hide();
            maintenanceForm.Hide();

            /*
            InitForm(adsForm = new AdsForm());
            InitForm(documentChooseForm = new DocumentChooseForm());
            //InitForm(prePrintForm = new PrePrintForm());
            InitForm(printForm = new PrintForm());
            */

            if (PrintBoxApp.instance.runOptions.testMode)
            {
                controlForm = new ControlForm();
                controlForm.Show();
            }
        }