Example #1
0
        public AppDelegate()
        {
            OS.Current = new AxCrypt.Core.MacOsx.RuntimeEnvironment();

            UpdateCheck updatecheck = new UpdateCheck(UpdateCheck.VersionUnknown);
            Uri restApiUri = new Uri("https://www.axantum.com/Xecrets/RestApi.ashx/axcrypt2version/mac");
            Uri versionUri = new Uri("http://www.axantum.com/");
            string currentVersion = UpdateCheck.VersionUnknown.ToString();

            updatecheck.VersionUpdate += (sender, versionArguments) => {
                if (versionArguments.VersionUpdateStatus == VersionUpdateStatus.NewerVersionIsAvailable) {
                    int response = NSAlert.WithMessage("New version available!", "Update now", "Update later", null,
                                        "A new version of Axantum AxCrypt for Mac is available! " +
                                        "Would you like to download and install it now?")
                        .RunModal();

                    if (response == 1) {
                        Process.Start(versionArguments.UpdateWebpageUrl.AbsoluteUri);
                        NSApplication.SharedApplication.Terminate(this);
                    }
                }
            };

            updatecheck.CheckInBackground(DateTime.UtcNow, currentVersion, restApiUri, versionUri);
        }
		internal MappedDataMember(MetaType declaringType, MemberInfo mi, MemberMapping map, int ordinal)
		{
			this.declaringType = declaringType;
			this.member = mi;
			this.ordinal = ordinal;
			this.type = TypeSystem.GetMemberType(mi);
			this.isNullableType = TypeSystem.IsNullableType(this.type);
			this.memberMap = map;
			if(this.memberMap != null && this.memberMap.StorageMemberName != null)
			{
				MemberInfo[] mis = mi.DeclaringType.GetMember(this.memberMap.StorageMemberName, BindingFlags.Instance | BindingFlags.NonPublic);
				if(mis == null || mis.Length != 1)
				{
					throw Error.BadStorageProperty(this.memberMap.StorageMemberName, mi.DeclaringType, mi.Name);
				}
				this.storageMember = mis[0];
			}
			Type storageType = this.storageMember != null ? TypeSystem.GetMemberType(this.storageMember) : this.type;
			this.isDeferred = IsDeferredType(storageType);
			ColumnMapping cmap = map as ColumnMapping;
			if(cmap != null && cmap.IsDbGenerated && cmap.IsPrimaryKey)
			{
				// auto-gen identities must be synced on insert
				if((cmap.AutoSync != AutoSync.Default) && (cmap.AutoSync != AutoSync.OnInsert))
				{
					throw Error.IncorrectAutoSyncSpecification(mi.Name);
				}
			}
			if(cmap != null)
			{
				this.isPrimaryKey = cmap.IsPrimaryKey;
				this.isVersion = cmap.IsVersion;
				this.isDBGenerated = cmap.IsDbGenerated || !string.IsNullOrEmpty(cmap.Expression) || this.isVersion;
				this.isDiscriminator = cmap.IsDiscriminator;
				this.canBeNull = cmap.CanBeNull == null ? this.isNullableType || !this.type.IsValueType : (bool)cmap.CanBeNull;
				this.dbType = cmap.DbType;
				this.expression = cmap.Expression;
				this.updateCheck = cmap.UpdateCheck;
				// auto-gen keys are always and only synced on insert
				if(this.IsDbGenerated && this.IsPrimaryKey)
				{
					this.autoSync = AutoSync.OnInsert;
				}
				else if(cmap.AutoSync != AutoSync.Default)
				{
					// if the user has explicitly set it, use their value
					this.autoSync = cmap.AutoSync;
				}
				else if(this.IsDbGenerated)
				{
					// database generated members default to always
					this.autoSync = AutoSync.Always;
				}
			}
			this.mappedName = this.memberMap.DbName != null ? this.memberMap.DbName : this.member.Name;
		}
        public void EndInit()
        {
            if (DesignMode)
            {
                return;
            }

            Version myVersion = Assembly.GetExecutingAssembly().GetName().Version;
            UpdateCheck = new UpdateCheck(myVersion);
        }
        private static UpdateCheck CheckForUpdates(string feedUrl, Version currentVersion)
        {
            var r = new UpdateCheck();
            r.Message = "";
            // NOTE: Requires a reference to System.ServiceModel.dll
            var formatter = new Atom10FeedFormatter();
            try
            {
                // Read the feed
                using (var reader = System.Xml.XmlReader.Create(feedUrl))
                {
                    formatter.ReadFrom(reader);

                    var latest = (from i in formatter.Feed.Items
                                  where i.Categories.Any(c => IsStable(c.Name))
                                  orderby i.LastUpdatedTime descending
                                  select i).FirstOrDefault();

                    if (latest != null)
                    {
                        var u = latest.Links.Single().Uri.AbsoluteUri;
                        r.Message += String.Format("The latest release is: {0}\n", u);

                        var update = (from i in formatter.Feed.Items
                                      where ExtractVersion(i.Title.Text) > currentVersion &&
                                      i.Categories.Any(c => IsStable(c.Name))
                                      orderby i.LastUpdatedTime descending
                                      select i).FirstOrDefault();

                        if (update != null)
                        {
                            // TODO: Notify user of available download
                            var downloadUrl = update.Links.Single().Uri.AbsoluteUri;
                            r.Message += String.Format("There is an available update: {0}",
                                                       update.Title.Text);
                            r.UpdateAvailable = true;
                        }
                        else
                        {
                            r.Message += "There is no later version.";
                        }
                    }
                    else
                    {
                        r.Message += "Could not find a later version.";
                    }
                }
            }
            catch (System.Exception exc1)
            {
                r.Message += "Cannot check for updates. " + exc1.ToString();
            }
            return r;
        }
Example #5
0
        public static void TestArgumentNullException()
        {
            string nullVersion = null;
            Uri nullUrl = null;
            Version thisVersion = new Version(2, 0, 300, 0);
            Version newVersion = new Version(2, 0, 307, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                Assert.Throws<ArgumentNullException>(() => { updateCheck.CheckInBackground(DateTime.MinValue, nullVersion, restApiUrl, updateWebPageUrl); }, "Null argument should throw.");
                Assert.Throws<ArgumentNullException>(() => { updateCheck.CheckInBackground(DateTime.MinValue, newVersion.ToString(), nullUrl, updateWebPageUrl); }, "Null argument should throw.");
                Assert.Throws<ArgumentNullException>(() => { updateCheck.CheckInBackground(DateTime.MinValue, newVersion.ToString(), restApiUrl, nullUrl); }, "Null argument should throw.");

                updateCheck.WaitForBackgroundCheckComplete();
            }
        }
        public static void Sync(ConfigFile configFile, LogDelegate Log)
        {
            ConfigFileSyncPermissionsSection config = configFile.StudentSchoolEnrolmentPermissions;

            Log("========= STUDENT SCHOOL ENROLMENTS ========= ");
            if (!config.AllowSync)
            {
                Log("This sync module is disabled in config file - skipping");
                return;
            }

            SLStudentSchoolEnrolmentRepository       externalRepository = new SLStudentSchoolEnrolmentRepository(configFile.DatabaseConnectionString_SchoolLogic);
            InternalStudentSchoolEnrolmentRepository internalRepository = new InternalStudentSchoolEnrolmentRepository(configFile.DatabaseConnectionString_Internal);

            List <StudentSchoolEnrolment> externalObjects = externalRepository.GetAll();

            List <StudentSchoolEnrolment> previouslyUnknown = new List <StudentSchoolEnrolment>();
            List <StudentSchoolEnrolment> needingUpdate     = new List <StudentSchoolEnrolment>();
            List <StudentSchoolEnrolment> noLongerExistsInExternalSystem = new List <StudentSchoolEnrolment>();

            int     doneCount             = 0;
            int     totalExternalObjects  = externalObjects.Count();
            decimal donePercent           = 0;
            decimal doneThresholdPercent  = (decimal)0.1;
            decimal doneThresholdIncrease = (decimal)0.1;

            foreach (StudentSchoolEnrolment externalObject in externalObjects)
            {
                // Objects we don't have in the database
                StudentSchoolEnrolment internalObject = internalRepository.Get(externalObject.ID);
                if (internalObject == null)
                {
                    previouslyUnknown.Add(externalObject);
                }

                // Objects requiring update
                if (internalObject != null)
                {
                    UpdateCheck check = internalObject.CheckIfUpdatesAreRequired(externalObject);
                    if ((check == UpdateCheck.UpdatesRequired) || (config.ForceUpdate))
                    {
                        needingUpdate.Add(externalObject);
                    }
                }

                doneCount++;
                donePercent = (decimal)((decimal)doneCount / (decimal)totalExternalObjects);
                if (donePercent > doneThresholdPercent)
                {
                    doneThresholdPercent = doneThresholdPercent + doneThresholdIncrease;
                    Log((int)(donePercent * 100) + "% finished inspecting objects");
                }

                if (doneCount == totalExternalObjects)
                {
                    Log("100% finished inspecting objects");
                }
            }

            // Objects in the internal database that aren't in the external database
            if (config.AllowRemovals)
            {
                List <int> foundIDs = externalRepository.GetAllIDs();
                foreach (StudentSchoolEnrolment internalObject in internalRepository.GetAll())
                {
                    if (!foundIDs.Contains(internalObject.iStudentID))
                    {
                        noLongerExistsInExternalSystem.Add(internalObject);
                    }
                }
            }

            Log("Found " + internalRepository.GetAll().Count() + " objects in internal database");
            Log("Found " + externalObjects.Count() + " objects in external database");

            Log("Found " + previouslyUnknown.Count() + " previously unknown");
            Log("Found " + needingUpdate.Count() + " with updates");
            Log("Found " + noLongerExistsInExternalSystem.Count() + " not in external database");

            // Commit these changes to the database
            if (previouslyUnknown.Count > 0)
            {
                if (config.AllowAdds)
                {
                    Log(" > Adding " + previouslyUnknown.Count() + " new objects");
                    internalRepository.Add(previouslyUnknown);
                }
                else
                {
                    Log(" > Not allowed to add, skipping " + previouslyUnknown.Count() + " adds");
                }
            }


            if (needingUpdate.Count > 0)
            {
                if (config.AllowUpdates)
                {
                    Log(" > Updating " + needingUpdate.Count() + " objects");
                    internalRepository.Update(needingUpdate);
                }
                else
                {
                    Log(" > Not allowed to do updates, skipping " + needingUpdate.Count() + " updates");
                }
            }

            if (noLongerExistsInExternalSystem.Count > 0)
            {
                if (config.AllowRemovals)
                {
                    Log(" > If removals were implemented, we would remove " + noLongerExistsInExternalSystem.Count() + " objects here");
                }
                else
                {
                    Log(" > Not allowed to remove, skipping " + noLongerExistsInExternalSystem.Count() + " removals");
                }
            }
        }
        public MainWindow()
        {
            log4net.Config.XmlConfigurator.Configure();
            _log.Info("Starting SPIPware");

            AppDomain.CurrentDomain.UnhandledException += UnhandledException;
            InitializeComponent();


            UpdatePlateCheckboxes(true);
            //LoadDefaults();
            //UpdatePlateCheckboxes();
            //cycle.UpdatePositionList(checkBoxes);


            peripheral.PeripheralUpdate += UpdatePeripheralStatus;
            cycle.StatusUpdate          += UpdateCycleStatus;
            timelapse.TimeLapseStatus   += UpdateTimeLapseStatus;
            cycle.ImageUpdatedEvent     += UpdatePictureBox;
            timelapse.ExperimentStatus  += ExperimentUpdated;

            updateSerialPortComboBox(PeripheralSerialPortSelect);
            updateSerialPortComboBox(SerialPortSelect);
            updateCameraSettingsOptions();
            //UpdateClrCanvas();
            Properties.Settings.Default.tlStartDate = DateTime.Now;

            Task task = new Task(() => camera.StartVimba());

            task.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
            task.Start();
            //camera.StartVimba();
            Task task2 = new Task(() => UpdateCheck.CheckForUpdate());

            task2.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
            task2.Start();

            machine.ConnectionStateChanged += Machine_ConnectionStateChanged;

            machine.NonFatalException += Machine_NonFatalException;
            machine.Info           += Machine_Info;
            machine.LineReceived   += Machine_LineReceived;
            machine.LineReceived   += settingsWindow.LineReceived;
            machine.StatusReceived += Machine_StatusReceived;
            machine.LineSent       += Machine_LineSent;

            machine.PositionUpdateReceived += Machine_PositionUpdateReceived;
            machine.StatusChanged          += Machine_StatusChanged;
            machine.DistanceModeChanged    += Machine_DistanceModeChanged;
            machine.UnitChanged            += Machine_UnitChanged;
            machine.PlaneChanged           += Machine_PlaneChanged;
            machine.BufferStateChanged     += Machine_BufferStateChanged;
            machine.OperatingModeChanged   += Machine_OperatingMode_Changed;
            //machine.FileChanged += Machine_FileChanged;
            //machine.FilePositionChanged += Machine_FilePositionChanged;
            //machine.ProbeFinished += Machine_ProbeFinished;
            machine.OverrideChanged += Machine_OverrideChanged;
            machine.PinStateChanged += Machine_PinStateChanged;

            Machine_OperatingMode_Changed();
            Machine_PositionUpdateReceived();

            Properties.Settings.Default.SettingChanging += Default_SettingChanging;
            FileRuntimeTimer.Tick += FileRuntimeTimer_Tick;

            machine.ProbeFinished += Machine_ProbeFinished_UserOutput;

            settingsWindow.SendLine += machine.SendLine;

            CheckBoxUseExpressions_Changed(null, null);
            //updatePlateCheckboxes();

            //cameraControl.m_CameraList = m_CameraList;
            camera.m_PictureBox = m_PictureBox;
        }
