//get all information at once
        public SystemInformation GetSystemInformation()
        {
            SystemInformation info = new SystemInformation();

            //computer system
            info.ComputerSystem = GetSysInfoDataAsKeyValues(ManagementSourceEnum.Win32_ComputerSystem,
               ComputerSystemPropertiesEnum.Caption.GetNames<ComputerSystemPropertiesEnum>());

            //hard drive
            info.DiskDrive = GetSysInfoDataAsKeyValues(ManagementSourceEnum.Win32_DiskDrive,
                HddPropertiesEnum.Name.GetNames<HddPropertiesEnum>());

            //operating system
            info.OperatingSystem = GetSysInfoDataAsKeyValues(ManagementSourceEnum.Win32_OperatingSystem,
               OperatingSystemPropertiesEnum.BootDevice.GetNames<OperatingSystemPropertiesEnum>());

            //processor
            info.Processor = GetSysInfoDataAsKeyValues(ManagementSourceEnum.Win32_Processor,
               ProcessorPropertiesEnum.Caption.GetNames<ProcessorPropertiesEnum>()
                );

            //system devices
            info.SystemDevices = GetSysInfoDataAsKeyValues(ManagementSourceEnum.Win32_SystemDevices);

            //startup programs
            info.StartupPrograms = GetSysInfoDataAsKeyValues(ManagementSourceEnum.Win32_StartupCommand);

            return info;
        }
Example #2
0
        /// <summary>
        /// Sets the configuration used when sending reports.
        /// </summary>
        /// <param name="configuration">Configuration used when sending reports.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="configuration"/> is null.</exception>
        /// <exception cref="InvalidOperationException">Thrown when a configuration has already been provided.</exception>
        /// <exception cref="ArgumentException">Thrown when either the Url or Version haven't been set on the configuration.</exception>
        public static void SetConfiguration(IConfiguration configuration)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");

            if (Configuration != null)
                throw new InvalidOperationException(Properties.Resources.ConfigurationAlreadyProvided);

            if (configuration.Url == null)
                throw new ArgumentException(Properties.Resources.UrlIsRequired, "configuration");
            if (configuration.Version == null)
                throw new ArgumentException(Properties.Resources.VersionIsRequired, "configuration");

            Configuration = new FrozenConfiguration(configuration);

            // Once we have a valid configuration, we can set/update the system
            // information.

            using (var key = BaseKey)
            {
                SystemInformation = new SystemInformation(key);
            }
        }
Example #3
0
 private async void RateButton_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
 {
     await SystemInformation.LaunchStoreForReviewAsync();
 }