Example #8
0
        public static void Main(string[] args)
        {
            bool mutexReserved;

            using (Mutex appMutex = new Mutex(true, "SpeditGlobalMutex", out mutexReserved))
            {
                if (mutexReserved)
                {
                    bool ProgramIsNew = false;
#if !DEBUG
                    try
                    {
#endif
                    Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
#if !DEBUG
                    ProfileOptimization.SetProfileRoot(Environment.CurrentDirectory);
                    ProfileOptimization.StartProfile("Startup.Profile");
#endif
                    //todo implement own updater
                    Options = OptionsControl.Load(out ProgramIsNew);

                    Assembly assembly = Assembly.GetExecutingAssembly();
                    NeutralResourcesLanguageAttribute a = (NeutralResourcesLanguageAttribute)assembly.GetCustomAttribute(typeof(NeutralResourcesLanguageAttribute));
                    Culture.cultures = Culture.GetAvailableCultures();
                    CultureInfo defCultureInfo = new CultureInfo(string.IsNullOrEmpty(Options.Language) ? a.CultureName : Options.Language);
                    CultureInfo.DefaultThreadCurrentUICulture = defCultureInfo;
                    CultureInfo.DefaultThreadCurrentCulture   = defCultureInfo;

                    ConfigList = ConfigLoader.Load();
                    foreach (Config config in ConfigList.Configs.Where(config => config.Name == Options.SelectedConfig))
                    {
                        ConfigList.CurrentConfig = ConfigList.Configs.IndexOf(config);
                        break;
                    }
                    if (!Options.UseHardwareAcceleration)
                    {
                        RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
                    }
#if !DEBUG
                    if (ProgramIsNew)
                    {
                        if (Translations.AvailableLanguageIDs.Length > 0)
                        {
                            splashScreen.Close(new TimeSpan(0, 0, 1));
                            var languageWindow = new UI.Interop.LanguageChooserWindow(Translations.AvailableLanguageIDs, Translations.AvailableLanguages);
                            languageWindow.ShowDialog();
                            string potentialSelectedLanguageID = languageWindow.SelectedID;
                            if (!string.IsNullOrWhiteSpace(potentialSelectedLanguageID))
                            {
                                OptionsObject.Language = potentialSelectedLanguageID;
                                Translations.LoadLanguage(potentialSelectedLanguageID);
                            }
                            splashScreen.Show(false, true);
                        }
                    }
#endif
                    MainWindow = new MainWindow();
                    new PipeInteropServer(MainWindow).Start();
#if !DEBUG
                }
                catch (Exception e)
                {
                    File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT LOADING"));
                    MessageBox.Show("An error occured while loading." + Environment.NewLine + "A crash report was written in the editor-directory.",
                                    "Error while Loading",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Environment.Exit(Environment.ExitCode);
                }
#endif
                    Application app = new Application();
#if !DEBUG
                    try
                    {
                        if (OptionsObject.Program_CheckForUpdates)
                        {
                            UpdateCheck.Check(true);
                        }
#endif
                    app.Run(MainWindow);
                    OptionsControl.Save();
#if !DEBUG
                }
                catch (Exception e)
                {
                    File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT MAIN"));
                    MessageBox.Show("An error occured." + Environment.NewLine + "A crash report was written in the editor-directory.",
                                    "Error",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Environment.Exit(Environment.ExitCode);
                }
#endif
                }
                else
                {
                    try
                    {
                        StringBuilder sBuilder   = new StringBuilder();
                        bool          addedFiles = false;
                        for (int i = 0; i < args.Length; ++i)
                        {
                            if (!string.IsNullOrWhiteSpace(args[i]))
                            {
                                FileInfo fInfo = new FileInfo(args[i]);
                                if (fInfo.Exists)
                                {
                                    string ext = fInfo.Extension.ToLowerInvariant().Trim('.', ' ');
                                    //todo fix this?
                                    if (ext == "sp" || ext == "inc" || ext == "txt" || ext == "smx")
                                    {
                                        addedFiles = true;
                                        sBuilder.Append(fInfo.FullName);
                                        if ((i + 1) != args.Length)
                                        {
                                            sBuilder.Append("|");
                                        }
                                    }
                                }
                            }
                        }
                        if (addedFiles)
                        {
                            PipeInteropClient.ConnectToMasterPipeAndSendData(sBuilder.ToString());
                        }
                    }
                    catch (Exception) { } //dont f**k the user up with irrelevant data
                }
            }
        }
Example #9
0
 public ColumnAttribute()
 {
     check = UpdateCheck.Always;
 }
Example #10
0
        public static void Sync(ConfigFile configFile, LogDelegate Log)
        {
            ConfigFileSyncPermissionsSection config = configFile.AbsencePermissions;

            Log("========= ABSENCES ========= ");
            if (!config.AllowSync)
            {
                Log("This sync module is disabled in config file - skipping");
                return;
            }

            // Parse the school year from the config file, we'll need it later
            InternalSchoolYearRepository _schoolYearRepo = new InternalSchoolYearRepository(configFile.DatabaseConnectionString_Internal);
            SchoolYear schoolYear = _schoolYearRepo.Get(configFile.SchoolYearName);

            if (schoolYear == null)
            {
                throw new InvalidSchoolYearException("School year from config file is invalid");
            }
            SLAbsenceRepository       externalRepository = new SLAbsenceRepository(configFile.DatabaseConnectionString_SchoolLogic, schoolYear);
            InternalAbsenceRepository internalRepository = new InternalAbsenceRepository(configFile.DatabaseConnectionString_Internal);

            List <Absence> externalObjects = externalRepository.GetAll();
            List <Absence> internalObjects = internalRepository.GetForSchoolYear(schoolYear.ID);

            Log("Found " + internalObjects.Count() + " absences in internal database for this school year");
            Log("Found " + externalObjects.Count() + " absences in external database");

            // Find previously unknown schools
            // Find schools that need an update
            List <Absence> previouslyUnknown = new List <Absence>();
            List <Absence> needingUpdate     = new List <Absence>();
            List <Absence> noLongerExistsInExternalSystem = new List <Absence>();

            int     doneCount             = 0;
            int     totalExternalObjects  = externalObjects.Count();
            decimal donePercent           = 0;
            decimal doneThresholdPercent  = (decimal)0.01;
            decimal doneThresholdIncrease = (decimal)0.01;

            foreach (Absence externalObject in externalObjects)
            {
                // Check to see if we know about this school already
                Absence internalObject = internalObjects.GetWithID(externalObject.ID);
                if (internalObject == null)
                {
                    previouslyUnknown.Add(externalObject);
                }

                // Check to see if this school requires an update
                if (internalObject != null)
                {
                    UpdateCheck check = internalObject.CheckIfUpdatesAreRequired(externalObject);
                    if ((check == UpdateCheck.UpdatesRequired) || (config.ForceUpdate))
                    {
                        needingUpdate.Add(externalObject);
                    }
                }

                doneCount++;
                donePercent = (decimal)((decimal)doneCount / (decimal)totalExternalObjects);
                if (donePercent > doneThresholdPercent)
                {
                    doneThresholdPercent = doneThresholdPercent + doneThresholdIncrease;
                    Log((int)(donePercent * 100) + "% finished inspecting objects");
                }

                if (doneCount == totalExternalObjects)
                {
                    Log("100% finished inspecting objects");
                }
            }

            // Find schools that are no longer in the database that could potentially be cleaned up
            if (config.AllowRemovals)
            {
                List <int> foundIDs = externalRepository.GetAllIDs();
                foreach (Absence internalObject in internalObjects)
                {
                    if (!foundIDs.Contains(internalObject.ID))
                    {
                        noLongerExistsInExternalSystem.Add(internalObject);
                    }
                }
            }

            Log("Found " + previouslyUnknown.Count() + " previously unknown");
            Log("Found " + needingUpdate.Count() + " with updates");
            Log("Found " + noLongerExistsInExternalSystem.Count() + " not in external database");

            // Commit these changes to the database

            if (previouslyUnknown.Count > 0)
            {
                if (config.AllowAdds)
                {
                    Log(" > Adding " + previouslyUnknown.Count() + " new objects");
                    internalRepository.Add(previouslyUnknown);
                }
                else
                {
                    Log(" > Not allowed to add, skipping " + previouslyUnknown.Count() + " adds");
                }
            }


            if (needingUpdate.Count > 0)
            {
                if (config.AllowUpdates)
                {
                    Log(" > Updating " + needingUpdate.Count() + " objects");
                    internalRepository.Update(needingUpdate);
                }
                else
                {
                    Log(" > Not allowed to do updates, skipping " + needingUpdate.Count() + " updates");
                }
            }

            if (noLongerExistsInExternalSystem.Count > 0)
            {
                if (config.AllowRemovals)
                {
                    Log(" > If removals were implemented, we would remove " + noLongerExistsInExternalSystem.Count() + " objects here");
                }
                else
                {
                    Log(" > Not allowed to remove, skipping " + noLongerExistsInExternalSystem.Count() + " removals");
                }
            }
        }
 protected override void Dispose(bool disposing)
 {
     if (_disposed)
     {
         return;
     }
     if (disposing)
     {
         if (UpdateCheck != null)
         {
             UpdateCheck.Dispose();
             UpdateCheck = null;
         }
     }
     _disposed = true;
     base.Dispose(disposing);
 }
Example #12
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if ((bool)SettingsInstance["ShowPlaylistEditorOnStartup"].Value)
            {
                InstanceManager.Instance.PlaylistEditorInstance.Show();
            }

            // Set the initial scrolling animation
            SetTextScrollingAnimation(MainLabel.Text);

            // Init PluginWidget
            PlWidget = new PluginsWidget(this, PluginsButton, Widget.WidgetRelativePosition.Above,
                                         Widget.WidgetAlignment.Center, false, true);

            // Load plugin GUIs:
            foreach (var p in InstanceManager.Instance.LoadedExtensions)
            {
                p.Instance.InitGui();
            }

            // Debug
            //MessageBox.Show("Actual size: " + playButtonImage.ActualHeight + "*" + playButtonImage.ActualWidth);

            // Open the file specified in CLArgs. If failed, open the autoload playlist if enabled
            if (!FileSystemUtils.LoadFileFromClArgs() && (bool)SettingsInstance["LoadPlaylistOnStartup"].Value)
            {
                var f = (string)SettingsInstance["PlaylistToAutoLoad"].Value;
                if (File.Exists(f))
                {
                    PlaybackManagerInstance.Playlist.AddRange(f, FileSystemUtils.DefaultLoadErrorCallback);
                }
                else
                {
                    MessageBox.Show("File not found: " + f,
                                    "Non-critical error, everything is ok!", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }
            }

            try
            {
                // Update Checking
                if (!(bool)SettingsInstance["CheckForUpdates"].Value)
                {
                    return;
                }
                var upd = await UpdateCheck.CheckForUpdate();

                if (upd == "")
                {
                    return;
                }
                var result = MessageBox.Show("A new version of Sky Jukebox is available! Download the update now?",
                                             "Update Checker", MessageBoxButton.YesNo, MessageBoxImage.Information);
                if (result == MessageBoxResult.Yes)
                {
                    Process.Start("https://github.com/OronDF343/Sky-Jukebox/releases");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Example #13
0
        public static void TestExceptionDuringVersionCallButRecentlyChecked()
        {
            FakeWebCaller webCaller = new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""2.0.400.0"",""R"":300,""S"":0,""M"":""OK""}");
            webCaller.Calling += (object sender, EventArgs e) => { throw new InvalidOperationException("Oops - a forced exception during the call."); };
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                return webCaller;
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(utcNow.AddDays(-2), UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.ShortTimeSinceLastSuccessfulCheck), "Although the check failed, a check was recently made a short time ago.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(updateWebPageUrl), "The original URL should be passed since the call failed.");
            Assert.That(eventArgs.Version, Is.EqualTo(UpdateCheck.VersionUnknown), "An unknown version should be returned, since the call failed.");
        }
Example #14
0
        public static void TestInvalidVersionReturned()
        {
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                return new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""x.y.z.z"",""R"":207,""S"":0,""M"":""OK""}");
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called even when an invalid version is returned.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.LongTimeSinceLastSuccessfulCheck), "No check has been performed previously and no new version is known.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(new Uri("http://localhost/AxCrypt/Downloads.html")), "The right URL should be passed in the event args.");
            Assert.That(eventArgs.Version, Is.EqualTo(UpdateCheck.VersionUnknown), "The version is not known since it could not be parsed.");
        }
Example #15
0
 private void runUpdateInstTestButton_Click(object sender, EventArgs e)
 {
     UpdateCheck.runUpdateInstance();
 }
Example #16
0
 public ColumnAttribute() {
     check = UpdateCheck.Always;
 }
Example #17
0
 private void updateTestButton_Click(object sender, EventArgs e)
 {
     UpdateCheck.CreateUpdateWindow();
 }
Example #18
0
 private void UpdateThread()
 {
     UpdateCheck.CheckForUpdate();
 }
Example #19
0
        private static void HandleFeedReadWorkerStart(object sender, DoWorkEventArgs e)
        {
            // Create a new database instance for just this thread
            var database = new FeedCenterEntities();

            // Get the worker
            var worker = (BackgroundWorker)sender;

            // Get the input information
            var workerInput = (FeedReadWorkerInput)e.Argument;

            // Setup for progress
            var currentProgress = 0;

            // Create the list of feeds to read
            var feedsToRead = new List <Feed>();

            // If we have a single feed then add it to the list - otherwise add them all
            if (workerInput.Feed != null)
            {
                feedsToRead.Add(database.Feeds.First(feed => feed.ID == workerInput.Feed.ID));
            }
            else
            {
                feedsToRead.AddRange(database.Feeds);
            }

            // Loop over each feed and read it
            foreach (var feed in feedsToRead)
            {
                // Read the feed
                feed.Read(database, workerInput.ForceRead);

                // Increment progress
                currentProgress += 1;

                // Report progress
                worker.ReportProgress(currentProgress);
            }

            // Save the changes
            database.SaveChanges();

            // Increment progress
            currentProgress += 1;

            // Report progress
            worker.ReportProgress(currentProgress);

            // See if we're due for a version check
            if (DateTime.Now - Settings.Default.LastVersionCheck >= Settings.Default.VersionCheckInterval)
            {
                // Get the update information
                UpdateCheck.CheckForUpdate();

                // Update the last check time
                Settings.Default.LastVersionCheck = DateTime.Now;
            }

            // Increment progress
            currentProgress += 1;

            // Report progress
            worker.ReportProgress(currentProgress);

            // Sleep for a little bit so the user can see the update
            Thread.Sleep(Settings.Default.ProgressSleepInterval * 3);
        }
Example #20
0
        public static void Main(string[] args)
        {
            bool InSafe = false;
            bool mutexReserved;

            using (Mutex appMutex = new Mutex(true, "SpeditGlobalMutex", out mutexReserved))
            {
                if (mutexReserved)
                {
#if !DEBUG
                    try
                    {
#endif
                    SplashScreen splashScreen = new SplashScreen("Resources/Icon256x.png");
                    splashScreen.Show(false, true);
                    UpdateStatus = new UpdateInfo();
                    Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    OptionsObject = OptionsControlIOObject.Load();
                    for (int i = 0; i < args.Length; ++i)
                    {
                        if (args[i].ToLowerInvariant() == "-rcck")     //ReCreateCryptoKey
                        {
                            var opt = OptionsObject;
                            OptionsObject.ReCreateCryptoKey();
                            MessageBox.Show("All FTP passwords are now encrypted wrong!" + Environment.NewLine + "You have to replace them!",
                                            "Created new crypto key", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else if (args[i].ToLowerInvariant() == "-safe")
                        {
                            InSafe = true;
                        }
                    }
                    Configs = ConfigLoader.Load();
                    for (int i = 0; i < Configs.Length; ++i)
                    {
                        if (Configs[i].Name == OptionsObject.Program_SelectedConfig)
                        {
                            Program.SelectedConfig = i;
                            break;
                        }
                    }
                    if (!OptionsObject.Program_UseHardwareAcceleration)
                    {
                        RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
                    }
                    MainWindow = new MainWindow(splashScreen);
                    PipeInteropServer pipeServer = new PipeInteropServer(MainWindow);
                    pipeServer.Start();
#if !DEBUG
                }
                catch (Exception e)
                {
                    File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT LOADING"));
                    MessageBox.Show("An error occured while loading." + Environment.NewLine + "A crash report was written in the editor-directory.",
                                    "Error while Loading",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Environment.Exit(Environment.ExitCode);
                }
#endif
                    Application app = new Application();
                    if (InSafe)
                    {
                        try
                        {
#if !DEBUG
                            if (OptionsObject.Program_CheckForUpdates)
                            {
                                UpdateCheck.Check(true);
                            }
#endif
                            app.Run(MainWindow);
                            OptionsControlIOObject.Save();
                        }
                        catch (Exception e)
                        {
                            File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT MAIN"));
                            MessageBox.Show("An error occured." + Environment.NewLine + "A crash report was written in the editor-directory.",
                                            "Error",
                                            MessageBoxButton.OK,
                                            MessageBoxImage.Error);
                            Environment.Exit(Environment.ExitCode);
                        }
                    }
                    else
                    {
#if !DEBUG
                        if (OptionsObject.Program_CheckForUpdates)
                        {
                            UpdateCheck.Check(true);
                        }
#endif
                        app.Run(MainWindow);
                        OptionsControlIOObject.Save();
                    }
                }
                else
                {
                    try
                    {
                        StringBuilder sBuilder   = new StringBuilder();
                        bool          addedFiles = false;
                        for (int i = 0; i < args.Length; ++i)
                        {
                            if (!string.IsNullOrWhiteSpace(args[i]))
                            {
                                FileInfo fInfo = new FileInfo(args[i]);
                                if (fInfo.Exists)
                                {
                                    string ext = fInfo.Extension.ToLowerInvariant().Trim(new char[] { '.', ' ' });
                                    if (ext == "sp" || ext == "inc" || ext == "txt" || ext == "smx")
                                    {
                                        addedFiles = true;
                                        sBuilder.Append(fInfo.FullName);
                                        if ((i + 1) != args.Length)
                                        {
                                            sBuilder.Append("|");
                                        }
                                    }
                                }
                            }
                        }
                        if (addedFiles)
                        {
                            PipeInteropClient.ConnectToMasterPipeAndSendData(sBuilder.ToString());
                        }
                    }
                    catch (Exception) { } //dont f**k the user up with irrelevant data
                }
            }
        }
Example #21
0
        public static void TestOnlyOneCallMadeWhenCheckIsMadeWithCheckPending()
        {
            int calls = 0;
            ManualResetEvent wait = new ManualResetEvent(false);
            FakeWebCaller webCaller = new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""2.0.400.0"",""R"":300,""S"":0,""M"":""OK""}");
            webCaller.Calling += (object sender, EventArgs e) => { wait.WaitOne(); ++calls; };
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                return webCaller;
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Version newVersion = new Version(2, 0, 400, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                wait.Set();
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.NewerVersionIsAvailable), "One check should be made, indicating a newer version is available.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(new Uri("http://localhost/AxCrypt/Downloads.html")), "The new URL should be passed since a call is made.");
            Assert.That(calls, Is.EqualTo(1), "The web caller should only be called once.");
            Assert.That(eventArgs.Version, Is.EqualTo(newVersion), "The new version should be passed back, since one call should be made.");
        }
Example #22
0
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                // 업데이트 완료
                if (args[0] == "--updated")
                {
                    // 업데이트 폴더 삭제
                    UpdateCheck.CleanFolder();
                    MessageBox.Show("업데이트 되었습니다", "알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                // 업데이트를 하기 위해 UAC 권한으로 넘어온 케이스
                else if (args[0] == "--update")
                {
                    UpdateCheck.ForceRun = true;
                    UpdateCheck.CreateUpdateWindow();
                }

                // 파일 처리를 하기 위해 업데이트된 파일로 임시 실행
                else if (args[0] == "--updating")
                {
                    Updater.UpdateProcess(args);
                    return;
                }
            }
            else
            {
                // 업데이트 확인
                UpdateCheck.CheckUpdateAvaliable((UpdateCheck.UpdateState updateState) =>
                {
                    switch (updateState)
                    {
                    case UpdateCheck.UpdateState.UPDATE_AVALIABLE:
                        UpdateCheck.CreateUpdateWindow();
                        break;
                    }
                });
            }

            bool created = false;

            mutex = new Mutex(true, "AnemoneTrizMutex", out created);
            if (created)
            {
                // 임시 폴더 이름을 위한 Guid 생성 및 가공
                Guid   g          = Guid.NewGuid();
                string GuidString = Convert.ToBase64String(g.ToByteArray());
                GuidString = GuidString.Replace("=", "");
                GuidString = GuidString.Replace("+", "");
                var tempFolder = $"{Path.GetTempPath()}{GuidString}\\";

                // 임시 폴더 생성
                try
                {
                    Directory.CreateDirectory(tempFolder);
                }
                catch
                {
                    MessageBox.Show("임시 폴더를 만들 수 없습니다", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                // 리소스에서 libSkiaSharp.dll 추출
                File.WriteAllBytes($"{tempFolder}libSkiaSharp.dll", Properties.Resources.libSkiaSharp);

                // libSkiaSharp를 LoadLibrary
                IntPtr dllHandle = LoadLibrary($"{tempFolder}libSkiaSharp.dll");

                // 이지트랜스 초기화
                Translator.ezTransXP.Initialize();

                // DPI 세팅
                SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT.PerMonitorAwareV2);

                // 폼 시작
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainForm());

                // 뮤텍스 닫기
                mutex.Close();

                // SkiaSharp.dll이 libSkiaSharp.dll을 Load했을 경우 Reference Count가 올라가므로
                // Ref.Count가 0이 될때까지 FreeLibrary 시도
                while (true)
                {
                    FreeLibrary(dllHandle);
                    if (GetModuleHandle($"{tempFolder}libSkiaSharp.dll") == IntPtr.Zero)
                    {
                        break;
                    }
                }

                // 임시 폴더를 삭제합니다. 예외가 발생할 수 있으므로 try-catch로 묶어둡니다
                try
                {
                    File.Delete($"{tempFolder}libSkiaSharp.dll");

                    System.IO.DirectoryInfo di = new DirectoryInfo(tempFolder);
                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }
                    foreach (DirectoryInfo dir in di.GetDirectories())
                    {
                        dir.Delete(true);
                    }
                    Directory.Delete(tempFolder);
                }
                catch { }

                // 프로세스를 강제로 죽인다
                // 강제로 죽이는 이유는, FreeLibrary를 하면서 Skia쪽의 포인터가 날아갔기 때문에
                // Main 함수가 끝나고 AccessViolation 예외가 발생하기 때문이다.
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                // 아네모네 인스턴스가 이미 있는 경우 존재하는 인스턴스 윈도우를 활성화합니다
                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                FileVersionInfo            fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);
                IntPtr handle = FindWindow(null, $"{Properties.Resources.ResourceManager.GetString("AnemoneTitleName")} v{fvi.FileVersion}");
                ShowWindow(handle, 5);
                BringWindowToTop(handle);
                SetForegroundWindow(handle);
            }
        }
Example #23
0
        public static void TestVersionAlreadyCheckedRecently()
        {
            bool wasCalled = false;
            FakeWebCaller webCaller = new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""2.0.400.0"",""R"":300,""S"":0,""M"":""OK""}");
            webCaller.Calling += (object sender, EventArgs e) => { wasCalled = true; };
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                return webCaller;
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(utcNow.AddHours(-1), thisVersion.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.IsUpToDateOrRecentlyChecked), "No check should be made, and it is assumed this version is up to date.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(updateWebPageUrl), "The original URL should be passed in the event args since no call is made.");
            Assert.That(wasCalled, Is.False, "The web caller should never be called.");
            Assert.That(eventArgs.Version, Is.EqualTo(thisVersion), "The new version should not be passed back, since no call should be made.");
        }
Example #24
0
 private void HandleCheckVersionNowButtonClick(object sender, System.Windows.RoutedEventArgs e)
 {
     UpdateCheck.DisplayUpdateInformation(true);
 }
Example #25
0
        public static void TestVersionSameAndCheckedRecently()
        {
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                return new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""2.0.300.0"",""R"":300,""S"":0,""M"":""OK""}");
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Version newVersion = new Version(2, 0, 300, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(utcNow.AddDays(-2), UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.IsUpToDateOrRecentlyChecked), "The new version was the same and we checked recently.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(new Uri("http://localhost/AxCrypt/Downloads.html")), "The right URL should be passed in the event args.");
            Assert.That(eventArgs.Version, Is.EqualTo(newVersion), "The new version should be passed back.");
        }
Example #26
0
        protected void showAbout()
        {
            if (!FileBrowser.isPlatformSupported)
            {
                EditorGUILayout.HelpBox("The current platform is not supported in builds!", MessageType.Error);
            }

            GUILayout.Space(3);
            GUILayout.Label(Util.Constants.ASSET_NAME, EditorStyles.boldLabel);

            GUILayout.BeginHorizontal();
            {
                GUILayout.BeginVertical(GUILayout.Width(60));
                {
                    GUILayout.Label("Version:");

                    GUILayout.Space(12);

                    GUILayout.Label("Web:");

                    GUILayout.Space(2);

                    GUILayout.Label("Email:");
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.Width(170));
                {
                    GUILayout.Space(0);

                    GUILayout.Label(Util.Constants.ASSET_VERSION);

                    GUILayout.Space(12);

                    EditorGUILayout.SelectableLabel(Util.Constants.ASSET_AUTHOR_URL, GUILayout.Height(16), GUILayout.ExpandHeight(false));

                    GUILayout.Space(2);

                    EditorGUILayout.SelectableLabel(Util.Constants.ASSET_CONTACT, GUILayout.Height(16), GUILayout.ExpandHeight(false));
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.ExpandWidth(true));
                {
                    //GUILayout.Space(0);
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.Width(64));
                {
                    if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Logo_Asset, "Visit asset website")))
                    {
                        Application.OpenURL(EditorConstants.ASSET_URL);
                    }
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            GUILayout.Label("© 2017-2019 by " + Util.Constants.ASSET_AUTHOR);

            EditorHelper.SeparatorUI();

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button(new GUIContent(" AssetStore", EditorHelper.Logo_Unity, "Visit the 'Unity AssetStore' website.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_CT_URL);
                }

                if (GUILayout.Button(new GUIContent(" " + Util.Constants.ASSET_AUTHOR, EditorHelper.Logo_CT, "Visit the '" + Util.Constants.ASSET_AUTHOR + "' website.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_AUTHOR_URL);
                }
            }
            GUILayout.EndHorizontal();

            EditorHelper.SeparatorUI();

            aboutTab = GUILayout.Toolbar(aboutTab, new[] { "Readme", "Versions", "Update" });

            switch (aboutTab)
            {
            case 2:
            {
                scrollPosAboutUpdate = EditorGUILayout.BeginScrollView(scrollPosAboutUpdate, false, false);
                {
                    Color fgColor = GUI.color;

                    GUI.color = Color.yellow;

                    switch (updateStatus)
                    {
                    case UpdateStatus.NO_UPDATE:
                        GUI.color = Color.green;
                        GUILayout.Label(updateText);
                        break;

                    case UpdateStatus.UPDATE:
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" Download", "Visit the 'Unity AssetStore' to download the latest version.")))
                        {
                            //Application.OpenURL(Constants.ASSET_URL);
                            UnityEditorInternal.AssetStore.Open("content/" + EditorConstants.ASSET_ID);
                        }

                        break;
                    }

                    case UpdateStatus.UPDATE_PRO:
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" Upgrade", "Upgrade to the PRO-version in the 'Unity AssetStore'.")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_PRO_URL);
                        }

                        break;
                    }

                    case UpdateStatus.UPDATE_VERSION:
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" Upgrade", "Upgrade to the newer version in the 'Unity AssetStore'")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_CT_URL);
                        }

                        break;
                    }

                    case UpdateStatus.DEPRECATED:
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" More Information", "Visit the 'crosstales'-site for more information.")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_AUTHOR_URL);
                        }

                        break;
                    }

                    default:
                        GUI.color = Color.cyan;
                        GUILayout.Label(updateText);
                        break;
                    }

                    GUI.color = fgColor;
                }
                EditorGUILayout.EndScrollView();

                if (updateStatus == UpdateStatus.NOT_CHECKED || updateStatus == UpdateStatus.NO_UPDATE)
                {
                    bool isChecking = !(worker == null || worker != null && !worker.IsAlive);

                    GUI.enabled = Util.Helper.isInternetAvailable && !isChecking;

                    if (GUILayout.Button(new GUIContent(isChecking ? "Checking... Please wait." : " Check For Update", EditorHelper.Icon_Check, "Checks for available updates of " + Util.Constants.ASSET_NAME)))
                    {
                        worker = new System.Threading.Thread(() => UpdateCheck.UpdateCheckForEditor(out updateText, out updateStatus));
                        worker.Start();
                    }

                    GUI.enabled = true;
                }

                break;
            }

            case 0:
            {
                if (readme == null)
                {
                    string path = Application.dataPath + EditorConfig.ASSET_PATH + "README.txt";

                    try
                    {
                        readme = System.IO.File.ReadAllText(path);
                    }
                    catch (System.Exception)
                    {
                        readme = "README not found: " + path;
                    }
                }

                scrollPosAboutReadme = EditorGUILayout.BeginScrollView(scrollPosAboutReadme, false, false);
                {
                    GUILayout.Label(readme);
                }
                EditorGUILayout.EndScrollView();
                break;
            }

            default:
            {
                if (versions == null)
                {
                    string path = Application.dataPath + EditorConfig.ASSET_PATH + "Documentation/VERSIONS.txt";

                    try
                    {
                        versions = System.IO.File.ReadAllText(path);
                    }
                    catch (System.Exception)
                    {
                        versions = "VERSIONS not found: " + path;
                    }
                }

                scrollPosAboutVersions = EditorGUILayout.BeginScrollView(scrollPosAboutVersions, false, false);
                {
                    GUILayout.Label(versions);
                }

                EditorGUILayout.EndScrollView();
                break;
            }
            }

            EditorHelper.SeparatorUI();

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Discord, "Communicate with us via 'Discord'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_DISCORD);
                }

                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Facebook, "Follow us on 'Facebook'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_FACEBOOK);
                }

                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Twitter, "Follow us on 'Twitter'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_TWITTER);
                }

                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Linkedin, "Follow us on 'LinkedIn'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_LINKEDIN);
                }
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(6);
        }