Example #4
0
        private void Build()
        {
            Gui.Initialize(this);

            // Widget Launchpad.Launcher.Interface.MainWindow
            this.UIManager = new UIManager();
            ActionGroup mainActionGroup = new ActionGroup("Default");

            this.MenuAction = new Action("MenuAction", LocalizationCatalog.GetString("Menu"), null, null)
            {
                ShortLabel = LocalizationCatalog.GetString("Menu")
            };
            mainActionGroup.Add(this.MenuAction, null);

            this.RepairGameAction = new Action(
                "repairGameAction",
                LocalizationCatalog.GetString("Repair Game"),
                LocalizationCatalog.GetString("Starts a repair process for the installed game."),
                "gtk-refresh")
            {
                ShortLabel = LocalizationCatalog.GetString("Repair Game")
            };
            mainActionGroup.Add(this.RepairGameAction, null);

            this.ReinstallGameAction = new Action(
                "reinstallGameAction",
                LocalizationCatalog.GetString("Reinstall Game"),
                LocalizationCatalog.GetString("Reinstalls the installed game."),
                "gtk-refresh")
            {
                ShortLabel = LocalizationCatalog.GetString("Reinstall Game")
            };
            mainActionGroup.Add(this.ReinstallGameAction, null);

            this.UIManager.InsertActionGroup(mainActionGroup, 0);
            AddAccelGroup(this.UIManager.AccelGroup);
            this.Name  = "Launchpad.Launcher.Interface.MainWindow";
            this.Title = LocalizationCatalog.GetString("Launchpad - {0}");

            if (SystemInformation.IsRunningOnUnix())
            {
                this.Icon = Pixbuf.LoadFromResource("Launchpad.Launcher.Resources.RocketIcon.ico");
            }
            else
            {
                this.Icon = Pixbuf.LoadFromResource("Launchpad.Launcher.Resources.RocketIcon_Grey.ico");
            }

            this.WindowPosition = (WindowPosition)4;
            this.DefaultWidth   = 745;
            this.DefaultHeight  = 415;
            this.Resizable      = false;

            // Container child Launchpad.Launcher.Interface.MainWindow.Gtk.Container+ContainerChild
            this.VBox1 = new VBox
            {
                Name    = "VBox1",
                Spacing = 6
            };

            // Container child VBox1.Gtk.Box+BoxChild
            this.UIManager.AddUiFromString
            (
                "<ui>" +
                "<menubar name='MainMenuBar'>" +
                "<menu name='MenuAction' action='MenuAction'>" +
                "<menuitem name='repairGameAction' action='repairGameAction'/>" +
                "<separator/>" +
                "<menuitem name='reinstallGameAction' action='reinstallGameAction'/>" +
                "</menu>" +
                "</menubar>" +
                "</ui>"
            );
            this.MainMenuBar      = (MenuBar)this.UIManager.GetWidget("/MainMenuBar");
            this.MainMenuBar.Name = "MainMenuBar";
            this.VBox1.Add(this.MainMenuBar);

            Box.BoxChild w2 = (Box.BoxChild) this.VBox1 [this.MainMenuBar];
            w2.Position = 0;
            w2.Expand   = false;
            w2.Fill     = false;

            // Container child VBox1.Gtk.Box+BoxChild
            this.HBox2 = new HBox
            {
                Name        = "HBox2",
                Spacing     = 6,
                BorderWidth = 4
            };

            // Container child HBox2.Gtk.Box+BoxChild
            this.BrowserContainer = new VBox
            {
                Name    = "browserContainer",
                Spacing = 6
            };

            // Container child browserContainer.Gtk.Box+BoxChild
            this.Alignment2 = new Alignment(0.5F, 0.5F, 1F, 1F)
            {
                WidthRequest = 310,
                Name         = "alignment2"
            };

            // Container child alignment2.Gtk.Container+ContainerChild
            this.BrowserWindow = new ScrolledWindow
            {
                CanFocus   = true,
                Name       = "browserWindow",
                ShadowType = ShadowType.In
            };
            this.Alignment2.Add(this.BrowserWindow);
            this.BrowserContainer.Add(this.Alignment2);

            Box.BoxChild w4 = (Box.BoxChild) this.BrowserContainer [this.Alignment2];
            w4.Position = 0;
            this.HBox2.Add(this.BrowserContainer);

            Box.BoxChild w5 = (Box.BoxChild) this.HBox2 [this.BrowserContainer];
            w5.Position = 0;
            w5.Expand   = false;

            // Container child HBox2.Gtk.Box+BoxChild
            this.Alignment5 = new Alignment(0.5F, 0.5F, 1F, 1F)
            {
                Name = "alignment5"
            };

            // Container child alignment5.Gtk.Container+ContainerChild
            this.GameBanner = new Image
            {
                WidthRequest  = 450,
                HeightRequest = 300,
                Name          = "gameBanner",
                Pixbuf        = Pixbuf.LoadFromResource("Launchpad.Launcher.Resources.RocketIcon.ico")
            };
            this.Alignment5.Add(this.GameBanner);
            this.HBox2.Add(this.Alignment5);

            Box.BoxChild w7 = (Box.BoxChild) this.HBox2 [this.Alignment5];
            w7.Position = 1;
            this.VBox1.Add(this.HBox2);

            Box.BoxChild w8 = (Box.BoxChild) this.VBox1 [this.HBox2];
            w8.Position = 1;
            w8.Expand   = false;
            w8.Fill     = false;

            // Container child VBox1.Gtk.Box+BoxChild
            this.Alignment1 = new Alignment(0.5F, 0.5F, 1F, 1F)
            {
                Name        = "alignment1",
                LeftPadding = 6
            };

            // Container child alignment1.Gtk.Container+ContainerChild
            this.IndicatorLabel = new Label
            {
                Name      = "IndicatorLabel",
                Xalign    = 0F,
                LabelProp = LocalizationCatalog.GetString("Idle")
            };
            this.Alignment1.Add(this.IndicatorLabel);
            this.VBox1.Add(this.Alignment1);

            Box.BoxChild w10 = (Box.BoxChild) this.VBox1 [this.Alignment1];
            w10.Position = 2;
            w10.Expand   = false;
            w10.Fill     = false;

            // Container child VBox1.Gtk.Box+BoxChild
            this.HBox3 = new HBox
            {
                Name        = "HBox3",
                Spacing     = 6,
                BorderWidth = 4
            };

            // Container child HBox3.Gtk.Box+BoxChild
            this.Alignment4 = new Alignment(0.5F, 0.5F, 1F, 1F)
            {
                Name = "alignment4"
            };

            // Container child alignment4.Gtk.Container+ContainerChild
            this.MainProgressBar = new ProgressBar
            {
                Name = "mainProgressBar"
            };
            this.Alignment4.Add(this.MainProgressBar);
            this.HBox3.Add(this.Alignment4);

            Box.BoxChild w12 = (Box.BoxChild) this.HBox3 [this.Alignment4];
            w12.Position = 0;

            // Container child HBox3.Gtk.Box+BoxChild
            this.HBox4 = new HBox
            {
                Name    = "HBox4",
                Spacing = 6
            };

            // Container child HBox4.Gtk.Box+BoxChild
            this.Alignment3 = new Alignment(0.5F, 0.5F, 1F, 1F)
            {
                WidthRequest = 100,
                Name         = "alignment3"
            };

            // Container child alignment3.Gtk.Container+ContainerChild
            this.PrimaryButton = new Button
            {
                Sensitive    = false,
                CanDefault   = true,
                CanFocus     = true,
                Name         = "primaryButton",
                UseUnderline = true,
                Label        = LocalizationCatalog.GetString("Inactive")
            };
            this.Alignment3.Add(this.PrimaryButton);
            this.HBox4.Add(this.Alignment3);

            Box.BoxChild w14 = (Box.BoxChild) this.HBox4 [this.Alignment3];
            w14.Position = 0;
            this.HBox3.Add(this.HBox4);

            Box.BoxChild w15 = (Box.BoxChild) this.HBox3 [this.HBox4];
            w15.Position = 1;
            w15.Expand   = false;
            w15.Fill     = false;
            this.VBox1.Add(this.HBox3);

            Box.BoxChild w16 = (Box.BoxChild) this.VBox1 [this.HBox3];
            w16.Position = 3;
            w16.Expand   = true;
            w16.Fill     = false;

            Add(this.VBox1);
            if ((this.Child != null))
            {
                this.Child.ShowAll();
            }

            this.PrimaryButton.HasDefault = true;
            Show();
            this.DeleteEvent += OnDeleteEvent;
            this.RepairGameAction.Activated    += OnRepairGameActionActivated;
            this.ReinstallGameAction.Activated += OnReinstallGameActionActivated;
            this.PrimaryButton.Clicked         += OnPrimaryButtonClicked;
        }
        void _BGWSemesterMoralScoresTotal_DoWork(object sender, DoWorkEventArgs e)
        {
            object[] args       = (object[])e.Argument;
            int      schoolyear = (int)args[0];
            int      semester   = (int)args[1];
            bool     over100    = (bool)args[2];
            int      sizeIndex  = (int)args[3];
            Dictionary <string, List <string> > userType = (Dictionary <string, List <string> >)args[4];

            _BGWSemesterMoralScoresTotal.ReportProgress(1);

            #region 取得資料

            AccessHelper         dataSeed    = new AccessHelper();
            List <ClassRecord>   allClasses  = dataSeed.ClassHelper.GetSelectedClass();
            List <StudentRecord> allStudents = new List <StudentRecord>();
            Dictionary <string, List <StudentRecord> > classStudents = new Dictionary <string, List <StudentRecord> >();
            AngelDemonComputer computer = new AngelDemonComputer();

            int maxStudents    = 0;
            int totalStudent   = 0;
            int currentStudent = 1;

            foreach (ClassRecord aClass in allClasses)
            {
                List <StudentRecord> studnetList = aClass.Students;
                if (studnetList.Count > maxStudents)
                {
                    maxStudents = studnetList.Count;
                }
                allStudents.AddRange(studnetList);

                //computer.FillDemonScore(dataSeed, schoolyear, semester, studnetList);

                classStudents.Add(aClass.ClassID, studnetList);
                totalStudent += studnetList.Count;
            }

            computer.FillDemonScore(dataSeed, schoolyear, semester, allStudents);
            dataSeed.StudentHelper.FillSemesterEntryScore(true, allStudents);
            if (semester == 2)
            {
                dataSeed.StudentHelper.FillSchoolYearEntryScore(true, allStudents);
                dataSeed.StudentHelper.FillSemesterHistory(allStudents);
            }

            SystemInformation.getField("DiffItem");
            SystemInformation.getField("Degree");

            Dictionary <string, decimal> degreeList = (Dictionary <string, decimal>)SystemInformation.Fields["Degree"];

            #endregion

            #region 產生表格
            Workbook template  = new Workbook();
            Workbook prototype = new Workbook();

            //列印尺寸
            if (sizeIndex == 0)
            {
                template.Open(new MemoryStream(Properties.Resources.德行成績總表A3), FileFormatType.Excel2003);
            }
            else if (sizeIndex == 1)
            {
                template.Open(new MemoryStream(Properties.Resources.德行成績總表A4), FileFormatType.Excel2003);
            }
            else if (sizeIndex == 2)
            {
                template.Open(new MemoryStream(Properties.Resources.德行成績總表B4), FileFormatType.Excel2003);
            }
            prototype.Copy(template);

            Worksheet templateSheet  = template.Worksheets[0];
            Worksheet prototypeSheet = prototype.Worksheets[0];

            Range tempInfoAndReward   = templateSheet.Cells.CreateRange(0, 17, true);
            Range tempAbsence         = templateSheet.Cells.CreateRange(17, 2, true);
            Range tempBeforeOtherDiff = templateSheet.Cells.CreateRange(19, 3, true);
            Range tempOtherDiff       = templateSheet.Cells.CreateRange(22, 1, true);
            Range tempAfterOtherDiff  = templateSheet.Cells.CreateRange(25, 2, true);

            Dictionary <string, int> columnIndexTable = new Dictionary <string, int>();

            Dictionary <string, List <string> > periodAbsence = new Dictionary <string, List <string> >();

            //紀錄獎懲的 Column Index
            columnIndexTable.Add("大功", 4);
            columnIndexTable.Add("小功", 6);
            columnIndexTable.Add("嘉獎", 8);
            columnIndexTable.Add("大過", 10);
            columnIndexTable.Add("小過", 12);
            columnIndexTable.Add("警告", 14);
            columnIndexTable.Add("獎懲小計", 16);

            //缺曠加減分
            int ptColIndex = 17;
            foreach (SmartSchool.Evaluation.AngelDemonComputer.UsefulPeriodAbsence var in computer.UsefulPeriodAbsences)
            {
                if (!periodAbsence.ContainsKey(var.Period))
                {
                    periodAbsence.Add(var.Period, new List <string>());
                }
                if (!periodAbsence[var.Period].Contains(var.Absence))
                {
                    periodAbsence[var.Period].Add(var.Absence);
                }

                prototypeSheet.Cells.CreateRange(ptColIndex, 2, true).Copy(tempAbsence);
                ptColIndex += 2;
            }
            //foreach (string period in userType.Keys)
            //{
            //    if (!periodAbsence.ContainsKey(period))
            //    {
            //        periodAbsence.Add(period, new List<string>());
            //        foreach (string absence in userType[period])
            //        {
            //            if (!periodAbsence[period].Contains(absence))
            //            {
            //                periodAbsence[period].Add(absence);
            //                prototypeSheet.Cells.CreateRange(ptColIndex, 2, true).Copy(tempAbsence);
            //                ptColIndex += 2;
            //            }
            //        }
            //    }
            //}

            ptColIndex = 17;

            foreach (string period in periodAbsence.Keys)
            {
                prototypeSheet.Cells.CreateRange(2, ptColIndex, 1, periodAbsence[period].Count * 2).Merge();
                prototypeSheet.Cells[2, ptColIndex].PutValue(period);
                foreach (string absence in periodAbsence[period])
                {
                    prototypeSheet.Cells[3, ptColIndex].PutValue(absence);

                    columnIndexTable.Add(period + "_" + absence, ptColIndex);

                    ptColIndex += 2;
                }
            }
            prototypeSheet.Cells.CreateRange(1, 17, 1, ptColIndex - 15).Merge();
            prototypeSheet.Cells[1, 17].PutValue("缺曠加減分");

            columnIndexTable.Add("全勤", ptColIndex);
            columnIndexTable.Add("缺曠小計", ptColIndex + 1);

            prototypeSheet.Cells.CreateRange(ptColIndex, 3, true).Copy(tempBeforeOtherDiff);
            ptColIndex += 3;

            //導師加減分
            columnIndexTable.Add("導師加減分", ptColIndex - 1);

            //其他加減分項目
            foreach (string var in (List <string>)SystemInformation.Fields["DiffItem"])
            {
                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue(var);

                columnIndexTable.Add(var, ptColIndex);

                ptColIndex++;
            }

            if (semester == 2)
            {
                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue("上學期德行成績");
                columnIndexTable.Add("上學期成績", ptColIndex++);

                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue("學期德行成績");
                columnIndexTable.Add("學期成績", ptColIndex++);

                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue("等第");
                columnIndexTable.Add("等第", ptColIndex++);

                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue("學年德行成績");
                columnIndexTable.Add("學年成績", ptColIndex++);
            }
            else
            {
                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue("學期德行成績");
                columnIndexTable.Add("學期成績", ptColIndex++);

                prototypeSheet.Cells.CreateRange(ptColIndex, 1, true).Copy(tempOtherDiff);
                prototypeSheet.Cells[1, ptColIndex].PutValue("等第");
                columnIndexTable.Add("等第", ptColIndex++);
            }
            prototypeSheet.Cells.CreateRange(ptColIndex, 2, true).Copy(tempAfterOtherDiff);
            columnIndexTable.Add("評語", ptColIndex++);
            columnIndexTable.Add("更改等第", ptColIndex++);

            //加上底線
            prototypeSheet.Cells.CreateRange(maxStudents + 5, 0, 1, ptColIndex).SetOutlineBorder(BorderType.TopBorder, CellBorderType.Medium, System.Drawing.Color.Black);

            //填入製表日期
            prototypeSheet.Cells[0, 0].PutValue("製表日期:" + DateTime.Today.ToShortDateString());

            //填入標題
            prototypeSheet.Cells.CreateRange(0, 4, 1, ptColIndex - 4).Merge();
            prototypeSheet.Cells[0, 4].PutValue(SystemInformation.SchoolChineseName + " " + schoolyear + " 學年度 " + ((semester == 1) ? "上" : "下") + " 學期 德行成績總表        ");

            Range ptEachRow = prototypeSheet.Cells.CreateRange(5, 1, false);

            for (int i = 5; i < maxStudents + 5; i++)
            {
                prototypeSheet.Cells.CreateRange(i, 1, false).Copy(ptEachRow);
            }

            Range pt = prototypeSheet.Cells.CreateRange(0, maxStudents + 5, false);

            #endregion

            #region 填入表格
            Workbook wb = new Workbook();
            wb.Copy(prototype);
            Worksheet ws = wb.Worksheets[0];

            int index         = 0;
            int dataIndex     = 0;
            int classTotalRow = maxStudents + 5;

            foreach (ClassRecord aClass in allClasses)
            {
                //複製完成後的樣板
                ws.Cells.CreateRange(index, classTotalRow, false).Copy(pt);

                //填入班級名稱
                ws.Cells[index + 1, 0].PutValue(aClass.ClassName);

                Dictionary <string, int> degreeCount = new Dictionary <string, int>();
                foreach (string key in degreeList.Keys)
                {
                    degreeCount.Add(key, 0);
                }

                dataIndex = index + 5;

                foreach (StudentRecord aStudent in classStudents[aClass.ClassID])
                {
                    ws.Cells[dataIndex, 0].PutValue(aStudent.SeatNo);
                    ws.Cells[dataIndex, 1].PutValue(aStudent.StudentName);
                    ws.Cells[dataIndex, 2].PutValue(aStudent.StudentNumber);

                    decimal?score        = null;
                    decimal rewardScore  = 0;
                    decimal absenceScore = 0;
                    decimal diffScore    = 0;
                    int     gradeYear    = -1;

                    XmlElement demonScore = (XmlElement)aStudent.Fields["DemonScore"];

                    //score = decimal.Parse(demonScore.GetAttribute("Score"));
                    foreach (SemesterEntryScoreInfo info in aStudent.SemesterEntryScoreList)
                    {
                        if (info.SchoolYear == schoolyear && info.Semester == semester && info.Entry == "德行")
                        {
                            score     = (decimal?)info.Score;
                            gradeYear = info.GradeYear;
                            break;
                        }
                    }

                    foreach (XmlElement var in demonScore.SelectNodes("SubScore"))
                    {
                        if (var.GetAttribute("Type") == "基分")
                        {
                            ws.Cells[dataIndex, 3].PutValue(var.GetAttribute("Score"));
                        }
                        else if (var.GetAttribute("Type") == "獎懲")
                        {
                            int colIndex = columnIndexTable[var.GetAttribute("Name")];
                            if (decimal.Parse(var.GetAttribute("Count")) != 0)
                            {
                                ws.Cells[dataIndex, colIndex].PutValue(var.GetAttribute("Count"));
                            }
                            if (decimal.Parse(var.GetAttribute("Score")) != 0)
                            {
                                ws.Cells[dataIndex, colIndex + 1].PutValue(var.GetAttribute("Score"));
                            }
                            rewardScore += decimal.Parse(var.GetAttribute("Score"));
                        }
                        else if (var.GetAttribute("Type") == "缺曠")
                        {
                            string pa = var.GetAttribute("PeriodType") + "_" + var.GetAttribute("Absence");
                            if (columnIndexTable.ContainsKey(pa))
                            {
                                int colIndex = columnIndexTable[pa];
                                if (decimal.Parse(var.GetAttribute("Count")) != 0)
                                {
                                    ws.Cells[dataIndex, colIndex].PutValue(var.GetAttribute("Count"));
                                }
                                if (decimal.Parse(var.GetAttribute("Score")) != 0)
                                {
                                    ws.Cells[dataIndex, colIndex + 1].PutValue(var.GetAttribute("Score"));
                                }
                            }
                            absenceScore += decimal.Parse(var.GetAttribute("Score"));
                        }
                        else if (var.GetAttribute("Type") == "加減分")
                        {
                            int colIndex = columnIndexTable[var.GetAttribute("DiffItem")];
                            if (decimal.Parse(var.GetAttribute("Score")) != 0)
                            {
                                ws.Cells[dataIndex, colIndex].PutValue(var.GetAttribute("Score"));
                            }
                            diffScore += decimal.Parse(var.GetAttribute("Score"));
                        }
                        else if (var.GetAttribute("Type") == "全勤")
                        {
                            int colIndex = columnIndexTable["全勤"];
                            if (decimal.Parse(var.GetAttribute("Score")) != 0)
                            {
                                ws.Cells[dataIndex, colIndex].PutValue(var.GetAttribute("Score"));
                            }
                            absenceScore += decimal.Parse(var.GetAttribute("Score"));
                        }
                    }

                    //填入獎懲小計
                    if (rewardScore != 0)
                    {
                        ws.Cells[dataIndex, columnIndexTable["獎懲小計"]].PutValue(rewardScore.ToString());
                    }
                    //填入缺曠小計
                    if (absenceScore != 0)
                    {
                        ws.Cells[dataIndex, columnIndexTable["缺曠小計"]].PutValue(absenceScore.ToString());
                    }

                    //填入學業成績試算
                    if (!over100 && score > 100)
                    {
                        score = 100;
                    }
                    ws.Cells[dataIndex, columnIndexTable["學期成績"]].PutValue(score.ToString());

                    //填入上學期&學年成績
                    if (semester == 2)
                    {
                        //沒有學期歷程就用當下的學期
                        if (gradeYear == -1 && schoolyear == SystemInformation.SchoolYear)
                        {
                            int.TryParse(aStudent.RefClass.GradeYear, out gradeYear);
                        }
                        //填入上學期成績
                        foreach (SemesterEntryScoreInfo semesterEntryScore in aStudent.SemesterEntryScoreList)
                        {
                            if (semesterEntryScore.Entry == "德行" && semesterEntryScore.GradeYear == gradeYear && semesterEntryScore.Semester == 1)
                            {
                                if (!over100 && semesterEntryScore.Score > 100)
                                {
                                    ws.Cells[dataIndex, columnIndexTable["上學期成績"]].PutValue("100");
                                }
                                else
                                {
                                    ws.Cells[dataIndex, columnIndexTable["上學期成績"]].PutValue(semesterEntryScore.Score.ToString());
                                }
                                break;
                            }
                        }

                        //填入學年成績
                        foreach (SchoolYearEntryScoreInfo schoolyearEntryScore in aStudent.SchoolYearEntryScoreList)
                        {
                            if (schoolyearEntryScore.Entry == "德行" && schoolyearEntryScore.GradeYear == gradeYear)
                            {
                                if (!over100 && schoolyearEntryScore.Score > 100)
                                {
                                    ws.Cells[dataIndex, columnIndexTable["學年成績"]].PutValue("100");
                                }
                                else
                                {
                                    ws.Cells[dataIndex, columnIndexTable["學年成績"]].PutValue(schoolyearEntryScore.Score.ToString());
                                }
                                break;
                            }
                        }
                    }

                    //填入等第
                    string degree = score == null?"": computer.ParseLevel((decimal)score);
                    ws.Cells[dataIndex, columnIndexTable["等第"]].PutValue(degree);

                    //計算等第出現次數
                    if (degreeCount.ContainsKey(degree))
                    {
                        degreeCount[degree]++;
                    }

                    //評語
                    if (demonScore.SelectSingleNode("Others/@Comment") != null)
                    {
                        ws.Cells[dataIndex, columnIndexTable["評語"]].PutValue(demonScore.SelectSingleNode("Others/@Comment").InnerText);
                    }

                    dataIndex++;

                    //回報進度
                    _BGWSemesterMoralScoresTotal.ReportProgress((int)(currentStudent++ *100.0 / totalStudent));
                }

                ws.Cells.CreateRange(index + classTotalRow + 1, 0, 1, ptColIndex).Merge();
                StringBuilder degreeSumString = new StringBuilder("");
                degreeSumString.Append("德行等第統計    ");
                foreach (string key in degreeCount.Keys)
                {
                    degreeSumString.Append(key + "等: " + degreeCount[key].ToString() + "    ");
                }
                ws.Cells[index + classTotalRow + 1, 0].Style.Font.Size = 12;
                ws.Cells.CreateRange(index + classTotalRow + 1, 1, false).RowHeight = 20;
                ws.Cells[index + classTotalRow + 1, 0].PutValue(degreeSumString.ToString());
                ws.Cells[index + classTotalRow + 1, 0].Style.HorizontalAlignment = TextAlignmentType.Left;

                index += classTotalRow + 3;
                ws.HPageBreaks.Add(index, ptColIndex);
            }

            #endregion

            e.Result = wb;
        }
Example #6
0
        public static bool StartupProcess()
        {
            // Profile our initialization
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            // Fire up our server
            if (!StartServer())
            {
                if (!arg_replace)
                {
                    Logger.Log.Error("Could not set up the listener for beagrep requests.  "
                                     + "There is probably another beagrepd instance running.  "
                                     + "Use --replace to replace the running service");
                    Environment.Exit(1);
                }

                ReplaceExisting();
            }

            // Set up out-of-process indexing
            LuceneQueryable.IndexerHook = new LuceneQueryable.IndexerCreator(RemoteIndexer.NewRemoteIndexer);

            Config config = Conf.Get(Conf.Names.DaemonConfig);

            // Initialize synchronization to keep the indexes local if PathFinder.StorageDir
            // is on a non-block device, or if BEAGREP_SYNCHRONIZE_LOCALLY is set

            if ((!SystemInformation.IsPathOnBlockDevice(PathFinder.StorageDir) &&
                 config.GetOption(Conf.Names.IndexSynchronization, true)) ||
                Environment.GetEnvironmentVariable("BEAGREP_SYNCHRONIZE_LOCALLY") != null)
            {
                IndexSynchronization.Initialize();
            }

            // Start the query driver.
            Logger.Log.Debug("Starting QueryDriver");
            QueryDriver.Start();

            // Start our battery monitor so we can shut down the
            // scheduler if needed.
            BatteryMonitor.Init();

            bool initially_on_battery = !BatteryMonitor.UsingAC && !config.GetOption(Conf.Names.IndexOnBattery, false);

            // Start the Global Scheduler thread
            if (!arg_disable_scheduler)
            {
                if (!initially_on_battery)
                {
                    Logger.Log.Debug("Starting Scheduler thread");
                    Scheduler.Global.Start();
                }
                else
                {
                    Log.Debug("Beagrep started on battery, not starting scheduler thread");
                }
            }

            // Start our Inotify threads
            Inotify.Start();

            // Test if the FileAdvise stuff is working: This will print a
            // warning if not.  The actual advice calls will fail silently.
            FileAdvise.TestAdvise();

#if ENABLE_AVAHI
            zeroconf = new Beagrep.Daemon.Network.Zeroconf();
#endif

            Conf.WatchForUpdates();

            stopwatch.Stop();

            Logger.Log.Debug("Daemon initialization finished after {0}", stopwatch);

            SystemInformation.LogMemoryUsage();

            if (arg_indexing_test_mode)
            {
                Thread.Sleep(1000);                  // Ugly paranoia: wait a second for the backends to settle.
                Logger.Log.Debug("Running in indexing test mode");
                Scheduler.Global.EmptyQueueEvent += OnEmptySchedulerQueue;
                Scheduler.Global.Add(null);                  // pulse the scheduler
            }

            return(false);
        }