Example #27
0
        public static void TestVersionUpdatedWithInvalidVersionFormatFromServer()
        {
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                // The version returned has 5 components - bad!
                return new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""2.0.307.0.0"",""R"":307,""S"":0,""M"":""OK""}");
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.LongTimeSinceLastSuccessfulCheck), "This is not a successful check, and it was DateTime.MinValue since the last.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(new Uri("http://localhost/AxCrypt/Downloads.html")), "The right URL should be passed in the event args.");
            Assert.That(eventArgs.Version, Is.EqualTo(UpdateCheck.VersionUnknown), "The new version has 5 components, and should be parsed as unknown.");

            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                // The version returned is an empty string - bad!
                return new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":"""",""R"":307,""S"":0,""M"":""OK""}");
            };

            using (UpdateCheck updateCheck = new UpdateCheck(thisVersion))
            {
                updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
                {
                    eventArgs = e;
                };
                updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
                updateCheck.WaitForBackgroundCheckComplete();
            }

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.LongTimeSinceLastSuccessfulCheck), "This is not a successful check, and it was DateTime.MinValue since the last.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(new Uri("http://localhost/AxCrypt/Downloads.html")), "The right URL should be passed in the event args.");
            Assert.That(eventArgs.Version, Is.EqualTo(UpdateCheck.VersionUnknown), "The new version is an empty string and should be parse as unknown.");
        }
Example #28
0
            public static async Task <bool> CheckForRpcs3Updates(DiscordClient discordClient, DiscordChannel?channel, string?sinceCommit = null, DiscordMessage?emptyBotMsg = null)
            {
                var updateAnnouncement        = channel is null;
                var updateAnnouncementRestore = emptyBotMsg != null;
                var info = await Client.GetUpdateAsync(Config.Cts.Token, sinceCommit).ConfigureAwait(false);

                if (info?.ReturnCode != 1 && sinceCommit != null)
                {
                    info = await Client.GetUpdateAsync(Config.Cts.Token).ConfigureAwait(false);
                }

                if (updateAnnouncementRestore && info?.CurrentBuild != null)
                {
                    info.LatestBuild = info.CurrentBuild;
                }
                var embed = await info.AsEmbedAsync(discordClient, updateAnnouncement).ConfigureAwait(false);

                if (info == null || embed.Color.Value.Value == Config.Colors.Maintenance.Value)
                {
                    if (updateAnnouncementRestore)
                    {
                        Config.Log.Debug($"Failed to get update info for commit {sinceCommit}: {JsonSerializer.Serialize(info)}");
                        return(false);
                    }

                    embed = await cachedUpdateInfo.AsEmbedAsync(discordClient, updateAnnouncement).ConfigureAwait(false);
                }
                else if (!updateAnnouncementRestore)
                {
                    if (cachedUpdateInfo?.LatestBuild?.Datetime is string previousBuildTimeStr &&
                        info.LatestBuild?.Datetime is string newBuildTimeStr &&
                        DateTime.TryParse(previousBuildTimeStr, out var previousBuildTime) &&
                        DateTime.TryParse(newBuildTimeStr, out var newBuildTime) &&
                        newBuildTime > previousBuildTime)
                    {
                        cachedUpdateInfo = info;
                    }
                }
                if (!updateAnnouncement)
                {
                    await channel !.SendMessageAsync(embed: embed.Build()).ConfigureAwait(false);
                    return(true);
                }

                if (updateAnnouncementRestore)
                {
                    if (embed.Title == "Error")
                    {
                        return(false);
                    }

                    Config.Log.Debug($"Restoring update announcement for build {sinceCommit}: {embed.Title}\n{embed.Description}");
                    await emptyBotMsg !.ModifyAsync(embed: embed.Build()).ConfigureAwait(false);
                    return(true);
                }

                var latestUpdatePr = info?.LatestBuild?.Pr?.ToString();
                var match          = (
                    from field in embed.Fields
                    let m = UpdateVersionRegex.Match(field.Value)
                            where m.Success
                            select m
                    ).FirstOrDefault();
                var latestUpdateBuild = match?.Groups["build"].Value;

                if (string.IsNullOrEmpty(latestUpdatePr) ||
                    lastUpdateInfo == latestUpdatePr ||
                    !await UpdateCheck.WaitAsync(0).ConfigureAwait(false))
                {
                    return(false);
                }

                try
                {
                    if (!string.IsNullOrEmpty(lastFullBuildNumber) &&
                        !string.IsNullOrEmpty(latestUpdateBuild) &&
                        int.TryParse(lastFullBuildNumber, out var lastSaveBuild) &&
                        int.TryParse(latestUpdateBuild, out var latestBuild) &&
                        latestBuild <= lastSaveBuild)
                    {
                        return(false);
                    }

                    var compatChannel = await discordClient.GetChannelAsync(Config.BotChannelId).ConfigureAwait(false);

                    var botMember = discordClient.GetMember(compatChannel.Guild, discordClient.CurrentUser);
                    if (botMember == null)
                    {
                        return(false);
                    }

                    if (!compatChannel.PermissionsFor(botMember).HasPermission(Permissions.SendMessages))
                    {
                        NewBuildsMonitor.Reset();
                        return(false);
                    }

                    if (embed.Color.Value.Value == Config.Colors.Maintenance.Value)
                    {
                        return(false);
                    }

                    await CheckMissedBuildsBetween(discordClient, compatChannel, lastUpdateInfo, latestUpdatePr, Config.Cts.Token).ConfigureAwait(false);

                    await compatChannel.SendMessageAsync(embed : embed.Build()).ConfigureAwait(false);

                    lastUpdateInfo      = latestUpdatePr;
                    lastFullBuildNumber = latestUpdateBuild;
                    await using var db  = new BotDb();
                    var currentState = await db.BotState.FirstOrDefaultAsync(k => k.Key == Rpcs3UpdateStateKey).ConfigureAwait(false);

                    if (currentState == null)
                    {
                        await db.BotState.AddAsync(new() { Key = Rpcs3UpdateStateKey, Value = latestUpdatePr }).ConfigureAwait(false);
                    }
                    else
                    {
                        currentState.Value = latestUpdatePr;
                    }
                    var savedLastBuild = await db.BotState.FirstOrDefaultAsync(k => k.Key == Rpcs3UpdateBuildKey).ConfigureAwait(false);

                    if (savedLastBuild == null)
                    {
                        await db.BotState.AddAsync(new() { Key = Rpcs3UpdateBuildKey, Value = latestUpdateBuild }).ConfigureAwait(false);
                    }
                    else
                    {
                        savedLastBuild.Value = latestUpdateBuild;
                    }
                    await db.SaveChangesAsync(Config.Cts.Token).ConfigureAwait(false);

                    NewBuildsMonitor.Reset();
                    return(true);
                }
                catch (Exception e)
                {
                    Config.Log.Warn(e, "Failed to check for RPCS3 update info");
                }
                finally
                {
                    UpdateCheck.Release();
                }
                return(false);
            }
 /// <summary>
 /// Specifies how Linq to Sql approaches the detection of optimistic concurrency conflicts. 
 /// </summary>
 /// <remarks>
 ///	The default is 'Always' unless the entity has a version field is defined.
 /// </remarks>
 /// <param name="updateCheck">The UpdateCheck value to use</param>
 /// <returns></returns>
 public IColumnMapping UpdateCheck(UpdateCheck updateCheck)
 {
     return SetAttribute(Constants.UpdateCheck, updateCheck.ToString());
 }
Example #30
0
        private void InitializeColumnAttributeMapping(ColumnAttribute column)
        {
            this.name = string.IsNullOrEmpty(column.Name) ? this.memberInfo.Name : column.Name;

            if (column is KeyAttribute)
            {
                this.isPrimaryKey = true;

                this.key = (KeyAttribute)this.memberAttribute;

                this.isDbGenerated = this.isPrimaryKey && this.key.IsDbGenerated;

                this.sequenceName = this.key.SequenceName;
            }

            this.memberType = this.memberInfo.ReflectedType;
            this.dbType = column.DbType;

            if (this.dbType == DBType.Char ||
                this.dbType == DBType.NChar ||
                this.dbType == DBType.NVarChar ||
                this.dbType == DBType.VarChar)
            {
                this.length = column.Length;
            }

            this.isNullable = this.isPrimaryKey ? false : column.IsNullable;
            this.isUnique = this.isPrimaryKey ? true : column.IsUnique;

            if (column.IsVersion &&
               (this.dbType == DBType.Int16 ||
                this.dbType == DBType.Int32 ||
                this.dbType == DBType.Int64 ||
                this.dbType == DBType.DateTime))
            {
                this.isVersion = true;
            }
            else
            {
                throw new MappingException(string.Format("Invalid Version member type '{0}' for  '{1}' , version type must be int or datetime type.", 
                                           this.dbType.ToString(),
                                           this.entity.EntityType.Name + "." + this.memberInfo.Name));
            }

            this.updateCheck = column.UpdateCheck;
        }
Example #31
0
 private void UpdateMessageBox_YesClicked(XNAMessageBox messageBox)
 {
     UpdateCheck?.Invoke(this, EventArgs.Empty);
 }
 /// <summary>
 /// Specifies how Linq to Sql approaches the detection of optimistic concurrency conflicts.
 /// </summary>
 /// <remarks>
 ///	The default is 'Always' unless the entity has a version field is defined.
 /// </remarks>
 /// <param name="updateCheck">The UpdateCheck value to use</param>
 /// <returns></returns>
 public IColumnMapping UpdateCheck(UpdateCheck updateCheck)
 {
     return(SetAttribute(Constants.UpdateCheck, updateCheck.ToString()));
 }
Example #33
0
        public static void Sync(ConfigFile configFile, LogDelegate Log)
        {
            ConfigFileSyncPermissionsSection config = configFile.AbsenceReasonPermissions
            ;

            Log("========= ABSENCE REASONS ========= ");
            if (!config.AllowSync)
            {
                Log("This sync module is disabled in config file - skipping");
                return;
            }
            InternalAbsenceReasonRepository internalRepository = new InternalAbsenceReasonRepository(configFile.DatabaseConnectionString_Internal);
            SLAbsenceReasonRepository       externalRepository = new SLAbsenceReasonRepository(configFile.DatabaseConnectionString_SchoolLogic);

            List <AbsenceReason> externalObjects = externalRepository.GetAll();

            Log("Found " + internalRepository.GetAllIDs().Count() + " reasons in internal database");
            Log("Found " + externalObjects.Count() + " reasons in external database");

            // Find previously unknown schools
            // Find schools that need an update
            List <AbsenceReason> previouslyUnknown = new List <AbsenceReason>();
            List <AbsenceReason> needingUpdate     = new List <AbsenceReason>();
            List <AbsenceReason> noLongerExistsInExternalSystem = new List <AbsenceReason>();

            foreach (AbsenceReason externalObject in externalObjects)
            {
                // Check to see if we know about this school already
                AbsenceReason internalObject = internalRepository.Get(externalObject.ID);
                if (internalObject == null)
                {
                    previouslyUnknown.Add(externalObject);
                }

                // Check to see if this school requires an update
                if (internalObject != null)
                {
                    UpdateCheck check = internalObject.CheckIfUpdatesAreRequired(externalObject);
                    if ((check == UpdateCheck.UpdatesRequired) || (config.ForceUpdate))
                    {
                        needingUpdate.Add(externalObject);
                    }
                }
            }

            // Find schools that are no longer in the database that could potentially be cleaned up
            if (config.AllowRemovals)
            {
                List <int> foundIDs = externalRepository.GetAllIDs();
                foreach (AbsenceReason internalObject in internalRepository.GetAll())
                {
                    if (!foundIDs.Contains(internalObject.ID))
                    {
                        noLongerExistsInExternalSystem.Add(internalObject);
                    }
                }
            }

            Log("Found " + previouslyUnknown.Count() + " previously unknown");
            Log("Found " + needingUpdate.Count() + " with updates");
            Log("Found " + noLongerExistsInExternalSystem.Count() + " not in external database");

            // Commit these changes to the database
            if (previouslyUnknown.Count > 0)
            {
                if (config.AllowAdds)
                {
                    Log(" > Adding " + previouslyUnknown.Count() + " new objects");
                    internalRepository.Add(previouslyUnknown);
                }
                else
                {
                    Log(" > Not allowed to add, skipping " + previouslyUnknown.Count() + " adds");
                }
            }


            if (needingUpdate.Count > 0)
            {
                if (config.AllowUpdates)
                {
                    Log(" > Updating " + needingUpdate.Count() + " objects");
                    internalRepository.Update(needingUpdate);
                }
                else
                {
                    Log(" > Not allowed to do updates, skipping " + needingUpdate.Count() + " updates");
                }
            }

            if (noLongerExistsInExternalSystem.Count > 0)
            {
                if (config.AllowRemovals)
                {
                    Log(" > If removals were implemented, we would remove " + noLongerExistsInExternalSystem.Count() + " objects here");
                }
                else
                {
                    Log(" > Not allowed to remove, skipping " + noLongerExistsInExternalSystem.Count() + " removals");
                }
            }
        }
Example #34
0
        public static void Main(string[] args)
        {
            // Init Discord RPC
            discordClient.Initialize();

            // Set default presence
            discordClient.SetPresence(new RichPresence()
            {
                State      = "Idle",
                Timestamps = discordTime,
                Assets     = new Assets()
                {
                    LargeImageKey = "immagine",
                }
            });
            bool mutexReserved;

            using (new Mutex(true, "SpeditGlobalMutex", out mutexReserved))
            {
                if (mutexReserved)
                {
#if !DEBUG
                    try
                    {
#endif
                    SplashScreen splashScreen = new SplashScreen("Resources/Icon256x.png");
                    splashScreen.Show(false, true);
                    Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? throw new NullReferenceException();
#if !DEBUG
                    ProfileOptimization.SetProfileRoot(Environment.CurrentDirectory);
                    ProfileOptimization.StartProfile("Startup.Profile");
#endif
                    UpdateStatus  = new UpdateInfo();
                    OptionsObject = OptionsControlIOObject.Load(out var ProgramIsNew);
                    Translations  = new TranslationProvider();
                    Translations.LoadLanguage(OptionsObject.Language, true);
                    for (int i = 0; i < args.Length; ++i)
                    {
                        if (args[i].ToLowerInvariant() == "-rcck")                     //ReCreateCryptoKey
                        {
                            OptionsObject.ReCreateCryptoKey();
                            MakeRCCKAlert();
                        }
                    }
                    Configs = ConfigLoader.Load();
                    for (int i = 0; i < Configs.Length; ++i)
                    {
                        if (Configs[i].Name == OptionsObject.Program_SelectedConfig)
                        {
                            SelectedConfig = i;
                            break;
                        }
                    }
                    if (!OptionsObject.Program_UseHardwareAcceleration)
                    {
                        RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
                    }
#if !DEBUG
                    if (ProgramIsNew)
                    {
                        if (Translations.AvailableLanguageIDs.Length > 0)
                        {
                            splashScreen.Close(new TimeSpan(0, 0, 1));
                            var languageWindow = new UI.Interop.LanguageChooserWindow(Translations.AvailableLanguageIDs, Translations.AvailableLanguages);
                            languageWindow.ShowDialog();
                            string potentialSelectedLanguageID = languageWindow.SelectedID;
                            if (!string.IsNullOrWhiteSpace(potentialSelectedLanguageID))
                            {
                                OptionsObject.Language = potentialSelectedLanguageID;
                                Translations.LoadLanguage(potentialSelectedLanguageID);
                            }
                            splashScreen.Show(false, true);
                        }
                    }
#endif
                    MainWindow = new MainWindow(splashScreen);
                    PipeInteropServer pipeServer = new PipeInteropServer(MainWindow);
                    pipeServer.Start();
#if !DEBUG
                }
                catch (Exception e)
                {
                    File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT LOADING"));
                    MessageBox.Show("An error occured while loading." + Environment.NewLine + "A crash report was written in the editor-directory.",
                                    "Error while Loading",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Environment.Exit(Environment.ExitCode);
                }
#endif
                    Application app = new Application();
#if !DEBUG
                    try
                    {
                        if (OptionsObject.Program_CheckForUpdates)
                        {
                            UpdateCheck.Check(true);
                        }
#endif
                    app.Startup += App_Startup;
                    app.Run(MainWindow);
                    OptionsControlIOObject.Save();
#if !DEBUG
                }
                catch (Exception e)
                {
                    File.WriteAllText("CRASH_" + Environment.TickCount.ToString() + ".txt", BuildExceptionString(e, "SPEDIT MAIN"));
                    MessageBox.Show("An error occured." + Environment.NewLine + "A crash report was written in the editor-directory.",
                                    "Error",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                    Environment.Exit(Environment.ExitCode);
                }
#endif
                }
                else
                {
                    try
                    {
                        StringBuilder sBuilder   = new StringBuilder();
                        bool          addedFiles = false;
                        for (int i = 0; i < args.Length; ++i)
                        {
                            if (!string.IsNullOrWhiteSpace(args[i]))
                            {
                                FileInfo fInfo = new FileInfo(args[i]);
                                if (fInfo.Exists)
                                {
                                    string ext = fInfo.Extension.ToLowerInvariant().Trim(new char[] { '.', ' ' });
                                    if (ext == "sp" || ext == "inc" || ext == "txt" || ext == "smx")
                                    {
                                        addedFiles = true;
                                        sBuilder.Append(fInfo.FullName);
                                        if ((i + 1) != args.Length)
                                        {
                                            sBuilder.Append("|");
                                        }
                                    }
                                }
                            }
                        }
                        if (addedFiles)
                        {
                            PipeInteropClient.ConnectToMasterPipeAndSendData(sBuilder.ToString());
                        }
                    }
                    catch (Exception)
                    {
                        // ignored
                    }         //dont f**k the user up with irrelevant data
                }
            }
        }
Example #35
0
        static void Main(string[] args)
        {
            BuildInfo.isWindows = Environment.OSVersion.ToString().ToLower().Contains("windows");

            if ((Environment.CommandLine.Length >= 1 || args.Length >= 1) && Environment.CommandLine.Contains("--autostart"))
            {
                if (Directory.Exists(BuildInfo.isWindows ? $"{Environment.CurrentDirectory}\\Beat Saber" : $"{AppDomain.CurrentDomain.BaseDirectory}Beat Saber"))
                {
                    PlayGame.LaunchGame(Environment.CommandLine.Contains("oculus"));
                    Task.Delay(1000);
                    Process.GetCurrentProcess().Kill();
                }
                Con.Log("Game Not installed, running program like normal.");
            }

            if (Environment.CommandLine.Contains("debug"))
            {
                isDebug = true;
                Con.Init();
            }
            Con.BSL_Logo();
            Con.Log("This tool will allow you to easily downgrade your Beat Saber.");
            Con.Log("Brought to you by the", "Beat Saber Legacy Group", ConsoleColor.DarkCyan);
            Con.Space();

            //JSONSetup.Load();

            if (isDebug)
            {
                Con.Log($"Environment Version is v{Environment.Version}");
                Con.Log($"OS is {Environment.OSVersion}");
                Con.Log($"Debug: isWindows = {BuildInfo.isWindows}");
            }

            if (!isDebug)
            {
                UpdateCheck.CheckForUpdates();
            }

            bool showError = false;

            if (BuildInfo.isWindows)
            {
                if (!Directory.Exists(Environment.CurrentDirectory + "\\Resources") || !Directory.Exists(Environment.CurrentDirectory + "\\Depotdownloader"))
                {
                    showError = true;
                }
            }
            else
            {
                if (!Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}Resources") || !Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}Depotdownloader"))
                {
                    showError = true;
                }
            }

            if (showError)
            {
                Con.Error("Please be sure you have extracted the files before running this!");
                Con.Error("Program will not run until you have extracted all the contents out of the ZIP file.");
                Con.Exit();
            }
            else
            {
                BeginInputOption();
            }
        }
Example #36
0
        protected void showAbout()
        {
            GUILayout.Label(Util.Constants.ASSET_NAME, EditorStyles.boldLabel);

            GUILayout.BeginHorizontal();
            {
                GUILayout.BeginVertical(GUILayout.Width(60));
                {
                    GUILayout.Label("Version:");

                    GUILayout.Space(12);

                    GUILayout.Label("Web:");

                    GUILayout.Space(2);

                    GUILayout.Label("Email:");
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.Width(170));
                {
                    GUILayout.Space(0);

                    GUILayout.Label(Util.Constants.ASSET_VERSION);

                    GUILayout.Space(12);

                    EditorGUILayout.SelectableLabel(Util.Constants.ASSET_AUTHOR_URL, GUILayout.Height(16), GUILayout.ExpandHeight(false));

                    GUILayout.Space(2);

                    EditorGUILayout.SelectableLabel(Util.Constants.ASSET_CONTACT, GUILayout.Height(16), GUILayout.ExpandHeight(false));
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.ExpandWidth(true));
                {
                    //GUILayout.Space(0);
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical(GUILayout.Width(64));
                {
                    if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Logo_Asset, "Visit asset website")))
                    {
                        Application.OpenURL(EditorConstants.ASSET_URL);
                        GAApi.Event(typeof(ConfigBase).Name, "ASSET_URL");
                    }

                    if (!Util.Constants.isPro)
                    {
                        if (GUILayout.Button(new GUIContent(" Upgrade", "Upgrade " + Util.Constants.ASSET_NAME + " to the PRO-version")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_PRO_URL);
                            GAApi.Event(typeof(ConfigBase).Name, "ASSET_PRO_URL");
                        }
                    }
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();

            GUILayout.Label("© 2015-2017 by " + Util.Constants.ASSET_AUTHOR);

            EditorHelper.SeparatorUI();

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button(new GUIContent(" AssetStore", EditorHelper.Logo_Unity, "Visit the 'Unity AssetStore' website.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_CT_URL);
                    GAApi.Event(typeof(ConfigBase).Name, "ASSET_CT_URL");
                }

                if (GUILayout.Button(new GUIContent(" " + Util.Constants.ASSET_AUTHOR, EditorHelper.Logo_CT, "Visit the '" + Util.Constants.ASSET_AUTHOR + "' website.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_AUTHOR_URL);
                    GAApi.Event(typeof(ConfigBase).Name, "ASSET_AUTHOR_URL");
                }
            }
            GUILayout.EndHorizontal();

            EditorHelper.SeparatorUI();

            aboutTab = GUILayout.Toolbar(aboutTab, new string[] { "Readme", "Versions", "SSML", "EML", "Update" });

            if (aboutTab == 4)
            {
                scrollPosAboutUpdate = EditorGUILayout.BeginScrollView(scrollPosAboutUpdate, false, false);
                {
                    Color fgColor = GUI.color;

                    GUI.color = Color.yellow;

                    if (updateStatus == UpdateStatus.NO_UPDATE)
                    {
                        GUI.color = Color.green;
                        GUILayout.Label(updateText);
                    }
                    else if (updateStatus == UpdateStatus.UPDATE)
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" Download", "Visit the 'Unity AssetStore' to download the latest version.")))
                        {
                            Application.OpenURL(EditorConstants.ASSET_URL);
                            GAApi.Event(typeof(ConfigBase).Name, "UPDATE");
                        }
                    }
                    else if (updateStatus == UpdateStatus.UPDATE_PRO)
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" Upgrade", "Upgrade to the PRO-version in the 'Unity AssetStore'.")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_PRO_URL);
                            GAApi.Event(typeof(ConfigBase).Name, "UPGRADE PRO");
                        }
                    }
                    else if (updateStatus == UpdateStatus.UPDATE_VERSION)
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" Upgrade", "Upgrade to the newer version in the 'Unity AssetStore'")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_CT_URL);
                            GAApi.Event(typeof(ConfigBase).Name, "UPGRADE");
                        }
                    }
                    else if (updateStatus == UpdateStatus.DEPRECATED)
                    {
                        GUILayout.Label(updateText);

                        if (GUILayout.Button(new GUIContent(" More Information", "Visit the 'crosstales'-site for more information.")))
                        {
                            Application.OpenURL(Util.Constants.ASSET_AUTHOR_URL);
                            GAApi.Event(typeof(ConfigBase).Name, "DEPRECATED");
                        }
                    }
                    else
                    {
                        GUI.color = Color.cyan;
                        GUILayout.Label(updateText);
                    }

                    GUI.color = fgColor;
                }
                EditorGUILayout.EndScrollView();

                if (updateStatus == UpdateStatus.NOT_CHECKED || updateStatus == UpdateStatus.NO_UPDATE)
                {
                    bool isChecking = !(worker == null || (worker != null && !worker.IsAlive));

                    GUI.enabled = Util.Helper.isInternetAvailable && !isChecking;

                    if (GUILayout.Button(new GUIContent(isChecking ? "Checking... Please wait." : " Check For Update", EditorHelper.Icon_Check, "Checks for available updates of " + Util.Constants.ASSET_NAME)))
                    {
                        worker = new System.Threading.Thread(() => UpdateCheck.UpdateCheckForEditor(out updateText, out updateStatus));
                        worker.Start();

                        GAApi.Event(typeof(ConfigBase).Name, "UpdateCheck");
                    }

                    GUI.enabled = true;
                }
            }
            else if (aboutTab == 0)
            {
                if (readme == null)
                {
                    string path = Application.dataPath + EditorConfig.ASSET_PATH + "README.txt";

                    try
                    {
                        readme = System.IO.File.ReadAllText(path);
                    }
                    catch (System.Exception)
                    {
                        readme = "README not found: " + path;
                    }
                }

                scrollPosAboutReadme = EditorGUILayout.BeginScrollView(scrollPosAboutReadme, false, false);
                {
                    GUILayout.Label(readme);
                }
                EditorGUILayout.EndScrollView();
            }
            else if (aboutTab == 1)
            {
                if (versions == null)
                {
                    string path = Application.dataPath + EditorConfig.ASSET_PATH + "Documentation/VERSIONS.txt";

                    try
                    {
                        versions = System.IO.File.ReadAllText(path);
                    }
                    catch (System.Exception)
                    {
                        versions = "VERSIONS not found: " + path;
                    }
                }

                scrollPosAboutVersions = EditorGUILayout.BeginScrollView(scrollPosAboutVersions, false, false);
                {
                    GUILayout.Label(versions);
                }

                EditorGUILayout.EndScrollView();
            }
            else if (aboutTab == 2)
            {
                if (ssml == null)
                {
                    string path = Application.dataPath + EditorConfig.ASSET_PATH + "Documentation/SSML.txt";

                    try
                    {
                        ssml = System.IO.File.ReadAllText(path);
                    }
                    catch (System.Exception)
                    {
                        ssml = "SSML not found: " + path;
                    }
                }

                scrollPosAboutVersions = EditorGUILayout.BeginScrollView(scrollPosAboutVersions, false, false);
                {
                    GUILayout.Label(ssml);
                }

                EditorGUILayout.EndScrollView();
            }
            else
            {
                if (emotionml == null)
                {
                    string path = Application.dataPath + EditorConfig.ASSET_PATH + "Documentation/EMOTIONML.txt";

                    try
                    {
                        emotionml = System.IO.File.ReadAllText(path);
                    }
                    catch (System.Exception)
                    {
                        emotionml = "EmotionML not found: " + path;
                    }
                }

                scrollPosAboutVersions = EditorGUILayout.BeginScrollView(scrollPosAboutVersions, false, false);
                {
                    GUILayout.Label(emotionml);
                }

                EditorGUILayout.EndScrollView();
            }

            EditorHelper.SeparatorUI();

            GUILayout.BeginHorizontal();
            {
                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Facebook, "Follow us on 'Facebook'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_FACEBOOK);
                    GAApi.Event(typeof(ConfigBase).Name, "ASSET_SOCIAL_FACEBOOK");
                }

                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Twitter, "Follow us on 'Twitter'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_TWITTER);
                    GAApi.Event(typeof(ConfigBase).Name, "ASSET_SOCIAL_TWITTER");
                }

                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Linkedin, "Follow us on 'LinkedIn'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_LINKEDIN);
                    GAApi.Event(typeof(ConfigBase).Name, "ASSET_SOCIAL_LINKEDIN");
                }

                if (GUILayout.Button(new GUIContent(string.Empty, EditorHelper.Social_Xing, "Follow us on 'XING'.")))
                {
                    Application.OpenURL(Util.Constants.ASSET_SOCIAL_XING);
                    GAApi.Event(typeof(ConfigBase).Name, "ASSET_SOCIAL_XING");
                }
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(6);
        }
Example #37
0
        public static void Sync(ConfigFile configFile, LogDelegate Log)
        {
            ConfigFileSyncPermissionsSection config = configFile.ExpectedAttendancePermissions;

            Log("========= EXPECTED ATTENDANCE ========= ");
            if (!config.AllowSync)
            {
                Log("This sync module is disabled in config file - skipping");
                return;
            }

            // Load all students that have enrolled classes
            //  - a DISTINCT() on the enrollment table should do nicely here

            // Load all of those student's schedules
            // - Load each class's schedule, then combine into the student's own schedule

            // Parse the school year from the config file, we'll need it later
            InternalSchoolYearRepository _schoolYearRepo = new InternalSchoolYearRepository(configFile.DatabaseConnectionString_Internal);
            SchoolYear schoolYear = _schoolYearRepo.Get(configFile.SchoolYearName);

            if (schoolYear == null)
            {
                throw new InvalidSchoolYearException("School year from config file is invalid");
            }

            SLStudentRepository _studentRepo = new SLStudentRepository(configFile.DatabaseConnectionString_SchoolLogic);
            SLTrackRepository   _trackRepo   = new SLTrackRepository(configFile.DatabaseConnectionString_SchoolLogic);

            List <Student> dailyAttendanceStudents  = _studentRepo.GetDailyAttendanceStudents();
            List <Student> periodAttendanceStudents = _studentRepo.GetPeriodAttendanceStudents();

            Log("Found " + dailyAttendanceStudents.Count() + " students in a daily track");
            Log("Found " + periodAttendanceStudents.Count() + " students in a period track");

            List <StudentExpectedAttendanceEntry> externalObjects = new List <StudentExpectedAttendanceEntry>();

            foreach (Student student in dailyAttendanceStudents)
            {
                // Get this student's track
                Track track = _trackRepo.GetTrackFor(student.iStudentID);

                if (track != null)
                {
                    // For each calendar day for the whole school year
                    foreach (CalendarDay day in CalendarDay.GetCalendarDaysBetween(schoolYear.Starts, schoolYear.Ends, true))
                    {
                        // If this calendar day is instructional, use the daily blocks per day for the track as the value
                        // If this calendar day is not instructional, set it to zero
                        // We might not want to actually store zeroes in the database
                        if (track.Schedule.IsInstructional(day))
                        {
                            externalObjects.Add(new StudentExpectedAttendanceEntry()
                            {
                                iStudentID    = student.iStudentID,
                                iSchoolYearID = schoolYear.ID,
                                Date          = day,
                                BlocksToday   = track.DailyBlocksPerDay
                            });
                        }
                    }
                }
            }

            // Get student schedules for period attendance students
            SLStudentScheduleRepository _scheduleRepository = new SLStudentScheduleRepository(configFile.DatabaseConnectionString_SchoolLogic);

            Log("Loading student schedules...");
            Dictionary <int, StudentClassSchedule> _allStudentSchedules = _scheduleRepository.Get(periodAttendanceStudents.Select(x => x.iStudentID).ToList());

            Log("Finished loading student schedules.");

            foreach (Student student in periodAttendanceStudents)
            {
                // Get this student's track
                Track track = _trackRepo.GetTrackFor(student.iStudentID);
                if (!_allStudentSchedules.ContainsKey(student.iStudentID))
                {
                    continue;
                }
                StudentClassSchedule schedule = _allStudentSchedules[student.iStudentID];

                // Make a StudentSchedule object to handle some of this automatically
                // I want to create a new StudentSchedule object (or a dictionary of them)
                // that can be easily queried for a specific calendar day

                if (track != null)
                {
                    // For each calendar day for the whole school year
                    foreach (CalendarDay day in CalendarDay.GetCalendarDaysBetween(schoolYear.Starts, schoolYear.Ends, true))
                    {
                        // If this calendar day is instructional, calculate the student's scheduled blocks
                        if (track.Schedule.IsInstructional(day))
                        {
                            // Calculate the student's schedule for today
                            int blocksToday = schedule.GetNumberOfScheduledBlocksOn(day);
                            if (blocksToday > 0)
                            {
                                externalObjects.Add(new StudentExpectedAttendanceEntry()
                                {
                                    iStudentID    = student.iStudentID,
                                    iSchoolYearID = schoolYear.ID,
                                    Date          = day,
                                    BlocksToday   = blocksToday
                                });
                            }
                        }
                    }
                }
            }

            Log("Found " + externalObjects.Count() + " external objects");

            InternalStudentExpectedAttendanceRepository internalRepository = new InternalStudentExpectedAttendanceRepository(configFile.DatabaseConnectionString_Internal);

            Log("Found " + internalRepository.RecordCount(schoolYear.ID) + " internal objects");

            /* ************************************************************ */
            // *
            // * This took over 6 hours to do, so we need to make a more efficient way of doing this.
            // * Perhaps the repository needs to store in a Dictionary<> mess instead of a single list
            // *
            /* ************************************************************ */
            // Compare for changes after here - all the above code was just loading stuff
            List <StudentExpectedAttendanceEntry> previouslyUnknown = new List <StudentExpectedAttendanceEntry>();
            List <StudentExpectedAttendanceEntry> needingUpdate     = new List <StudentExpectedAttendanceEntry>();
            List <StudentExpectedAttendanceEntry> noLongerExistsInExternalSystem = new List <StudentExpectedAttendanceEntry>();

            int     doneCount             = 0;
            int     totalExternalObjects  = externalObjects.Count();
            decimal donePercent           = 0;
            decimal doneThresholdPercent  = (decimal)0.1;
            decimal doneThresholdIncrease = (decimal)0.1;

            foreach (StudentExpectedAttendanceEntry externalObject in externalObjects)
            {
                // Check to see if we know about this object already
                StudentExpectedAttendanceEntry internalObject = internalRepository.Get(externalObject.iStudentID, externalObject.iSchoolYearID, externalObject.Date.Year, externalObject.Date.Month, externalObject.Date.Day);
                if (internalObject == null)
                {
                    previouslyUnknown.Add(externalObject);
                }

                // Check to see if this object requires an update
                if (internalObject != null)
                {
                    UpdateCheck check = internalObject.CheckIfUpdatesAreRequired(externalObject);
                    if ((check == UpdateCheck.UpdatesRequired) || (config.ForceUpdate))
                    {
                        needingUpdate.Add(externalObject);
                    }
                }

                doneCount++;
                donePercent = (decimal)((decimal)doneCount / (decimal)totalExternalObjects);
                if (donePercent > doneThresholdPercent)
                {
                    doneThresholdPercent = doneThresholdPercent + doneThresholdIncrease;
                    Log((int)(donePercent * 100) + "% finished inspecting objects");
                }

                if (doneCount == totalExternalObjects)
                {
                    Log("100% finished inspecting objects");
                }
            }

            Log("Found " + previouslyUnknown.Count() + " previously unknown");
            Log("Found " + needingUpdate.Count() + " with updates");

            // Commit these changes to the database
            if (previouslyUnknown.Count > 0)
            {
                if (config.AllowAdds)
                {
                    Log(" > Adding " + previouslyUnknown.Count() + " new objects");
                    internalRepository.Add(previouslyUnknown);
                }
                else
                {
                    Log(" > Not allowed to add, skipping " + previouslyUnknown.Count() + " adds");
                }
            }


            if (needingUpdate.Count > 0)
            {
                if (config.AllowUpdates)
                {
                    Log(" > Updating " + needingUpdate.Count() + " objects");
                    internalRepository.Update(needingUpdate);
                }
                else
                {
                    Log(" > Not allowed to do updates, skipping " + needingUpdate.Count() + " updates");
                }
            }

            Log("Finished syncing Expected Attendance");
        }
Example #38
0
        public static void TestDoubleDisposeAndObjectDisposedException()
        {
            SetupAssembly.FakeRuntimeEnvironment.WebCallerCreator = () =>
            {
                return new FakeWebCaller(@"{""U"":""http://localhost/AxCrypt/Downloads.html"",""V"":""2.0.307.0"",""R"":307,""S"":0,""M"":""OK""}");
            };

            DateTime utcNow = DateTime.UtcNow;
            SetupAssembly.FakeRuntimeEnvironment.TimeFunction = () => { return utcNow; };

            Version thisVersion = new Version(2, 0, 300, 0);
            Version newVersion = new Version(2, 0, 307, 0);
            Uri restApiUrl = new Uri("http://localhost/RestApi.asxh/axcrypt2version");
            Uri updateWebPageUrl = new Uri("http://www.axantum.com/");
            VersionEventArgs eventArgs = null;
            UpdateCheck updateCheck = new UpdateCheck(thisVersion);
            updateCheck.VersionUpdate += (object sender, VersionEventArgs e) =>
            {
                eventArgs = e;
            };
            updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl);
            updateCheck.WaitForBackgroundCheckComplete();
            updateCheck.Dispose();

            Assert.DoesNotThrow(updateCheck.Dispose);
            Assert.Throws<ObjectDisposedException>(() => { updateCheck.CheckInBackground(DateTime.MinValue, UpdateCheck.VersionUnknown.ToString(), restApiUrl, updateWebPageUrl); });
            Assert.Throws<ObjectDisposedException>(updateCheck.WaitForBackgroundCheckComplete);

            Assert.That(eventArgs, Is.Not.Null, "The VersionUpdate event should be called with non-null VersionEventArgs.");
            Assert.That(eventArgs.VersionUpdateStatus, Is.EqualTo(VersionUpdateStatus.NewerVersionIsAvailable), "The new version was newer.");
            Assert.That(eventArgs.UpdateWebpageUrl, Is.EqualTo(new Uri("http://localhost/AxCrypt/Downloads.html")), "The right URL should be passed in the event args.");
            Assert.That(eventArgs.Version, Is.EqualTo(newVersion), "The new version should be passed back.");
        }
Example #39
0
 public virtual Task Execute(IJobExecutionContext context)
 {
     UpdateCheck.CheckForUpdates();
     return(Task.CompletedTask);
 }