Example #7
0
        public SMBIOS()
        {
            int p = (int)Environment.OSVersion.Platform;
            if ((p == 4) || (p == 128))
            {
                this.raw = null;
                this.table = null;

                string boardVendor = ReadSysFS("/sys/class/dmi/id/board_vendor");
                string boardName = ReadSysFS("/sys/class/dmi/id/board_name");
                string boardVersion = ReadSysFS("/sys/class/dmi/id/board_version");
                this.baseBoardInformation = new BaseBoardInformation(
                  boardVendor, boardName, boardVersion, null);

                string systemVendor = ReadSysFS("/sys/class/dmi/id/sys_vendor");
                string productName = ReadSysFS("/sys/class/dmi/id/product_name");
                string productVersion = ReadSysFS("/sys/class/dmi/id/product_version");
                this.systemInformation = new SystemInformation(systemVendor,
                  productName, productVersion, null, null);

                string biosVendor = ReadSysFS("/sys/class/dmi/id/bios_vendor");
                string biosVersion = ReadSysFS("/sys/class/dmi/id/bios_version");
                this.biosInformation = new BIOSInformation(biosVendor, biosVersion);

                this.memoryDevices = new MemoryDevice[0];
            }
            else
            {
                List<Structure> structureList = new List<Structure>();
                List<MemoryDevice> memoryDeviceList = new List<MemoryDevice>();

                raw = null;
                byte majorVersion = 0;
                byte minorVersion = 0;
                try
                {
                    ManagementObjectCollection collection;
                    using (ManagementObjectSearcher searcher =
                      new ManagementObjectSearcher("root\\WMI",
                        "SELECT * FROM MSSMBios_RawSMBiosTables"))
                    {
                        collection = searcher.Get();
                    }

                    foreach (ManagementObject mo in collection)
                    {
                        raw = (byte[])mo["SMBiosData"];
                        majorVersion = (byte)mo["SmbiosMajorVersion"];
                        minorVersion = (byte)mo["SmbiosMinorVersion"];
                        break;
                    }
                }
                catch { }

                if (majorVersion > 0 || minorVersion > 0)
                    version = new Version(majorVersion, minorVersion);

                if (raw != null && raw.Length > 0)
                {
                    int offset = 0;
                    byte type = raw[offset];
                    while (offset + 4 < raw.Length && type != 127)
                    {

                        type = raw[offset];
                        int length = raw[offset + 1];
                        ushort handle = (ushort)((raw[offset + 2] << 8) | raw[offset + 3]);

                        if (offset + length > raw.Length)
                            break;
                        byte[] data = new byte[length];
                        Array.Copy(raw, offset, data, 0, length);
                        offset += length;

                        List<string> stringsList = new List<string>();
                        if (offset < raw.Length && raw[offset] == 0)
                            offset++;

                        while (offset < raw.Length && raw[offset] != 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (offset < raw.Length && raw[offset] != 0)
                            {
                                sb.Append((char)raw[offset]); offset++;
                            }
                            offset++;
                            stringsList.Add(sb.ToString());
                        }
                        offset++;
                        switch (type)
                        {
                            case 0x00:
                                this.biosInformation = new BIOSInformation(
                                  type, handle, data, stringsList.ToArray());
                                structureList.Add(this.biosInformation); break;
                            case 0x01:
                                this.systemInformation = new SystemInformation(
                                  type, handle, data, stringsList.ToArray());
                                structureList.Add(this.systemInformation); break;
                            case 0x02:
                                this.baseBoardInformation = new BaseBoardInformation(
                         type, handle, data, stringsList.ToArray());
                                structureList.Add(this.baseBoardInformation); break;
                            case 0x04:
                                this.processorInformation = new ProcessorInformation(
                         type, handle, data, stringsList.ToArray());
                                structureList.Add(this.processorInformation); break;
                            case 0x11:
                                MemoryDevice m = new MemoryDevice(
                         type, handle, data, stringsList.ToArray());
                                memoryDeviceList.Add(m);
                                structureList.Add(m); break;
                            default:
                                structureList.Add(new Structure(
                         type, handle, data, stringsList.ToArray())); break;
                        }
                    }
                }

                memoryDevices = memoryDeviceList.ToArray();
                table = structureList.ToArray();
            }
        }
    public TurnState UpdateSystemMenu(TurnState state)
    {
        if (CommonFunction.IsNull(UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject) == false)
        {
            bool   isError = false;
            string target  = "";
            try
            {
                target = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.name;
            }
            catch (MissingReferenceException)
            {
                isError = true;
            }

            if (isError == false)
            {
                if (target == "SystemInputFieldMoveUp")
                {
                    SetKeyInfoField(SystemMoveUpHeader, KeyType.MoveUp);
                }
                else if (target == "SystemInputFieldMoveDown")
                {
                    SetKeyInfoField(SystemMoveDownHeader, KeyType.MoveDown);
                }
                else if (target == "SystemInputFieldMoveLeft")
                {
                    SetKeyInfoField(SystemMoveLeftHeader, KeyType.MoveLeft);
                }
                else if (target == "SystemInputFieldMoveRight")
                {
                    SetKeyInfoField(SystemMoveRightHeader, KeyType.MoveRight);
                }
                else if (target == "SystemInputFieldMoveSlash")
                {
                    SetKeyInfoField(SystemMoveSlashHeader, KeyType.XMove);
                }
                else if (target == "SystemInputFieldDir")
                {
                    SetKeyInfoField(SystemDirHeader, KeyType.ChangeDirection);
                }
                else if (target == "SystemInputFieldDeathBlow")
                {
                    SetKeyInfoField(SystemDeathBlowHeader, KeyType.DeathBlow);
                }
                else if (target == "SystemInputFieldMenu")
                {
                    SetKeyInfoField(SystemMenuHeader, KeyType.MenuOpen);
                }
                else if (target == "SystemInputFieldMlog")
                {
                    SetKeyInfoField(SystemMlogHeader, KeyType.MessageLog);
                }
                else if (target == "SystemInputFieldDash")
                {
                    SetKeyInfoField(SystemDashHeader, KeyType.Dash);
                }
                else if (target == "SystemInputFieldAttack")
                {
                    SetKeyInfoField(SystemAttackHeader, KeyType.Attack);
                }
                else if (target == "SystemInputFieldIdle")
                {
                    SetKeyInfoField(SystemIdleHeader, KeyType.Idle);
                }
                else if (target == "SystemInputFieldDisplay")
                {
                    SetKeyInfoField(SystemKeyDisplayHeader, KeyType.KeyDisplay);
                }
                else if (target == "SystemInputFieldOk")
                {
                    SetKeyInfoMenu(SystemOkHeader, KeyType.MenuOk);
                }
                else if (target == "SystemInputFieldCancel")
                {
                    SetKeyInfoMenu(SystemCancelHeader, KeyType.MenuCancel);
                }
                else if (target == "SystemInputFieldOption")
                {
                    SetKeyInfoMenu(SystemOptionHeader, KeyType.LookOption);
                }
                else if (target == "SystemInputFieldSort")
                {
                    SetKeyInfoMenu(SystemSortHeader, KeyType.ItemSort);
                }
                else if (target == "SystemInputFieldMultiSelect")
                {
                    SetKeyInfoMenu(SystemMultiSelectHeader, KeyType.MenuMultiSelectOk);
                }
                else if (target == "SystemInputFieldDTop")
                {
                    SetVertical();
                }
                else if (target == "SystemInputFieldDLeft")
                {
                    SetHorizontal();
                }
            }
        }
        //閉じる
        else if (Input.GetKeyDown(KeyControlInformation.Info.MenuCancel))
        {
            IsClose = true;
        }
        if (IsClose == true)
        {
            //データを保存
            SystemInformation s = new SystemInformation();
            s.CharacterName = pl.DisplayName;
            s.IsBgm         = MusicInformation.Music.IsMusicOn;
            s.BGMVolume     = CommonFunction.PercentToInt(MusicInformation.Music.Volume);
            s.IsSound       = SoundInformation.Sound.IsPlay;
            s.SoundVolume   = CommonFunction.PercentToInt(SoundInformation.Sound.Volume);
            s.IsVoice       = VoiceInformation.Voice.IsPlay;
            s.VoiceVolume   = CommonFunction.PercentToInt(VoiceInformation.Voice.Volume);
            SaveDataInformation.SaveValue(KeyControlInformation.Info);
            SaveDataInformation.SaveValue(s);
            SaveDataInformation.Submit();

            //Debug.Log(temp.GetJsonData());

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.MenuCancel);
            SystemPanel.SetActive(false);
            state = TurnState.FirstMenu;
        }

        return(state);
    }
 public void Test_f()
 {
     Assert.AreEqual(1, SystemInformation.f());
 }
Example #10
0
        static void Main()
        {
            /*
             * try
             * {
             */
            SystemInformation info = new SystemInformation();


            //
            // Load Game Settings
            //



            /*
             * // The 'using' idiom guarantees proper resource cleanup.
             * // We request 30 UpdateFrame events per second, and unlimited
             * // RenderFrame events (as fast as the computer can handle).
             *
             * AudioContext audioContext = null;
             * StreamWriter statsFileWriter = null;
             * TankGame game = null;
             *
             *
             * try
             * {
             *
             *  try
             *  {
             *      audioContext = new AudioContext();
             *
             *
             *
             *      //
             *      // Load Audio
             *      //
             *      int audioBufferHandle = AL.GenBuffer();
             *      int audioSourceHandle = AL.GenSource();
             *      //int state;
             *
             *      WaveFormat soundFileFormat;
             *      Byte[] soundData = Wave.LoadWaveFile("CitadelKDrew.wav", out soundFileFormat);
             *      Console.WriteLine(soundFileFormat);
             *      AL.BufferData(audioBufferHandle, GetSoundFormat(soundFileFormat), soundData, soundData.Length, (int)soundFileFormat.samplesPerSecond);
             *
             *      AL.Source(audioSourceHandle, ALSourcei.Buffer, audioBufferHandle);
             *      //AL.Source(audioSourceHandle, ALSourcei.ByteOffset, 0);
             *      AL.SourcePlay(audioSourceHandle);
             *
             *      // Query the source to find out when it stops playing.
             *      do
             *      {
             *          Thread.Sleep(250);
             *          Trace.Write(".");
             *          AL.GetSource(source, ALGetSourcei.SourceState, out state);
             *      }
             *      while ((ALSourceState)state == ALSourceState.Playing);
             *
             *      Trace.WriteLine("");
             *
             *      AL.SourceStop(source);
             *      AL.DeleteSource(source);
             *      AL.DeleteBuffer(buffer);
             *  }
             *  catch (Exception e)
             *  {
             *      Console.WriteLine("Sound failed: " + e.ToString());
             *  }
             *
             *  String statisticsFileName = @"C:\temp\hexagon.stats";
             *  try
             *  {
             *      statsFileWriter = new StreamWriter(new FileStream(statisticsFileName, FileMode.Create));
             *  }
             *  catch (Exception e)
             *  {
             *      Console.WriteLine("Failed to open statistics file '{0}'", statisticsFileName);
             *  }
             *
             *  game = new TankGame();
             *  //game.CustomGameLoop(statsFileWriter);
             *  game.CustomGameLoop(null);
             *
             * }
             * finally
             * {
             *  if (game != null) game.Dispose();
             *  if (statsFileWriter != null) statsFileWriter.Dispose();
             *  if (audioContext != null) audioContext.Dispose();
             * }
             *
             *
             */

            TankLevel level = new TankLevel();

            level.width  = 800;
            level.height = 800;


            TankGame game = new TankGame(level);

            game.CustomGameLoop(null);

            /*
             * }
             * catch (Exception e)
             * {
             * throw;
             * }
             */
        }
Example #11
0
    static int Main(string[] args)
    {
        SystemInformation.SetProcessName ("beagle-extract-content");

        if (args.Length < 1 || Array.IndexOf (args, "--help") != -1) {
            PrintUsage ();
            return 0;
        }

        if (Array.IndexOf (args, "--debug") == -1)
            Log.Disable ();

        if (Array.IndexOf (args, "--version") != -1) {
            VersionFu.PrintVersion ();
            return 0;
        }

        if (Array.IndexOf (args, "--tokenize") != -1)
            tokenize = true;

        if (Array.IndexOf (args, "--analyze") != -1)
            analyze = true;

        if (Array.IndexOf (args, "--show-generated") != -1 || Array.IndexOf (args, "--show-children") != -1)
            show_generated = true;

        StreamWriter writer = null;
        string outfile = null;
        foreach (string arg in args) {

            // mime-type option
            if (arg.StartsWith ("--mimetype=")) {
                mime_type = arg.Substring (11);
                continue;
            // output file option
            // we need this in case the output contains different encoding
            // printing to Console might not always display properly
            } else if (arg.StartsWith ("--outfile=")) {
                outfile = arg.Substring (10);
                Console.WriteLine ("Redirecting output to " + outfile);
                FileStream f = new FileStream (outfile, FileMode.Create);
                writer = new StreamWriter (f, System.Text.Encoding.UTF8);
                continue;
            } else if (arg.StartsWith ("--")) // option, skip it
                continue;

            Uri uri = UriFu.PathToFileUri (arg);
            Indexable indexable = new Indexable (uri);
            if (mime_type != null)
                indexable.MimeType = mime_type;

            try {
                if (writer != null) {
                    Console.SetOut (writer);
                }

                Display (indexable);
                if (writer != null) {
                    writer.Flush ();
                }

                if (outfile != null) {
                    StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
                    standardOutput.AutoFlush = true;
                    Console.SetOut(standardOutput);
                }

            } catch (Exception e) {
                Console.WriteLine ("Unable to filter {0}: {1}", uri, e.Message);
                return -1;
            }

            // Super Lame Hack: gtk-sharp up to 2.10 requires a main loop
            // to dispose of any managed wrappers around GObjects.  Since
            // we don't have one, we'll process all the pending items in
            // a loop here.  This is particularly an issue with maildirs,
            // because we need the loop to clean up after GMime.  Without
            // it, GMime's streams are never completely unref'd, the
            // file descriptors aren't closed, and we run out and crash.
            while (GLib.MainContext.Pending ())
                GLib.MainContext.Iteration ();
        }
        if (writer != null)
            writer.Close ();

        return 0;
    }
Example #12
0
 public void SystemInformation_GetHorizontalScrollBarArrowWidthForDpi_LogicalDpi_HorizontalScrollBarArrowWidth()
 {
     Assert.Equal(SystemInformation.HorizontalScrollBarArrowWidth, SystemInformation.GetHorizontalScrollBarArrowWidthForDpi(LogicalDpi));
 }
Example #13
0
 public void SystemInformation_VerticalScrollBarArrowHeight_LogicalDpi_ReturnsVerticalScrollBarArrowHeight()
 {
     Assert.Equal(SystemInformation.VerticalScrollBarArrowHeight, SystemInformation.VerticalScrollBarArrowHeightForDpi(LogicalDpi));
 }
Example #14
0
        public bool IsRebootPending()
        {
            var sysInfo = new SystemInformation();

            return(sysInfo.RebootRequired);
        }
Example #15
0
 /// <summary>
 /// Builds the system information object to json
 /// </summary>
 public void GetSystemInformation()
 {
     _builder.WriteMessage(SystemInformation.ToObject());
 }
Example #16
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", IdeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            GettextCatalog.Initialize();

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            if (!Platform.IsWindows)
            {
                // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
                // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
                // to be too late to prevent the MEF composition and the static registrar from
                // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
                ResolveMSBuildAssemblies();
            }

            Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.Initialization.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize();
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            string   socket_filename = null;
            EndPoint ep = null;

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            AddinManager.AddinLoadError += OnAddinError;

            var startupInfo = new StartupInfo(args);

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                Counters.Initialization.Trace("Pre-Initializing Runtime to load files in existing window");
                Runtime.Initialize(true);
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            Counters.Initialization.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            IdeApp.Customizer.OnCoreInitialized();

            Counters.Initialization.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            ProgressMonitor monitor = new MonoDevelop.Core.ProgressMonitoring.ConsoleProgressMonitor();

            monitor.BeginTask(GettextCatalog.GetString("Starting {0}", BrandingService.ApplicationName), 2);

            //make sure that the platform service is initialised so that the Mac platform can subscribe to open-document events
            Counters.Initialization.Trace("Initializing Platform Service");
            DesktopService.Initialize();

            monitor.Step(1);

            if (options.IpcTcp)
            {
                listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                ep            = new IPEndPoint(IPAddress.Loopback, ipcBasePort + HashSdbmBounded(Environment.UserName));
            }
            else
            {
                socket_filename = "/tmp/md-" + Environment.GetEnvironmentVariable("USER") + "-socket";
                listen_socket   = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
                ep = new UnixEndPoint(socket_filename);
            }

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles)
            {
                try {
                    StringBuilder builder = new StringBuilder();
                    foreach (var file in startupInfo.RequestedFileList)
                    {
                        builder.AppendFormat("{0};{1};{2}\n", file.FileName, file.Line, file.Column);
                    }
                    listen_socket.Connect(ep);
                    listen_socket.Send(Encoding.UTF8.GetBytes(builder.ToString()));
                    return(0);
                } catch {
                    // Reset the socket
                    if (null != socket_filename && File.Exists(socket_filename))
                    {
                        File.Delete(socket_filename);
                    }
                }
            }

            Counters.Initialization.Trace("Checking System");

            CheckFileWatcher();

            Exception error            = null;
            int       reportedFailures = 0;

            try {
                Counters.Initialization.Trace("Loading Icons");
                //force initialisation before the workbench so that it can register stock icons for GTK before they get requested
                ImageService.Initialize();
                LocalizationService.Initialize();

                // If we display an error dialog before the main workbench window on OS X then a second application menu is created
                // which is then replaced with a second empty Apple menu.
                // XBC #33699
                Counters.Initialization.Trace("Initializing IdeApp");
                IdeApp.Initialize(monitor);

                if (errorsList.Count > 0)
                {
                    using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), false)) {
                        if (!dlg.Run())
                        {
                            return(1);
                        }
                    }
                    reportedFailures = errorsList.Count;
                }

                if (!CheckSCPlugin())
                {
                    return(1);
                }

                // Load requested files
                Counters.Initialization.Trace("Opening Files");

                // load previous combine
                RecentFile openedProject = null;
                if (IdeApp.Preferences.LoadPrevSolutionOnStartup && !startupInfo.HasSolutionFile && !IdeApp.Workspace.WorkspaceItemIsOpening && !IdeApp.Workspace.IsOpen)
                {
                    openedProject = DesktopService.RecentFiles.MostRecentlyUsedProject;
                    if (openedProject != null)
                    {
                        var metadata = GetOpenWorkspaceOnStartupMetadata();
                        IdeApp.Workspace.OpenWorkspaceItem(openedProject.FileName, true, true, metadata).ContinueWith(t => IdeApp.OpenFiles(startupInfo.RequestedFileList, metadata), TaskScheduler.FromCurrentSynchronizationContext());
                        startupInfo.OpenedRecentProject = true;
                    }
                }
                if (openedProject == null)
                {
                    IdeApp.OpenFiles(startupInfo.RequestedFileList, GetOpenWorkspaceOnStartupMetadata());
                    startupInfo.OpenedFiles = startupInfo.HasFiles;
                }

                monitor.Step(1);
            } catch (Exception e) {
                error = e;
            } finally {
                monitor.Dispose();
            }

            if (error != null)
            {
                string message = BrandingService.BrandApplicationName(GettextCatalog.GetString("MonoDevelop failed to start"));
                MessageService.ShowFatalError(message, null, error);
                return(1);
            }

            if (errorsList.Count > reportedFailures)
            {
                using (AddinLoadErrorDialog dlg = new AddinLoadErrorDialog((AddinError[])errorsList.ToArray(typeof(AddinError)), true))
                    dlg.Run();
            }

            errorsList = null;
            AddinManager.AddinLoadError -= OnAddinError;

            // FIXME: we should probably track the last 'selected' one
            // and do this more cleanly
            try {
                listen_socket.Bind(ep);
                listen_socket.Listen(5);
                listen_socket.BeginAccept(new AsyncCallback(ListenCallback), listen_socket);
            } catch {
                // Socket already in use
            }

            initialized = true;
            MessageService.RootWindow    = IdeApp.Workbench.RootWindow;
            Xwt.MessageDialog.RootWindow = Xwt.Toolkit.CurrentEngine.WrapWindow(IdeApp.Workbench.RootWindow);
            Thread.CurrentThread.Name    = "GUI Thread";
            Counters.Initialization.Trace("Running IdeApp");
            Counters.Initialization.EndTiming();

            AddinManager.AddExtensionNodeHandler("/MonoDevelop/Ide/InitCompleteHandlers", OnExtensionChanged);
            StartLockupTracker();

            startupTimer.Stop();

            CreateStartupMetadata(startupInfo);

            GLib.Idle.Add(OnIdle);
            IdeApp.Run();

            IdeApp.Customizer.OnIdeShutdown();

            // unloading services
            if (null != socket_filename)
            {
                File.Delete(socket_filename);
            }
            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
Example #17
0
        /// <summary>
        /// Called by the wizard to notify the page that it's now active
        /// </summary>
        public override void PageActivated()
        {
            if (!_firstInitComplete)
            {
                try
                {
                    Mouse.OverrideCursor = Cursors.Wait;

                    // testing
                    if (SystemInformation.IsAdmin())
                    {
                        // no shield if we're an admin...
                        imageShield.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        // .. otherwise get the correct shield icon for the platform
                        imageShield.Source = ClientUtils.GetShieldIconAsBitmapSource();
                    }


                    // disable 64-bit path if not on a 64 bit system
                    _is64                    = SystemInformation.Is64BitSystem();
                    label64.IsEnabled        = _is64;
                    textBox64.IsEnabled      = _is64;
                    buttonBrowse64.IsEnabled = _is64;

                    string cdb32 = ClientUtils.GetCdbPath(ImageFileMachine.I386);
                    if (cdb32 != null)
                    {
                        textBox32.Text = cdb32;
                    }

                    if (_is64)
                    {
                        string cdb64 = ClientUtils.GetCdbPath(ImageFileMachine.AMD64);
                        if (cdb64 != null)
                        {
                            textBox64.Text = cdb64;
                        }
                    }

                    // load any previous settings
                    DBConfigSettings.Settings.Load();

                    // DBConfigSettings Profile name is the context DATABASE NAME
                    if (!string.IsNullOrEmpty(DBConfigSettings.Settings.ProfileName))
                    {
                        _contextDatabaseName = DBConfigSettings.Settings.ProfileName;
                    }

                    _isDatabaseInCabFolder = DBConfigSettings.Settings.IsDatabaseInCabFolder;

                    if (!string.IsNullOrEmpty(DBConfigSettings.Settings.ConnectionString))
                    {
                        textBoxDatabase.Text = DBConfigSettings.Settings.ConnectionString;
                    }

                    _firstInitComplete = true;
                }
                finally
                {
                    Mouse.OverrideCursor = null;
                }
            }

            this.ClientLogic.ClientLogicSetupWizardPrompt += new EventHandler <ClientLogicSetupWizardPromptEventArgs>(ClientLogic_ClientLogicSetupWizardPrompt);

            UpdateState();
        }
Example #18
0
        public SMBIOS()
        {
            if (OperatingSystem.IsUnix)
            {
                this.raw   = null;
                this.table = null;

                string boardVendor  = ReadSysFS("/sys/class/dmi/id/board_vendor");
                string boardName    = ReadSysFS("/sys/class/dmi/id/board_name");
                string boardVersion = ReadSysFS("/sys/class/dmi/id/board_version");
                this.baseBoardInformation = new BaseBoardInformation(
                    boardVendor, boardName, boardVersion, null);

                string systemVendor   = ReadSysFS("/sys/class/dmi/id/sys_vendor");
                string productName    = ReadSysFS("/sys/class/dmi/id/product_name");
                string productVersion = ReadSysFS("/sys/class/dmi/id/product_version");
                this.systemInformation = new SystemInformation(systemVendor,
                                                               productName, productVersion, null, null);

                string biosVendor  = ReadSysFS("/sys/class/dmi/id/bios_vendor");
                string biosVersion = ReadSysFS("/sys/class/dmi/id/bios_version");
                this.biosInformation = new BIOSInformation(biosVendor, biosVersion);

                this.memoryDevices = new MemoryDevice[0];
            }
            else
            {
                List <Structure>    structureList    = new List <Structure>();
                List <MemoryDevice> memoryDeviceList = new List <MemoryDevice>();

                raw = null;
                byte majorVersion = 0;
                byte minorVersion = 0;
                try {
                    // Get bios raw information
                    ManagementObjectCollection collection;
                    using (ManagementObjectSearcher searcher =
                               new ManagementObjectSearcher("root\\WMI",
                                                            "SELECT * FROM MSSMBios_RawSMBiosTables")) {
                        collection = searcher.Get();
                    }

                    foreach (ManagementObject mo in collection)
                    {
                        raw          = (byte[])mo["SMBiosData"];
                        majorVersion = (byte)mo["SmbiosMajorVersion"];
                        minorVersion = (byte)mo["SmbiosMinorVersion"];
                        break;
                    }
                } catch { }

                if (majorVersion > 0 || minorVersion > 0)
                {
                    version = new Version(majorVersion, minorVersion);
                }

                if (raw != null && raw.Length > 0)
                {
                    int  offset = 0;
                    byte type   = raw[offset];
                    while (offset + 4 < raw.Length && type != 127)
                    {
                        // each iteration finds the structure inforamtion which are seperated by two zero bytes

                        // first byte in structure is the type of information
                        type = raw[offset];
                        // second byte in structure is the length of the structure header
                        int    length = raw[offset + 1];
                        ushort handle = (ushort)((raw[offset + 2] << 8) | raw[offset + 3]);

                        if (offset + length > raw.Length)
                        {
                            break;
                        }
                        // data is the structure header not the actual values
                        byte[] data = new byte[length];
                        Array.Copy(raw, offset, data, 0, length);
                        // moves offset to the start of the structure values
                        offset += length;

                        // moves over all the zeros after the structure header
                        List <string> stringsList = new List <string>();
                        if (offset < raw.Length && raw[offset] == 0)
                        {
                            offset++;
                        }

                        // Convert bytes to strings seperated by one zero byte, puts them in 'stringsList'
                        // Structure ends at two successive zero bytes
                        while (offset < raw.Length && raw[offset] != 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (offset < raw.Length && raw[offset] != 0)
                            {
                                sb.Append((char)raw[offset]); offset++;
                            }
                            offset++;
                            stringsList.Add(sb.ToString());
                        }
                        offset++;
                        switch (type)
                        {
                        case 0x00:
                            this.biosInformation = new BIOSInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.biosInformation); break;

                        case 0x01:
                            this.systemInformation = new SystemInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.systemInformation); break;

                        case 0x02: this.baseBoardInformation = new BaseBoardInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.baseBoardInformation); break;

                        case 0x04: this.processorInformation = new ProcessorInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.processorInformation); break;

                        case 0x07: //CPU Internal
                            //LCachenum = (data[5] ^ 0x80) + 1 //LCacheNum = data[16] - 3 //LCacheNum = (data[16] ^ 0x04) + 1
                            //LCacheSize = data[8] << 8 //LCacheSize = data[10] << 8
                            //LCacheAssociativity = 0
                            //switch (data[18]) {
                            //case 5: LCacheAssociativity = 4; break;
                            //case 7: LCacheAssociativity = 8; break;
                            //case 9: LCacheAssociativity = 12; break;
                            //}
                            break;

                        case 0x11: MemoryDevice m = new MemoryDevice(
                                type, handle, data, stringsList.ToArray());
                            memoryDeviceList.Add(m);
                            structureList.Add(m); break;

                        default: structureList.Add(new Structure(
                                                       type, handle, data, stringsList.ToArray())); break;
                            // type 8 = peripherals
                        }
                    }
                }

                memoryDevices = memoryDeviceList.ToArray();
                table         = structureList.ToArray();
            }
        }
        public void Test_SystemInformation()
        {
            var output = SystemInformation.Get("http://169.254.49.246", eRest.ApiResourcemanagerSystemperf);

            Assert.AreEqual("", output);
        }
Example #20
0
  public void Test()
  {
    RandomNumberGenerator[] rands = new RandomNumberGenerator[SystemInformation.GetAvailableCpuThreads()];
    for(int i=0; i<rands.Length; i++) rands[i] = RandomNumberGenerator.CreateDefault();
    foreach(int itemCount in new int[] { 100, 1000, 10000, 100000, 1000000 })
    {
      // test false positive rates from 1/2 to 1/8196 (1/64 for 100 items, and 1/1024 for 1000 items)
      for(int rate=1; rate <= (itemCount <= 100 ? 6 : itemCount <= 1000 ? 10 : 13); rate++)
      {
        float desiredRate = 1f / (1<<rate);
        BloomFilter<ulong> f = new BloomFilter<ulong>(itemCount, desiredRate);
        for(int i=0; i<itemCount; i++)
        {
          ulong n = rands[0].NextUInt64();
          f.Add(n); // we can't gainfully parallelize addition of items because the filter is not thread-safe
          Assert.IsTrue(f.PossiblyContains(n)); // make sure that there are no false negatives
        }

        // then make sure the false positive rate is acceptable
        int collisions = 0;
        Tasks.ParallelFor(0, itemCount*4, (i, end, info) =>
        {
          RandomNumberGenerator rand = rands[info.ThreadNumber];
          do
          {
            ulong n = rand.NextUInt64();
            if(f.PossiblyContains(n)) Interlocked.Increment(ref collisions);
            i++;
          } while(i < end);
        }, itemCount <= 100000 ? 1 : SystemInformation.GetAvailableCpuThreads());
        double actualRate = (double)collisions / (itemCount*4);

        // now we'll apply a statistical significance test to see if the number of failures was more than we could expect
        // by chance. first we'll calculate some parameters about the Bloom filter using the same logic as the filter
        int hashCount = (int)(Math.Log(desiredRate) * -1.4426950408890 + 0.5);
        int bitCount = (int)Math.Round((double)-hashCount * itemCount / Math.Log(1 - Math.Pow(desiredRate, 1.0 / hashCount)) + 0.5);
        bitCount = bitCount + ((bitCount&31) == 0 ? 0 : 32-bitCount&31);

        // the number of distinct bits returned from the k different hash functions is k*(1-1/bitCount)^k
        double distinctBits = hashCount * Math.Pow(1-1.0/bitCount, hashCount);
        // the chance of a bit being set after n items was added is 1-(1-1/bitCount)^(kn)
        double p = 1 - Math.Pow(1-1.0/bitCount, hashCount*itemCount);
        // the chance of a collision is the chance that all of the bits tested are set, p^distinctBits
        p = Math.Pow(p, distinctBits);
        // then, the number of expected collisions is 4n*p (since we're doing 4n checks), and the standard deviation is given by
        // the binomial distribution: sqrt(4n*p*(1-p))
        double expected = 4*itemCount * p, stddev = Math.Sqrt(expected * (1-p));

        // if we want the unit test to fail only once per five runs on average if it's functioning normally, then the overall
        // probability of success should be 0.8. since we're doing 6+10+13*3 = 55 size/rate combinations, this means the chance
        // of an individual combination succeeding should be the 55th root of 0.8, or 0.996. this corresponds to about 2.66 standard
        // deviations.
        const double allowedDeviation = 2.66;
        System.Diagnostics.Debugger.Log(0, "",
          string.Format("{0} items: desired={1:f5}, actual={2} {3:f2}x ({4:f2} / {5:f2}[{6:f2}+{7:f2}] collisions)\n",
                        itemCount, desiredRate, actualRate, actualRate/desiredRate, collisions, expected+stddev*allowedDeviation,
                        expected, stddev*allowedDeviation));
        Assert.IsTrue(collisions-expected <= Math.Round(stddev*allowedDeviation),
                      "The false positive rate of " + actualRate.ToString() + " for " + itemCount +
                      " items was unacceptable. We desired a rate of approximately " + desiredRate.ToString() + ". Note that " +
                      "it is normal for this test to fail 20% of the time.");
      }
    }
  }
Example #21
0
        public async Task <ActionResult> Index(SystemInformation model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var systemInformation = await _informationRepository.All.FirstOrDefaultAsync();

                    if (systemInformation == null)
                    {
                        systemInformation = new SystemInformation
                        {
                            SiteName       = StringHelper.KillChars(model.SiteName),
                            Slogan         = StringHelper.KillChars(model.Slogan),
                            Copyright      = StringHelper.KillChars(model.Copyright),
                            Email          = StringHelper.KillChars(model.Email),
                            CompanyName    = StringHelper.KillChars(model.CompanyName),
                            Address        = StringHelper.KillChars(model.Address),
                            HotLine        = StringHelper.KillChars(model.HotLine),
                            PhoneNumber    = StringHelper.KillChars(model.PhoneNumber),
                            WebsiteAddress = StringHelper.KillChars(model.WebsiteAddress),
                            FacebookPage   = StringHelper.KillChars(model.FacebookPage),
                            FacebookAppId  = StringHelper.KillChars(model.FacebookAppId),
                            TaxiFare       = model.TaxiFare
                        };
                        await _informationRepository.AddAsync(systemInformation);

                        await _informationRepository.SaveAsync(RequestContext);
                    }
                    else
                    {
                        systemInformation.SiteName = StringHelper.KillChars(model.SiteName);
                        systemInformation.Slogan   = StringHelper.KillChars(model.Slogan);

                        systemInformation.Copyright = StringHelper.KillChars(model.Copyright);
                        systemInformation.Email     = StringHelper.KillChars(model.Email);

                        systemInformation.CompanyName    = StringHelper.KillChars(model.CompanyName);
                        systemInformation.Address        = StringHelper.KillChars(model.Address);
                        systemInformation.HotLine        = StringHelper.KillChars(model.HotLine);
                        systemInformation.PhoneNumber    = StringHelper.KillChars(model.PhoneNumber);
                        systemInformation.WebsiteAddress = StringHelper.KillChars(model.WebsiteAddress);
                        systemInformation.FacebookPage   = StringHelper.KillChars(model.FacebookPage);
                        systemInformation.FacebookAppId  = StringHelper.KillChars(model.FacebookAppId);
                        systemInformation.TaxiFare       = model.TaxiFare;
                        _informationRepository.UpdateAsync(systemInformation);
                        await _informationRepository.SaveAsync(RequestContext);
                    }
                    ViewBag.Success = "Đã ghi nhận thành công!";

                    return(View(systemInformation));
                }
                catch (Exception ex)
                {
                    ViewBag.Error = "Đã xảy ra lỗi: " + ex.Message;
                    return(View(model));
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Vui lòng nhập chính xác thông tin!");
                ViewBag.Error = "Vui lòng nhập chính xác thông tin!";
                return(View(model));
            }
        }
 public void GetCurrentUserName()
 {
     SystemInformation.GetUserName().Should().Be(Environment.GetEnvironmentVariable("USERNAME"));
 }
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            LocalizeThisPage();

            string exception = Session["EXMessage"] as string;
            //if (Request.Params["mc"] == "500")
            //{
            //    string serverMessage = Localization.GetServerMessage("", Session["selectedCulture"] as string, "INVALID_LICENSE");
            //    LabelResponse.Text = serverMessage.ToString(); //"Invalid License"
            //    ImageButtonRegister.Visible = false;
            //}
            //if (Request.Params["mc"] == "401")
            //{
            //    string serverMessage = Localization.GetServerMessage("", Session["selectedCulture"] as string, "TRIAL_EXPIRED");
            //    LabelResponse.Text = serverMessage.ToString(); //"Trial Expired"
            //    //
            //}
            //if (Request.Params["mc"] == "501")
            //{
            //    string serverMessage = Localization.GetServerMessage("", Session["selectedCulture"] as string, "ALL_LICENCES_USE");
            //    LabelResponse.Text = serverMessage.ToString(); //"All licences are in use"
            //    ImageButtonRegister.Visible = false;
            //}
            string errorCode = Request.Params["mc"] as string;

            if (string.IsNullOrEmpty(errorCode))
            {
                errorCode = Request.Params["ErrorCode"] as string;
            }
            SystemInformation systemInformation = new SystemInformation();

            LabelServerIDText.Text = systemInformation.GetSystemID().ToUpperInvariant();
            switch (errorCode)
            {
            // Licencse Messages
            case "1000":
            case "401":
                actionMessage = "License Expired";
                suggestion    = "Please purchase license and register AccountingPlus" + " " + "If you already purchased please register here";

                ImageButtonRegister.Visible = true;
                break;

            case "1001":
                actionMessage = "System Signature doesn't match!";
                suggestion    = "Please provide valid license";

                break;

            case "3001":
                actionMessage = "Application Database doesn't match !";
                suggestion    = "Please contact Administrator";

                break;

            case "1002":
            case "502":
                actionMessage = "Licence file doesn't exist!";
                suggestion    = "Please provide valid license";

                break;

            case "1003":
            case "500":
            case "503":
                actionMessage = "Failed to process License!";
                suggestion    = "Please provide valid license";

                break;
            }
            LabelMessageID.Text        = errorCode;
            LabelResponse.Text         = actionMessage;
            LabelExceptionMessage.Text = exception;
            LabelSuggestioinText.Text  = suggestion;
            Session["EXMessage"]       = null;
        }
 public void GetSuiteMask()
 {
     SystemInformation.GetSuiteMask().Should().HaveFlag(SuiteMask.SingleUserTerminalServices);
 }
Example #25
0
        public static void DoMain(string[] args)
        {
            SystemInformation.InternalCallInitializer.Init();
            SystemInformation.SetProcessName("beagrepd");

            // Process the command-line arguments
            bool arg_debug        = false;
            bool arg_debug_memory = false;
            bool arg_fg           = false;

            int i = 0;

            while (i < args.Length)
            {
                string arg = args [i];
                ++i;
                string next_arg = i < args.Length ? args [i] : null;

                switch (arg)
                {
                case "-h":
                case "--help":
                    PrintUsage();
                    Environment.Exit(0);
                    break;

                case "--mdb":
                case "--mono-debug":
                    // Silently ignore these arguments: they get handled
                    // in the wrapper script.
                    break;

                case "--list-backends":
                    Console.WriteLine("Current available backends:");
                    Console.Write(QueryDriver.ListBackends());
                    Environment.Exit(0);
                    break;

                case "--fg":
                case "--foreground":
                    arg_fg = true;
                    break;

                case "--bg":
                case "--background":
                    arg_fg = false;
                    break;

                case "--replace":
                    arg_replace = true;
                    break;

                case "--debug":
                    arg_debug = true;
                    break;

                case "--heap-shot":
                    arg_heap_shot    = true;
                    arg_debug        = true;
                    arg_debug_memory = true;
                    break;

                case "--no-snapshots":
                case "--no-snapshot":
                    arg_heap_shot_snapshots = false;
                    break;

                case "--heap-buddy":
                case "--debug-memory":
                    arg_debug        = true;
                    arg_debug_memory = true;
                    break;

                case "--indexing-test-mode":
                    arg_indexing_test_mode = true;
                    arg_fg = true;
                    break;

                case "--backend":
                    if (next_arg == null)
                    {
                        Console.WriteLine("--backend requires a backend name");
                        Environment.Exit(1);
                        break;
                    }

                    if (next_arg.StartsWith("--"))
                    {
                        Console.WriteLine("--backend requires a backend name. Invalid name '{0}'", next_arg);
                        Environment.Exit(1);
                        break;
                    }

                    if (next_arg [0] != '+' && next_arg [0] != '-')
                    {
                        QueryDriver.OnlyAllow(next_arg);
                    }
                    else
                    {
                        if (next_arg [0] == '+')
                        {
                            QueryDriver.Allow(next_arg.Substring(1));
                        }
                        else
                        {
                            QueryDriver.Deny(next_arg.Substring(1));
                        }
                    }

                    ++i;                     // we used next_arg
                    break;

                case "--add-static-backend":
                    if (next_arg != null)
                    {
                        QueryDriver.AddStaticQueryable(next_arg);
                    }
                    ++i;
                    break;

                case "--disable-scheduler":
                    arg_disable_scheduler = true;
                    break;

                case "--indexing-delay":
                    if (next_arg != null)
                    {
                        try {
                            QueryDriver.IndexingDelay = Int32.Parse(next_arg);
                        } catch {
                            Console.WriteLine("'{0}' is not a valid number of seconds", next_arg);
                            Environment.Exit(1);
                        }
                    }

                    ++i;
                    break;

                case "--autostarted":
                    // FIXME: This option is deprecated and will be removed in a future release.
                    break;

                case "--disable-text-cache":
                    disable_textcache = true;
                    break;

                case "--version":
                    VersionFu.PrintVersion();
                    Environment.Exit(0);
                    break;

                default:
                    Console.WriteLine("Unknown argument '{0}'", arg);
                    Environment.Exit(1);
                    break;
                }
            }

            if (Environment.GetEnvironmentVariable("SABAYON_SESSION_RUNNING") == "yes")
            {
                Console.WriteLine("Beagrep is running underneath Sabayon, exiting.");
                Environment.Exit(0);
            }

            if (arg_indexing_test_mode)
            {
                LuceneQueryable.OptimizeRightAway = true;
            }

            // Bail out if we are trying to run as root
            if (Environment.UserName == "root" && Environment.GetEnvironmentVariable("SUDO_USER") != null)
            {
                Console.WriteLine("You appear to be running beagrep using sudo.  This can cause problems with");
                Console.WriteLine("permissions in your .beagrep and .wapi directories if you later try to run");
                Console.WriteLine("as an unprivileged user.  If you need to run beagrep as root, please use");
                Console.WriteLine("'su -c' instead.");
                Environment.Exit(-1);
            }

            if (Environment.UserName == "root" && !Conf.Daemon.GetOption(Conf.Names.AllowRoot, false))
            {
                Console.WriteLine("You can not run beagrep as root.  Beagrep is designed to run from your own");
                Console.WriteLine("user account.  If you want to create multiuser or system-wide indexes, use");
                Console.WriteLine("the beagrep-build-index tool.");
                Console.WriteLine();
                Console.WriteLine("You can override this setting using the beagrep-config or beagrep-settings tools.");
                Environment.Exit(-1);
            }

            try {
                string tmp = PathFinder.HomeDir;
            } catch (Exception e) {
                Console.WriteLine("Unable to start the daemon: {0}", e.Message);
                Environment.Exit(-1);
            }

            MainLoopThread = Thread.CurrentThread;

            // FIXME: We always turn on full debugging output!  We are still
            // debugging this code, after all...
            // arg_debug ? LogLevel.Debug : LogLevel.Warn

            Log.Initialize(PathFinder.LogDir, "Beagrep", LogLevel.Debug, arg_fg);
            Log.Always("Starting Beagrep Daemon (version {0})", ExternalStringsHack.Version);
            Log.Always("Running on {0}", SystemInformation.MonoRuntimeVersion);
            Log.Always("Command Line: {0}",
                       Environment.CommandLine != null ? Environment.CommandLine : "(null)");

            if (!ExtendedAttribute.Supported)
            {
                Logger.Log.Warn("Extended attributes are not supported on this filesystem. " +
                                "Performance will suffer as a result.");
            }

            if (disable_textcache)
            {
                Log.Warn("Running with text-cache disabled!");
                Log.Warn("*** Snippets will not be returned for documents indexed in this session.");
            }

            // Check if global configuration files are installed
            if (!Conf.CheckGlobalConfig())
            {
                Console.WriteLine("Global configuration files not found in '{0}'", PathFinder.ConfigDataDir);
                Environment.Exit(-1);
            }

            // Start our memory-logging thread
            if (arg_debug_memory)
            {
                ExceptionHandlingThread.Start(new ThreadStart(LogMemoryUsage));
            }

            // Do BEAGREP_EXERCISE_THE_DOG_HARDER-related processing.
            ExerciseTheDogHarder();

            // Initialize GObject type system
            g_type_init();


            // Lower our CPU priority
            SystemPriorities.Renice(7);

            QueryDriver.Init();
            Server.Init();

#if MONO_1_9
            Shutdown.SetupSignalHandlers(new Shutdown.SignalHandler(HandleSignal));
#else
            SetupSignalHandlers();
#endif

            Shutdown.ShutdownEvent += OnShutdown;

            main_loop = new MainLoop();
            Shutdown.RegisterMainLoop(main_loop);

            // Defer all actual startup until the main loop is
            // running.  That way shutdowns during the startup
            // process work correctly.
            GLib.Idle.Add(new GLib.IdleHandler(StartupProcess));

            // Start our event loop.
            main_loop.Run();

            // We're out of the main loop now, join all the
            // running threads so we can exit cleanly.
            ExceptionHandlingThread.JoinAllThreads();

            // If we placed our sockets in a temp directory, try to clean it up
            // Note: this may fail because the helper is still running
            if (PathFinder.GetRemoteStorageDir(false) != PathFinder.StorageDir)
            {
                try {
                    Directory.Delete(PathFinder.GetRemoteStorageDir(false));
                } catch (IOException) { }
            }

            Log.Always("Beagrep daemon process shut down cleanly.");
        }
 public void GetUserNameSam()
 {
     // Should be DOMAIN\user or COMPUTER\user
     SystemInformation.GetUserName(ExtendedNameFormat.SamCompatible)
     .Should().Be($"{Environment.GetEnvironmentVariable("USERDOMAIN")}\\{Environment.GetEnvironmentVariable("USERNAME")}");
 }
Example #27
0
        int Run(MonoDevelopOptions options)
        {
            LoggingService.LogInfo("Starting {0} {1}", BrandingService.ApplicationLongName, IdeVersionInfo.MonoDevelopVersion);
            LoggingService.LogInfo("Build Information{0}{1}", Environment.NewLine, SystemInformation.GetBuildInformation());
            LoggingService.LogInfo("Running on {0}", RuntimeVersionInfo.GetRuntimeInfo());

            //ensure native libs initialized before we hit anything that p/invokes
            Platform.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("PlatformInitialization");

            GettextCatalog.Initialize();
            IdeStartupTracker.StartupTracker.MarkSection("GettextInitialization");

            LoggingService.LogInfo("Operating System: {0}", SystemInformation.GetOperatingSystemDescription());

            // The assembly resolver for MSBuild 15 assemblies needs to be defined early on.
            // Whilst Runtime.Initialize loads the MSBuild 15 assemblies from Mono this seems
            // to be too late to prevent the MEF composition and the static registrar from
            // failing to load the MonoDevelop.Ide assembly which now uses MSBuild 15 assemblies.
            ResolveMSBuildAssemblies();

            Counters.InitializationTracker = Counters.Initialization.BeginTiming();

            if (options.PerfLog)
            {
                string logFile = Path.Combine(Environment.CurrentDirectory, "monodevelop.perf-log");
                LoggingService.LogInfo("Logging instrumentation service data to file: " + logFile);
                InstrumentationService.StartAutoSave(logFile, 1000);
            }

            Counters.InitializationTracker.Trace("Initializing GTK");
            if (Platform.IsWindows && !CheckWindowsGtk())
            {
                return(1);
            }
            SetupExceptionManager();

            // explicit GLib type system initialization for GLib < 2.36 before any other type system access
            GLib.GType.Init();

            var args = options.RemainingArgs.ToArray();

            IdeTheme.InitializeGtk(BrandingService.ApplicationName, ref args);

            startupInfo = new StartupInfo(options, args);
            if (startupInfo.HasFiles)
            {
                // If files are present, consider started from the commandline as being the same as file manager.
                // On macOS, we need to wait until the DidFinishLaunching notification to find out we were launched from the Finder
                IdeApp.LaunchReason = IdeApp.LaunchType.LaunchedFromFileManager;
            }
            else if (!Platform.IsMac)
            {
                IdeApp.LaunchReason = IdeApp.LaunchType.Normal;
            }

            IdeApp.Customizer = options.IdeCustomizer ?? new IdeCustomizer();
            try {
                IdeApp.Customizer.Initialize(startupInfo);
            } catch (UnauthorizedAccessException ua) {
                LoggingService.LogError("Unauthorized access: " + ua.Message);
                return(1);
            }

            try {
                GLibLogging.Enabled = true;
            } catch (Exception ex) {
                LoggingService.LogError("Error initialising GLib logging.", ex);
            }

            IdeStartupTracker.StartupTracker.MarkSection("GtkInitialization");
            LoggingService.LogInfo("Using GTK+ {0}", IdeVersionInfo.GetGtkVersion());

            // XWT initialization
            FilePath p = typeof(IdeStartup).Assembly.Location;

            Runtime.LoadAssemblyFrom(p.ParentDirectory.Combine("Xwt.Gtk.dll"));
            Xwt.Application.InitializeAsGuest(Xwt.ToolkitType.Gtk);
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarWindowBackend, GtkExtendedTitleBarWindowBackend> ();
            Xwt.Toolkit.CurrentEngine.RegisterBackend <IExtendedTitleBarDialogBackend, GtkExtendedTitleBarDialogBackend> ();
            IdeTheme.SetupXwtTheme();

            IdeStartupTracker.StartupTracker.MarkSection("XwtInitialization");

            //default to Windows IME on Windows
            if (Platform.IsWindows && GtkWorkarounds.GtkMinorVersion >= 16)
            {
                var settings = Gtk.Settings.Default;
                var val      = GtkWorkarounds.GetProperty(settings, "gtk-im-module");
                if (string.IsNullOrEmpty(val.Val as string))
                {
                    GtkWorkarounds.SetProperty(settings, "gtk-im-module", new GLib.Value("ime"));
                }
            }

            DispatchService.Initialize();

            // Set a synchronization context for the main gtk thread
            SynchronizationContext.SetSynchronizationContext(DispatchService.SynchronizationContext);
            Runtime.MainSynchronizationContext = SynchronizationContext.Current;

            IdeStartupTracker.StartupTracker.MarkSection("DispatchInitialization");

            // Initialize Roslyn's synchronization context
            RoslynServices.RoslynService.Initialize();

            IdeStartupTracker.StartupTracker.MarkSection("RoslynInitialization");

            AddinManager.AddinLoadError += OnAddinError;

            Counters.InitializationTracker.Trace("Initializing Runtime");
            Runtime.Initialize(true);

            // Register services used by the IDE

            RegisterServices();

            // If a combine was specified, force --newwindow.

            if (!options.NewWindow && startupInfo.HasFiles)
            {
                foreach (var file in startupInfo.RequestedFileList)
                {
                    if (MonoDevelop.Projects.Services.ProjectService.IsWorkspaceItemFile(file.FileName))
                    {
                        options.NewWindow = true;
                        break;
                    }
                }
            }

            instanceConnection = new IdeInstanceConnection(options.IpcTcp);

            // If not opening a combine, connect to existing monodevelop and pass filename(s) and exit
            if (!options.NewWindow && startupInfo.HasFiles && instanceConnection.TryConnect(startupInfo))
            {
                return(0);
            }

            IdeStartupTracker.StartupTracker.MarkSection("RuntimeInitialization");

            bool restartRequested = PropertyService.Get("MonoDevelop.Core.RestartRequested", false);

            startupInfo.Restarted = restartRequested;
            PropertyService.Set("MonoDevelop.Core.RestartRequested", false);

            Counters.InitializationTracker.Trace("Initializing theme");

            IdeTheme.SetupGtkTheme();

            IdeApp.Customizer.OnCoreInitialized();

            IdeStartupTracker.StartupTracker.MarkSection("ThemeInitialized");

            IdeApp.IsRunning = true;

            // Load the main menu before running the main loop
            var commandService = Runtime.GetService <CommandManager> ().Result;
            var desktopService = Runtime.GetService <DesktopService> ().Result;

            desktopService.SetGlobalMenu(commandService, DefaultWorkbench.MainMenuPath, DefaultWorkbench.AppMenuPath);

            // Run the main loop
            Gtk.Application.Invoke((s, e) => {
                MainLoop(options, startupInfo).Ignore();
            });
            Gtk.Application.Run();

            IdeApp.IsRunning = false;

            IdeApp.Customizer.OnIdeShutdown();

            instanceConnection.Dispose();

            lockupCheckRunning = false;
            Runtime.Shutdown();

            IdeApp.Customizer.OnCoreShutdown();

            InstrumentationService.Stop();

            MonoDevelop.Components.GtkWorkarounds.Terminate();

            return(0);
        }
 public void GetUserNameDisplay()
 {
     SystemInformation.GetUserName(ExtendedNameFormat.Display).Should().NotBeNullOrWhiteSpace();
 }
 static XmlDocumentationResolver()
 {
     XmlDocumentationResolver.referenceAssembliesPath = Path.Combine(SystemInformation.get_ProgramFilesX86(), "Reference Assemblies\\Microsoft\\Framework");
     XmlDocumentationResolver.frameworkPath           = SystemInformation.CLR_Default_32;
     return;
 }
 public void GetComputerName_NetBIOS()
 {
     SystemInformation.GetComputerName(ComputerNameFormat.NetBIOS)
     .Should().Be(SystemInformation.GetComputerName());
 }
Example #31
0
 public void GetSystemInformation()
 {
     _serializator.Serialize(_client, _packet.Endpoint, _packet.SyncKey, SystemInformation.ToObject());
 }
 public void ExpandEnvironmentVariables_Existing()
 {
     SystemInformation.ExpandEnvironmentVariables(@"%COMPUTERNAME%").
     Should().Be(Environment.GetEnvironmentVariable("COMPUTERNAME"));
 }
Example #33
0
        public SMBIOS()
        {
            int p = (int)Environment.OSVersion.Platform;

            if ((p == 4) || (p == 128))
            {
                this.raw   = null;
                this.table = null;

                string boardVendor  = ReadSysFS("/sys/class/dmi/id/board_vendor");
                string boardName    = ReadSysFS("/sys/class/dmi/id/board_name");
                string boardVersion = ReadSysFS("/sys/class/dmi/id/board_version");
                this.baseBoardInformation = new BaseBoardInformation(
                    boardVendor, boardName, boardVersion, null);

                string systemVendor   = ReadSysFS("/sys/class/dmi/id/sys_vendor");
                string productName    = ReadSysFS("/sys/class/dmi/id/product_name");
                string productVersion = ReadSysFS("/sys/class/dmi/id/product_version");
                this.systemInformation = new SystemInformation(systemVendor,
                                                               productName, productVersion, null, null);

                string biosVendor  = ReadSysFS("/sys/class/dmi/id/bios_vendor");
                string biosVersion = ReadSysFS("/sys/class/dmi/id/bios_version");
                this.biosInformation = new BIOSInformation(biosVendor, biosVersion);
            }
            else
            {
                List <Structure> structureList = new List <Structure>();

                raw = null;
                byte majorVersion = 0;
                byte minorVersion = 0;
                try {
                    ManagementObjectCollection collection;
                    using (ManagementObjectSearcher searcher =
                               new ManagementObjectSearcher("root\\WMI",
                                                            "SELECT * FROM MSSMBios_RawSMBiosTables")) {
                        collection = searcher.Get();
                    }

                    foreach (ManagementObject mo in collection)
                    {
                        raw          = (byte[])mo["SMBiosData"];
                        majorVersion = (byte)mo["SmbiosMajorVersion"];
                        minorVersion = (byte)mo["SmbiosMinorVersion"];
                        break;
                    }
                } catch { }

                if (majorVersion > 0 || minorVersion > 0)
                {
                    version = new Version(majorVersion, minorVersion);
                }

                if (raw != null && raw.Length > 0)
                {
                    int  offset = 0;
                    byte type   = raw[offset];
                    while (offset + 4 < raw.Length && type != 127)
                    {
                        type = raw[offset];
                        int    length = raw[offset + 1];
                        ushort handle = (ushort)((raw[offset + 2] << 8) | raw[offset + 3]);

                        if (offset + length > raw.Length)
                        {
                            break;
                        }
                        byte[] data = new byte[length];
                        Array.Copy(raw, offset, data, 0, length);
                        offset += length;

                        List <string> stringsList = new List <string>();
                        if (offset < raw.Length && raw[offset] == 0)
                        {
                            offset++;
                        }

                        while (offset < raw.Length && raw[offset] != 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (offset < raw.Length && raw[offset] != 0)
                            {
                                sb.Append((char)raw[offset]); offset++;
                            }
                            offset++;
                            stringsList.Add(sb.ToString());
                        }
                        offset++;
                        switch (type)
                        {
                        case 0x00:
                            this.biosInformation = new BIOSInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.biosInformation); break;

                        case 0x01:
                            this.systemInformation = new SystemInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.systemInformation); break;

                        case 0x02: this.baseBoardInformation = new BaseBoardInformation(
                                type, handle, data, stringsList.ToArray());
                            structureList.Add(this.baseBoardInformation); break;

                        default: structureList.Add(new Structure(
                                                       type, handle, data, stringsList.ToArray())); break;
                        }
                    }
                }

                table = structureList.ToArray();
            }
        }
 public void SystemInfoSetup()
 {
     info = Resolve<SystemInformation>();
 }