Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="Tasque.Core.BackendManager"/> class.
        /// </summary>
        /// <param name='preferences'>
        /// Preferences.
        /// </param>
        /// <exception cref="T:System.ArgumentNullException">
        /// thrown when preferences is <c>null</c>.
        /// </exception>
        public BackendManager(IPreferences preferences)
        {
            manager = new InternalBackendManager (preferences);

            // setup backend manager for AllList
            Tasque.Utils.AllList.SetBackendManager (this);
        }
		public RecentFilesProvider (IPreferences prefs)
		{
			NumRecentDocs = prefs.Get<int> ("NumRecentDocs", 7);
			
			RefreshRecentDocs ();
			Gtk.RecentManager.Default.Changed += delegate { RefreshRecentDocs (); };
		}
        /// <summary>
        /// Initializes a new instance of the StringSequenceFeedSourceStore class.
        /// </summary>
        /// <param name="preferences">IStringSequenceStore instance.</param>
        /// <param name="filterTag">Gallery filter tag for the feed sources.</param>
        public StringSequenceFeedSourceStore(IPreferences preferences, string filterTag)
            : base(preferences)
        {
            _filterTag = filterTag;

            _stringSequenceStore = new StringSequenceStore(this.Preferences);
        }
Ejemplo n.º 4
0
		static NPR ()
		{
			prefs = DockServices.Preferences.Get <NPR> ();
			Stations = new List<Station> ();
			// create the null station
			LookupStation (-1);
		}
Ejemplo n.º 5
0
 public ConnectionManager(IPreferences preferences, IPowerManager powerManager, IConnectionInfo connectionInfo, IBlackoutTime blackoutTime)
 {
     Preferences = preferences;
     PowerManager = powerManager;
     ConnectionInfo = connectionInfo;
     BlackoutTime = blackoutTime;
 }
 public RenderPackageFactoryViewModel(IPreferences preferenceSettings)
 {
     this.factory = new HelixRenderPackageFactory()
     {
         TessellationParameters = { ShowEdges = preferenceSettings.ShowEdges }
     };
 }
Ejemplo n.º 7
0
		public Connection (IPreferences preferences)
		{
			if (null == preferences) {
				throw new ArgumentNullException ("preferences");
			}
			this.preferences = preferences;
			this.cookies = new CookieCollection ();
		}
Ejemplo n.º 8
0
 /// <summary>
 /// Enables starting Dynamo with a mock IUpdateManager
 /// </summary>
 /// <param name="updateManager"></param>
 /// <param name="watchHandler"></param>
 /// <param name="preferences"></param>
 /// <param name="visualizationManager"></param>
 protected void StartDynamo(IUpdateManager updateManager, ILogger logger, IWatchHandler watchHandler, IPreferences preferences, IVisualizationManager visualizationManager)
 {
     //create a new instance of the ViewModel
     Controller = new DynamoController(Context.NONE, updateManager, logger, watchHandler, preferences);
     Controller.DynamoViewModel = new DynamoViewModel(Controller, null);
     DynamoController.IsTestMode = true;
     Controller.VisualizationManager = new VisualizationManager();
 }
        public static void GetPreferences(this ModbusAdaptersViewModel modbusAdaptersViewModel, IPreferences preferences, string key)
        {
            var selectedPort = modbusAdaptersViewModel.SelectedPort;

            if (selectedPort != null)
            {
                preferences[key] = selectedPort;
            }
        }
		public Setting(string id, ISettings settings)
		{
			ID = id;
			if (settings != null)
			{
				_preferences = settings.Preferences;
				settings.AddSetting(id, this);
			}
		}
Ejemplo n.º 11
0
 private void ScanAllPackageDirectories(IPreferences preferences)
 { 
     foreach (var dir in 
         Directory.EnumerateDirectories(RootPackagesDirectory, "*", SearchOption.TopDirectoryOnly))
     {
         var pkg = ScanPackageDirectory(dir);
         if (preferences.PackageDirectoriesToUninstall.Contains(dir)) pkg.MarkForUninstall(preferences);
     }
 }
Ejemplo n.º 12
0
 public NuGetFeedSourceStore(IPreferences preferences)
     : base(preferences)
 {
     _packageSourceProvider = new PackageSourceProvider(
         // Do not load user settings or machine wide settings for WebMatrix 'nuget.org' feed
         // In other words, pass all null to LoadDefaultSettings
         Settings.LoadDefaultSettings(null, null, null),
         defaultSources: new[] { new PackageSource("https://www.nuget.org/api/v2", Resources.NuGet_PackageSourceName) });
 }
Ejemplo n.º 13
0
 public void Load(IPreferences preferences, IPathManager pathManager)
 {
     // Load Packages
     PackageLoader.DoCachedPackageUninstalls(preferences);
     PackageLoader.LoadAll(new LoadPackageParams
     {
         Preferences = preferences,
         PathManager = pathManager
     });
 }
Ejemplo n.º 14
0
		public void Initialize (IPreferences preferences)
		{
			if (preferences == null)
				throw new ArgumentNullException ("preferences");
			this.preferences = preferences;

			// *************************************
			// AUTHENTICATION to Remember The Milk
			// *************************************
			string authToken = preferences.Get (PreferencesKeys.AuthTokenKey);
			if (authToken != null) {
				Logger.Debug ("Found AuthToken, checking credentials...");
				try {
					Rtm = new RtmNet.Rtm (ApiKey, SharedSecret, authToken);
					rtmAuth = Rtm.AuthCheckToken (authToken);
					Timeline = Rtm.TimelineCreate ();
					Logger.Debug ("RTM Auth Token is valid!");
					Logger.Debug ("Setting configured status to true");
					IsConfigured = true;
				} catch (RtmNet.RtmApiException e) {
					preferences.Set (PreferencesKeys.AuthTokenKey, null);
					preferences.Set (PreferencesKeys.UserIdKey, null);
					preferences.Set (PreferencesKeys.UserNameKey, null);
					Rtm = null;
					rtmAuth = null;
					Logger.Error ("Exception authenticating, reverting "
					              + e.Message);
				} catch (RtmNet.ResponseXmlException e) {
					Rtm = null;
					rtmAuth = null;
					Logger.Error ("Cannot parse RTM response. " +
						"Maybe the service is down. " + e.Message);
				} catch (RtmNet.RtmWebException e) {
					Rtm = null;
					rtmAuth = null;
					Logger.Error ("Not connected to RTM, maybe proxy: #{0}",
					              e.Message);
				} catch (System.Net.WebException e) {
					Rtm = null;
					rtmAuth = null;
					Logger.Error ("Problem connecting to internet: #{0}",
					              e.Message);
				}
			}

			if (Rtm == null) {
				Rtm = new RtmNet.Rtm (ApiKey, SharedSecret);
				if (NeedsConfiguration != null)
					NeedsConfiguration (this, EventArgs.Empty);
				return;
			}

			FinishInitialization ();
		}
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StartupParams"/> class.
 /// </summary>
 /// <param name="provider"><see cref="IAuthProvider"/> for DynamoModel</param>
 /// <param name="pathManager"><see cref="IPathManager"/> for DynamoModel</param>
 /// <param name="libraryLoader"><see cref="ILibraryLoader"/> for DynamoModel</param>
 /// <param name="customNodeManager"><see cref="ICustomNodeManager"/> for DynamoModel</param>
 /// <param name="dynamoVersion"><see cref="Version"/> for DynamoModel</param>
 /// <param name="preferences"><see cref="IPreferences"/> for DynamoModel</param>
 public StartupParams(IAuthProvider provider, IPathManager pathManager,
     ILibraryLoader libraryLoader, ICustomNodeManager customNodeManager,
     Version dynamoVersion, IPreferences preferences)
 {
     this.authProvider = provider;
     this.pathManager = pathManager;
     this.libraryLoader = libraryLoader;
     this.customNodeManager = customNodeManager;
     this.dynamoVersion = dynamoVersion;
     this.preferences = preferences;
 }
Ejemplo n.º 16
0
        public InternalBackendManager(IPreferences preferences)
        {
            if (preferences == null)
                throw new ArgumentNullException ("preferences");
            this.preferences = preferences;

            availableBackendNodes = AddinManager
                .GetExtensionNodes<BackendNode> (typeof(IBackend));

            taskLists = new TaskListCollection ();
        }
        public static void ApplyPreferences(this ModbusAdaptersViewModel modbusAdaptersViewModel, IPreferences preferences, string key)
        {
            var displayName = preferences[key];

            var item = modbusAdaptersViewModel.Ports.FirstOrDefault(a => string.Compare(a, displayName, true) == 0);

            if (item != null)
            {
                modbusAdaptersViewModel.SelectedPort = item;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Enables starting Dynamo with a mock IUpdateManager
        /// </summary>
        /// <param name="updateManager"></param>
        /// <param name="watchHandler"></param>
        /// <param name="preferences"></param>
        /// <param name="visualizationManager"></param>
        protected void StartDynamo(IUpdateManager updateManager, IWatchHandler watchHandler, IPreferences preferences, IVisualizationManager visualizationManager)
        {
            var corePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            DynamoPathManager.Instance.InitializeCore(corePath);

            //create a new instance of the ViewModel
            Controller = new DynamoController(Context.NONE, updateManager, watchHandler, preferences, corePath);
            Controller.DynamoViewModel = new DynamoViewModel(Controller, null);
            DynamoController.IsTestMode = true;
            Controller.VisualizationManager = new VisualizationManager();
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     Scan the PackagesDirectory for packages and attempt to load all of them.  Beware! Fails silently for duplicates.
        /// </summary>
        public void LoadPackagesIntoDynamo( IPreferences preferences, LibraryServices libraryServices )
        {
            this.ScanAllPackageDirectories( preferences );

            foreach (var pkg in LocalPackages)
            {
                DynamoPathManager.Instance.AddResolutionPath(pkg.BinaryDirectory);
            }

            foreach (var pkg in LocalPackages)
            {
                pkg.LoadIntoDynamo(loader, logger, libraryServices);
            }
        }
Ejemplo n.º 20
0
        public PackagePathViewModel(IPreferences setting)
        {
            RootLocations = new ObservableCollection<string>(setting.CustomPackageFolders);
            this.setting = setting;

            AddPathCommand = new DelegateCommand(p => InsertPath());
            DeletePathCommand = new DelegateCommand(p => RemovePathAt((int) p), CanDelete);
            MovePathUpCommand = new DelegateCommand(p => SwapPath((int) p, ((int) p) - 1), CanMoveUp);
            MovePathDownCommand = new DelegateCommand(p => SwapPath((int) p, ((int) p) + 1), CanMoveDown);
            UpdatePathCommand = new DelegateCommand(p => UpdatePathAt((int) p));
            SaveSettingCommand = new DelegateCommand(CommitChanges);

            SelectedIndex = 0;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Tasque.Client.BackendManager"/> class.
        /// </summary>
        /// <param name='preferences'>The preferences.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para>
        /// Thrown, when <paramref name="backendInfos"/> is <c>null</c> -or-
        /// </para>
        /// <para>
        /// when <paramref name="preferences"/> is <c>null</c>.
        /// </para>
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrown, when <paramref name="backendInfos"/> is empty.
        /// </exception>
        public BackendManager(IEnumerable<BackendInfo> backendInfos, IPreferences preferences)
        {
            if (backendInfos == null)
                throw new ArgumentNullException ("backendInfos");
            if (!backendInfos.Any ())
                throw new ArgumentException ("backendInfos must at least have one element");
            if (preferences == null)
                throw new ArgumentNullException ("preferences");

            AvailableBackends = new ReadOnlyCollection<BackendInfo> (backendInfos.ToList ());
            this.preferences = preferences;

            taskLists = new TaskListCollection ();
            TaskLists = new ReadOnlyObservableCollection<ITaskList> (taskLists);
        }
Ejemplo n.º 22
0
		void IBackend.Initialize (IPreferences preferences)
		{
			if (preferences == null)
				throw new ArgumentNullException ("preferences");
			
			database = new Database ();
			database.Open ();

			taskListRepo = new SqliteTaskListRepository (database);
			taskRepo = new SqliteTaskRepository (database);
			noteRepo = new SqliteNoteRepository (database);

			IsInitialized = true;
			if (Initialized != null)
				Initialized (this, EventArgs.Empty);
		}
Ejemplo n.º 23
0
        private void ScanPackageDirectories(string root, IPreferences preferences)
        {
            if (!Directory.Exists(root))
            {
                this.Log(string.Format(Resources.InvalidPackageFolderWarning, root));
                return;
            }

            foreach (var dir in
                     Directory.EnumerateDirectories(root, "*", SearchOption.TopDirectoryOnly))
            {
                var pkg = ScanPackageDirectory(dir);
                if (pkg != null && preferences.PackageDirectoriesToUninstall.Contains(dir))
                {
                    pkg.MarkForUninstall(preferences);
                }
            }
        }
Ejemplo n.º 24
0
 public void Initialize(TreeModel model, TaskView view, IPreferences preferences)
 {
     if (view == null)
     {
         throw new ArgumentNullException("view");
     }
     this.view = view;
     if (preferences == null)
     {
         throw new ArgumentNullException("preferences");
     }
     this.preferences = preferences;
     if (model == null)
     {
         throw new ArgumentNullException("model");
     }
     this.model = model;
 }
Ejemplo n.º 25
0
        public PullKeysTests()
        {
            DependencyInjectionConfig.Init();
            string zipDirectory = ServiceLocator.Current.GetInstance <IFileSystem>().CacheDirectory;

            if (!Directory.Exists(zipDirectory))
            {
                Directory.CreateDirectory(zipDirectory);
            }
            _helper = new ZipDownloaderHelper();

            _preferences    = ServiceLocator.Current.GetInstance <IPreferences>();
            _logManager     = ServiceLocator.Current.GetInstance <ILoggingManager>();
            _developerTools = ServiceLocator.Current.GetInstance <IDeveloperToolsService>();
            _preferences.Clear();
            _logManager.DeleteAll();
            _developerTools.ClearAllFields();
        }
Ejemplo n.º 26
0
 public ExtendedNotificationService(IAnalyticsService analyticsService,
                                    DeepLinkingService deepLinkingService,
                                    MobileSortingService sortingService,
                                    AzureFunctionsApiService azureFunctionsApiService,
                                    IPreferences preferences,
                                    ISecureStorage secureStorage,
                                    INotificationManager notificationManager,
                                    INotificationService notificationService) :
     base(analyticsService,
          deepLinkingService,
          sortingService,
          azureFunctionsApiService,
          preferences,
          secureStorage,
          notificationManager,
          notificationService)
 {
 }
Ejemplo n.º 27
0
        public BenchmarksModel(IPreferences preferences, IProteinService proteinService,
                               IProteinBenchmarkService benchmarkService, IEnumerable <BenchmarksReport> reports)
        {
            Preferences      = preferences ?? new InMemoryPreferencesProvider();
            ProteinService   = proteinService ?? NullProteinService.Instance;
            BenchmarkService = benchmarkService ?? NullProteinBenchmarkService.Instance;
            Reports          = reports ?? Array.Empty <BenchmarksReport>();

            SlotIdentifiers            = new BindingSource();
            SlotIdentifiers.DataSource = new BindingList <ListItem> {
                RaiseListChangedEvents = false
            };
            SlotProjects            = new BindingSource();
            SlotProjects.DataSource = new BindingList <ListItem> {
                RaiseListChangedEvents = false
            };
            SelectedSlotProjectListItems = new BindingSourceListItemCollection(SlotProjects);
        }
Ejemplo n.º 28
0
        public PreferenceEditor(IPreferences pref)
        {
            InitializeComponent();
            _boldFont    = new Font(_listView.Font, _listView.Font.Style | FontStyle.Bold);
            _preferences = pref;

            _filterChangeTimer          = new Timer();
            _filterChangeTimer.Interval = 500;
            _filterChangeTimer.Tick    += new EventHandler(OnFilterChangeTimer);

            StringResource sr = UsabilityPlugin.Strings;

            _filterLabel.Text  = sr.GetString("Form.PreferenceEditor._filterLabel");
            _nameHeader.Text   = sr.GetString("Form.PreferenceEditor._nameHeader");
            _typeHeader.Text   = sr.GetString("Form.PreferenceEditor._typeHeader");
            _valueHeader.Text  = sr.GetString("Form.PreferenceEditor._valueHeader");
            _okButton.Text     = sr.GetString("Common.OK");
            _cancelButton.Text = sr.GetString("Common.Cancel");
            _resetButton.Text  = sr.GetString("Form.PreferenceEditor._resetButton");
            this.Text          = sr.GetString("Form.PreferenceEditor.Text");

            //洗い出し
            _folderTags = new List <FolderTag>();
            _itemTags   = new List <ItemTag>();
            foreach (IPreferenceFolder folder in _preferences.GetAllFolders())
            {
                FolderTag ft = new FolderTag(folder);
                _folderTags.Add(ft);
                int count = ft.Work.ChildCount;
                for (int i = 0; i < count; i++)
                {
                    IPreferenceItem item = ft.Work.ChildAt(i).AsItem();
                    if (item != null)
                    {
                        ItemTag it = new ItemTag(item);
                        _itemTags.Add(it);
                    }
                }
            }
            //ソート
            _itemTags.Sort();

            InitList();
        }
        // TODO: Simplify this constructor once IPreferences and IRenderPrecisionPreference have been consolidated in 3.0 (DYN-1699)
        public RenderPackageFactoryViewModel(IPreferences preferenceSettings)
        {
            var ps = preferenceSettings as PreferenceSettings;

            if (ps != null)
            {
                this.factory = new HelixRenderPackageFactory()
                {
                    TessellationParameters = { ShowEdges = ps.ShowEdges, MaxTessellationDivisions = ps.RenderPrecision }
                };
            }
            else
            {
                this.factory = new HelixRenderPackageFactory()
                {
                    TessellationParameters = { ShowEdges = preferenceSettings.ShowEdges }
                };
            }
        }
Ejemplo n.º 30
0
		public ProxyDockItem (AbstractDockItemProvider provider, IPreferences prefs)
		{
			StripMnemonics = false;
			
			Provider = provider;
			Provider.ItemsChanged += HandleProviderItemsChanged;
			this.prefs = prefs;
			
			if (prefs == null) {
				currentPos = 0;
			} else {
				currentPos = prefs.Get<int> ("CurrentIndex", 0);
				
				if (CurrentPosition >= Provider.Items.Count ()) 
					CurrentPosition = 0;
			}
			
			ItemChanged ();
		}
Ejemplo n.º 31
0
        /// <summary>
        /// Creates a WebProxy object based on preference settings.
        /// </summary>
        public static WebProxy Create(IPreferences preferences)
        {
            if (preferences == null || !preferences.Get <bool>(Preference.UseProxy))
            {
                return(null);
            }

            var proxy = new WebProxy(
                preferences.Get <string>(Preference.ProxyServer),
                preferences.Get <int>(Preference.ProxyPort));

            if (preferences.Get <bool>(Preference.UseProxyAuth))
            {
                proxy.Credentials = NetworkCredentialFactory.Create(
                    preferences.Get <string>(Preference.ProxyUser),
                    preferences.Get <string>(Preference.ProxyPass));
            }
            return(proxy);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Helper function to load new custom nodes and packages.
        /// </summary>
        /// <param name="newPaths">New package paths to load custom nodes and packages from.</param>
        /// <param name="preferences">Can be a temporary local preferences object.</param>
        /// <param name="customNodeManager"></param>
        private void LoadCustomNodesAndPackagesHelper(IEnumerable <string> newPaths, IPreferences preferences,
                                                      CustomNodeManager customNodeManager)
        {
            foreach (var path in preferences.CustomPackageFolders)
            {
                // Append the definitions subdirectory for custom nodes.
                var dir = path == DynamoModel.BuiltInPackagesToken ? PathManager.BuiltinPackagesDirectory : path;
                dir = TransformPath(dir, PathManager.DefinitionsDirectoryName);

                customNodeManager.AddUninitializedCustomNodesInPath(dir, false, false);
            }
            foreach (var path in newPaths)
            {
                if (DynamoModel.IsDisabledPath(path, preferences))
                {
                    Log(string.Format(Resources.PackagesDirectorySkipped, path));
                    continue;
                }
                else
                {
                    ScanPackageDirectories(path, preferences);
                }
            }

            if (pathManager != null)
            {
                foreach (var pkg in LocalPackages)
                {
                    if (Directory.Exists(pkg.BinaryDirectory))
                    {
                        pathManager.AddResolutionPath(pkg.BinaryDirectory);
                    }
                }
            }

            if (LocalPackages.Any())
            {
                // Load only those recently addeed local packages (that are located in any of the new paths)
                var newPackages = LocalPackages.Where(x => newPaths.Any(y => x.RootDirectory.Contains(y)));
                LoadPackages(newPackages);
            }
        }
Ejemplo n.º 33
0
        protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
                                                out IPreferences preferences,
                                                string baseAddress = "",
                                                string header      = "",
                                                string path        = "",
                                                IDictionary <string, string> urlsWithResponse = null,
                                                bool readFromFile   = false,
                                                string fileContents = "",
                                                string contentType  = "")
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage();

            responseMessage.Content = new MockHttpContent(string.Empty);
            MockHttpMessageHandler messageHandler = new MockHttpMessageHandler(urlsWithResponse, header, readFromFile, fileContents, contentType);
            HttpClient             httpClient     = new HttpClient(messageHandler);

            fileSystem  = new MockedFileSystem();
            preferences = new NullPreferences();

            HttpState httpState = new HttpState(fileSystem, preferences, httpClient);

            if (!string.IsNullOrWhiteSpace(baseAddress))
            {
                httpState.BaseAddress = new Uri(baseAddress);
            }
            if (!string.IsNullOrWhiteSpace(path))
            {
                httpState.BaseAddress = new Uri(baseAddress);

                if (path != null)
                {
                    string[] pathParts = path.Split('/');

                    foreach (string pathPart in pathParts)
                    {
                        httpState.PathSections.Push(pathPart);
                    }
                }
            }

            return(httpState);
        }
Ejemplo n.º 34
0
        public DockPreferences(string dockName)
        {
            prefs = DockServices.Preferences.Get <DockPreferences> ();

            // ensures position actually gets set
            position = (DockPosition)100;

            this.Build();

            // Manually set the tooltips <shakes fist at MD...>
            window_manager_check.TooltipMarkup = Mono.Unix.Catalog.GetString(
                "When set, windows which do not already have launchers on a dock will be added to this dock.");

            icon_scale.Adjustment.SetBounds(24, 129, 1, 12, 1);
            zoom_scale.Adjustment.SetBounds(1, 4.01, .01, .1, .01);

            zoom_scale.FormatValue += delegate(object o, FormatValueArgs args) {
                args.RetVal = string.Format("{0:#}%", args.Value * 100);
            };

            name = dockName;

            BuildItemProviders();
            BuildOptions();

            Gdk.Screen.Default.CompositedChanged += HandleCompositedChanged;
            icon_scale.ValueChanged    += IconScaleValueChanged;
            zoom_scale.ValueChanged    += ZoomScaleValueChanged;
            zoom_checkbutton.Toggled   += ZoomCheckbuttonToggled;
            autohide_box.Changed       += AutohideBoxChanged;
            fade_on_hide_check.Toggled += FadeOnHideToggled;

            DefaultProvider.ItemsChanged += HandleDefaultProviderItemsChanged;

            if (FirstRun)
            {
                FirstRun = false;
            }

            ShowAll();
        }
        public WebAssemblyVersionTracking(IPreferences preferences, IAppInfo appInfo)
        {
            _preferences = preferences;
            _appInfo     = appInfo;

            IsFirstLaunchEver = !_preferences.ContainsKey(versionsKey, sharedName) || !_preferences.ContainsKey(buildsKey, sharedName);
            if (IsFirstLaunchEver)
            {
                versionTrail = new Dictionary <string, List <string> >
                {
                    { versionsKey, new List <string>() },
                    { buildsKey, new List <string>() }
                };
            }
            else
            {
                versionTrail = new Dictionary <string, List <string> >
                {
                    { versionsKey, ReadHistory(versionsKey).ToList() },
                    { buildsKey, ReadHistory(buildsKey).ToList() }
                };
            }

            IsFirstLaunchForCurrentVersion = !versionTrail[versionsKey].Contains(CurrentVersion);
            if (IsFirstLaunchForCurrentVersion)
            {
                versionTrail[versionsKey].Add(CurrentVersion);
            }

            IsFirstLaunchForCurrentBuild = !versionTrail[buildsKey].Contains(CurrentBuild);
            if (IsFirstLaunchForCurrentBuild)
            {
                versionTrail[buildsKey].Add(CurrentBuild);
            }

            if (IsFirstLaunchForCurrentVersion || IsFirstLaunchForCurrentBuild)
            {
                WriteHistory(versionsKey, versionTrail[versionsKey]);
                WriteHistory(buildsKey, versionTrail[buildsKey]);
            }
        }
Ejemplo n.º 36
0
        protected Watch3DViewModelBase(Watch3DViewModelStartupParams parameters)
        {
            model                         = parameters.Model;
            scheduler                     = parameters.Scheduler;
            preferences                   = parameters.Preferences;
            logger                        = parameters.Logger;
            engineManager                 = parameters.EngineControllerManager;
            renderPackageFactory          = parameters.RenderPackageFactory;
            viewModel                     = parameters.ViewModel;
            renderPackageFactoryViewModel = parameters.RenderPackageFactoryViewModel;

            Active = parameters.Preferences.IsBackgroundPreviewActive;
            Name   = parameters.Name;
            logger = parameters.Logger;

            RegisterEventHandlers();

            TogglePanCommand   = new DelegateCommand(TogglePan, CanTogglePan);
            ToggleOrbitCommand = new DelegateCommand(ToggleOrbit, CanToggleOrbit);
            ToggleCanNavigateBackgroundCommand = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// The DefaultWatch3DViewModel is used in contexts where a complete rendering environment
        /// cannot be established. Typically, this is machines that do not have GPUs, or do not
        /// support DirectX 10 feature levels. For most purposes, you will want to use a <see cref="HelixWatch3DViewModel"/>
        /// </summary>
        /// <param name="parameters">A Watch3DViewModelStartupParams object.</param>
        public DefaultWatch3DViewModel(Watch3DViewModelStartupParams parameters)
        {
            model         = parameters.Model;
            scheduler     = parameters.Scheduler;
            preferences   = parameters.Preferences;
            logger        = parameters.Logger;
            engineManager = parameters.EngineControllerManager;

            Name          = Resources.BackgroundPreviewDefaultName;
            isGridVisible = parameters.Preferences.IsBackgroundGridVisible;
            active        = parameters.Preferences.IsBackgroundPreviewActive;
            logger        = parameters.Logger;

            RegisterEventHandlers();

            TogglePanCommand   = new DelegateCommand(TogglePan, CanTogglePan);
            ToggleOrbitCommand = new DelegateCommand(ToggleOrbit, CanToggleOrbit);
            ToggleCanNavigateBackgroundCommand = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
            ZoomToFitCommand = new DelegateCommand(ZoomToFit, CanZoomToFit);
            CanBeActivated   = true;
        }
Ejemplo n.º 38
0
 public ServerState(
     IUser user,
     IEnumerable <IClient> clients                 = null,
     IEnumerable <IProject> projects               = null,
     IPreferences preferences                      = null,
     IEnumerable <ITag> tags                       = null,
     IEnumerable <ITask> tasks                     = null,
     IEnumerable <ITimeEntry> timeEntries          = null,
     IEnumerable <IWorkspace> workspaces           = null,
     IDictionary <long, PricingPlans> pricingPlans = null)
 {
     User         = user;
     Clients      = new HashSet <IClient>(clients ?? new IClient[0]);
     Projects     = new HashSet <IProject>(projects ?? new IProject[0]);
     Preferences  = preferences ?? new MockPreferences();
     Tags         = new HashSet <ITag>(tags ?? new ITag[0]);
     Tasks        = new HashSet <ITask>(tasks ?? new ITask[0]);
     TimeEntries  = new HashSet <ITimeEntry>(timeEntries ?? new ITimeEntry[0]);
     Workspaces   = new HashSet <IWorkspace>(workspaces ?? new IWorkspace[0]);
     PricingPlans = pricingPlans ?? new Dictionary <long, PricingPlans>();
 }
Ejemplo n.º 39
0
        private static HttpClient GetHttpClientWithPreferences(IPreferences preferences)
        {
            bool useDefaultCredentials      = preferences.GetBoolValue(WellKnownPreference.UseDefaultCredentials);
            bool proxyUseDefaultCredentials = preferences.GetBoolValue(WellKnownPreference.ProxyUseDefaultCredentials);

            if (useDefaultCredentials || proxyUseDefaultCredentials)
            {
#pragma warning disable CA2000 // Dispose objects before losing scope
                HttpClientHandler handler = new HttpClientHandler()
                {
                    UseDefaultCredentials   = useDefaultCredentials,
                    DefaultProxyCredentials = proxyUseDefaultCredentials ? CredentialCache.DefaultCredentials : null
                };

                return(new HttpClient(handler));

#pragma warning restore CA2000 // Dispose objects before losing scope
            }

            return(new HttpClient());
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:NuGetViewModel"/> class.
        /// </summary>
        public NuGetViewModel(
            INuGetGalleryDescriptor descriptor,
            IWebMatrixHost host,
            PackageSourcesViewModel packageSourcesViewModel,
            Func <Uri, string, INuGetPackageManager> packageManagerCreator,
            string destination,
            TaskScheduler scheduler)
        {
            this.Descriptor = descriptor;
            this.Host       = host;
            this.Scheduler  = scheduler;

            _packageManagerCreator        = packageManagerCreator;
            _destination                  = destination;
            _preferences                  = this.Host.GetExtensionSpecificPreferences(this.Descriptor.PreferencesStore);
            _selectedPrereleaseFilter     = LoadPrereleaseFilter();
            _includePrerelease            = (_selectedPrereleaseFilter == Resources.Prerelease_Filter_IncludePrerelease);
            PackagesToDisplayForUpdateAll = new List <PackageViewModel>();

            this.ShowDetailsPageCommand   = new RelayCommand(this.ShowDetailsPage, this.CanShowDetailsPage);
            this.ShowLicensePageCommand   = new RelayCommand(this.ShowLicensePage, this.CanShowLicensePage);
            this.ShowUninstallPageCommand = new RelayCommand(this.ShowUninstallPage, this.CanShowUninstallPage);

            this.ShowListCommand = new RelayCommand(this.ShowList, this.CanShowList);

            this.InstallCommand   = new RelayCommand(this.Install, this.CanInstall);
            this.UpdateCommand    = new RelayCommand(this.Update, this.CanUpdate);
            this.UninstallCommand = new RelayCommand(this.Uninstall, this.CanUninstall);

            this.UpdateAllCommand             = new RelayCommand(this.UpdateAll, this.CanUpdateAll);
            this.ShowLicensePageForAllCommand = new RelayCommand(this.ShowLicensePageForAll, this.CanShowLicensePageForAll);

            this.DisableCommand = new RelayCommand(this.Disable, this.CanDisable);
            this.EnableCommand  = new RelayCommand(this.Enable, this.CanEnable);

            this.DefaultActionCommand = new RelayCommand(this.DefaultAction, this.CanDefaultAction);

            // Initialize the Package Sources
            InitializePackageSources(packageSourcesViewModel);
        }
Ejemplo n.º 41
0
        protected virtual void StartDynamo(IPreferences settings = null)
        {
            var assemblyPath = Assembly.GetExecutingAssembly().Location;

            preloader = new Preloader(Path.GetDirectoryName(assemblyPath));
            preloader.Preload();

            var preloadedLibraries = new List <string>();

            GetLibrariesToPreload(preloadedLibraries);

            if (preloadedLibraries.Any())
            {
                // Only when any library needs preloading will a path resolver be
                // created, otherwise DynamoModel gets created without preloading
                // any library.
                //

                var pathResolverParams = new TestPathResolverParams()
                {
                    UserDataRootFolder   = GetUserUserDataRootFolder(),
                    CommonDataRootFolder = GetCommonDataRootFolder()
                };

                pathResolver = new TestPathResolver(pathResolverParams);
                foreach (var preloadedLibrary in preloadedLibraries.Distinct())
                {
                    pathResolver.AddPreloadLibraryPath(preloadedLibrary);
                }
            }

            this.CurrentDynamoModel = DynamoModel.Start(
                new DynamoModel.DefaultStartConfiguration()
            {
                PathResolver        = pathResolver,
                StartInTestMode     = true,
                GeometryFactoryPath = preloader.GeometryFactoryPath,
                Preferences         = settings
            });
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:NuGetViewModel"/> class.
        /// </summary>
        public NuGetViewModel(
            INuGetGalleryDescriptor descriptor,
            IWebMatrixHost host,
            PackageSourcesViewModel packageSourcesViewModel, 
            Func<Uri, string, INuGetPackageManager> packageManagerCreator, 
            string destination,
            TaskScheduler scheduler)
        {
            this.Descriptor = descriptor;
            this.Host = host;
            this.Scheduler = scheduler;

            _packageManagerCreator = packageManagerCreator;
            _destination = destination;
            _preferences = this.Host.GetExtensionSpecificPreferences(this.Descriptor.PreferencesStore);
            _selectedPrereleaseFilter = LoadPrereleaseFilter();
            _includePrerelease = (_selectedPrereleaseFilter == Resources.Prerelease_Filter_IncludePrerelease);
            PackagesToDisplayForUpdateAll = new List<PackageViewModel>();

            this.ShowDetailsPageCommand = new RelayCommand(this.ShowDetailsPage, this.CanShowDetailsPage);
            this.ShowLicensePageCommand = new RelayCommand(this.ShowLicensePage, this.CanShowLicensePage);
            this.ShowUninstallPageCommand = new RelayCommand(this.ShowUninstallPage, this.CanShowUninstallPage);

            this.ShowListCommand = new RelayCommand(this.ShowList, this.CanShowList);

            this.InstallCommand = new RelayCommand(this.Install, this.CanInstall);
            this.UpdateCommand = new RelayCommand(this.Update, this.CanUpdate);
            this.UninstallCommand = new RelayCommand(this.Uninstall, this.CanUninstall);

            this.UpdateAllCommand = new RelayCommand(this.UpdateAll, this.CanUpdateAll);
            this.ShowLicensePageForAllCommand = new RelayCommand(this.ShowLicensePageForAll, this.CanShowLicensePageForAll);

            this.DisableCommand = new RelayCommand(this.Disable, this.CanDisable);
            this.EnableCommand = new RelayCommand(this.Enable, this.CanEnable);

            this.DefaultActionCommand = new RelayCommand(this.DefaultAction, this.CanDefaultAction);

            // Initialize the Package Sources
            InitializePackageSources(packageSourcesViewModel);
        }
Ejemplo n.º 43
0
        public UserStatsDataModel(ISynchronizeInvoke synchronizeInvoke, IPreferences preferences, EocStatsScheduledTask scheduledTask)
        {
            _preferences   = preferences;
            _scheduledTask = scheduledTask;
            _mapper        = new MapperConfiguration(cfg => cfg.AddProfile <UserStatsDataModelProfile>()).CreateMapper();

            _preferences.PreferenceChanged += (s, e) =>
            {
                switch (e.Preference)
                {
                case Preference.EnableUserStats:
                    ControlsVisible = _preferences.Get <bool>(Preference.EnableUserStats);
                    if (ControlsVisible)
                    {
                        RefreshFromData();
                    }
                    break;

                case Preference.EocUserId:
                    Refresh();
                    break;
                }
            };

            _scheduledTask.Changed += (s, e) =>
            {
                switch (e.Action)
                {
                case ScheduledTaskChangedAction.Finished:
                    // scheduled task completes on thread pool, but RefreshFromData will trigger UI control updates
                    // provide the ISynchronizeInvoke instance for posting the updates back to the UI thread
                    RefreshFromData(synchronizeInvoke);
                    break;
                }
            };

            ControlsVisible = _preferences.Get <bool>(Preference.EnableUserStats);
            RefreshFromData();
        }
Ejemplo n.º 44
0
        /// <summary>
        ///     Scan the PackagesDirectory for packages and attempt to load all of them.  Beware! Fails silently for duplicates.
        /// </summary>
        public void LoadPackagesIntoDynamo(
            IPreferences preferences, LibraryServices libraryServices, DynamoLoader loader, string context,
            bool isTestMode, CustomNodeManager customNodeManager)
        {
            ScanAllPackageDirectories(preferences);

            foreach (var pkg in LocalPackages)
            {
                DynamoPathManager.Instance.AddResolutionPath(pkg.BinaryDirectory);
            }

            foreach (var pkg in LocalPackages)
            {
                pkg.LoadIntoDynamo(
                    loader,
                    AsLogger(),
                    libraryServices,
                    context,
                    isTestMode,
                    customNodeManager);
            }
        }
Ejemplo n.º 45
0
        private void InitItems()
        {
            _idToWorkPreference = new TypedHashtable <string, WorkPreference>();
            IPreferences preferences = OptionDialogPlugin.Instance.RootPreferences;
            int          y           = 8;

            for (int i = 0; i < _entries.Length; i++)
            {
                IOptionPanelExtension e = _entries[i].Extension;
                foreach (string pref_id in e.PreferenceFolderIDsToEdit)
                {
                    WorkPreference wp = _idToWorkPreference[pref_id];
                    if (wp == null)   //add entry
                    {
                        IPreferenceFolder folder = preferences.FindPreferenceFolder(pref_id);
                        if (folder == null)
                        {
                            throw new Exception(pref_id + " not found");
                        }
                        _idToWorkPreference.Add(pref_id, new WorkPreference(folder));
                    }
                }
                PanelItem item = new PanelItem(this, i, e.Icon, e.Caption);
                item.Location = new Point(3, y);
                _categoryItems.Controls.Add(item);

                y += 52;
            }

            // 項目が増えた場合はパネルにスクロールを表示させてパネル幅/フォーム幅を変更する
            // ※項目数が増えれば増えるほどフォーム自体が縦長になってしまい表示しきれない懸念がある
            // ※今後プラグインでどれだけ項目数を増やしてもスクロールを表示することで対応
            if (y > _categoryItems.ClientSize.Height)
            {
                _categoryItems.AutoScroll = true;
                _categoryItems.Width     += SystemInformation.VerticalScrollBarWidth;
                this.Width += SystemInformation.VerticalScrollBarWidth;
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Constructs DynamoAnalyticsClient with given DynamoModel
        /// </summary>
        /// <param name="dynamoModel">DynamoModel</param>
        public DynamoAnalyticsClient(DynamoModel dynamoModel)
        {
            //Set the preferences, so that we can get live value of analytics
            //reporting approved status.
            preferences = dynamoModel.PreferenceSettings;

            if (Session == null)
            {
                Session = new DynamoAnalyticsSession();
            }

            //Setup Analytics service, StabilityCookie, Heartbeat and UsageLog.
            Session.Start(dynamoModel);

            //Dynamo app version.
            var appversion = dynamoModel.AppVersion;

            product = new ProductInfo()
            {
                Name = "Dynamo", VersionString = appversion, AppVersion = dynamoModel.Version
            };
        }
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public SlaveExplorerViewModel(IMessageBoxService messageBoxService, IPreferences preferences)
        {
            _messageBoxService = messageBoxService;
            _preferences = preferences;

            _registerViewerPreferences = new RegisterViewerPreferences(preferences);

            ReadCommand = new RelayCommand(Read, CanRead);
            WriteCommand = new RelayCommand(Write, CanWrite);
            ExitCommand = new RelayCommand(Exit);
            OpenCommand = new RelayCommand(Open, CanOpen);
            SaveAsCommand = new RelayCommand(SaveAs, CanSaveAs);
            ExportToCsvCommand = new RelayCommand(ExportToCsv, CanExportToCsv);

            if (IsInDesignMode)
            {
                Registers = new ObservableCollection<SlaveExplorerRegisterViewModel>()
                {
                    new SlaveExplorerRegisterViewModel(1000, 0, _descriptionStore) { IsZeroBased = IsZeroBased },
                    new SlaveExplorerRegisterViewModel(1001, 20, _descriptionStore) { IsZeroBased = IsZeroBased },
                    new SlaveExplorerRegisterViewModel(1002, 23, _descriptionStore) { IsZeroBased = IsZeroBased },
                    new SlaveExplorerRegisterViewModel(1003, 24, _descriptionStore) { IsZeroBased = IsZeroBased },
                    new SlaveExplorerRegisterViewModel(1004, 25, _descriptionStore) { IsZeroBased = IsZeroBased },
                };
            }

            SlaveAddress = _registerViewerPreferences.SlaveAddress;
            StartingRegisterNumber = _registerViewerPreferences.StartingRegister;
            NumberOfRegisters = _registerViewerPreferences.NumberOfRegisters;

            RegisterType = _registerTypes.FirstOrDefault(rt => rt.RegisterType == _registerViewerPreferences.RegisterType);

            ModbusAdapters.ApplyPreferences(_preferences, RegisterViewerPreferences.Keys.ModbusAdapter);

            IsZeroBased = _registerViewerPreferences.IsZeroBased;

            _autoRefreshTimer.Elapsed += _autoRefreshTimer_Elapsed;
        }
Ejemplo n.º 48
0
        public EocStatsScheduledTask(IPreferences preferences, ILogger logger, IEocStatsService eocStatsService, EocStatsDataContainer dataContainer)
            : base("EOC stats")
        {
            Preferences   = preferences ?? new InMemoryPreferencesProvider();
            Logger        = logger ?? NullLogger.Instance;
            StatsService  = eocStatsService ?? throw new ArgumentNullException(nameof(eocStatsService));
            DataContainer = dataContainer ?? throw new ArgumentNullException(nameof(dataContainer));
            Interval      = CalculateInterval(DataContainer.Data.LastUpdated);
            Changed      += TaskChanged;

            Preferences.PreferenceChanged += (s, e) =>
            {
                if (e.Preference == Preference.EnableUserStats)
                {
                    bool enableUserStats = Preferences.Get <bool>(Preference.EnableUserStats);
                    if (enableUserStats)
                    {
                        Start();
                    }
                    else
                    {
                        Stop();
                    }
                }
            };

            if (Preferences.Get <bool>(Preference.EnableUserStats))
            {
                if (TimeForNextUpdate(DataContainer.Data.LastUpdated))
                {
                    Run();
                }
                else
                {
                    Start();
                }
            }
        }
Ejemplo n.º 49
0
        protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
                                                out IPreferences preferences,
                                                string baseAddress = "",
                                                string header      = "",
                                                string path        = "",
                                                IDictionary <string, string> urlsWithResponse = null,
                                                bool readFromFile   = false,
                                                string fileContents = "",
                                                string contentType  = "")
        {
            fileSystem  = new MockedFileSystem();
            preferences = new NullPreferences();

            return(GetHttpStateWithOptional(ref fileSystem,
                                            ref preferences,
                                            baseAddress,
                                            header,
                                            path,
                                            urlsWithResponse,
                                            readFromFile,
                                            fileContents,
                                            contentType));
        }
Ejemplo n.º 50
0
        internal void DoCachedPackageUninstalls(IPreferences preferences)
        {
            // this can only be run once per app run
            if (hasAttemptedUninstall)
            {
                return;
            }
            hasAttemptedUninstall = true;

            var pkgDirsRemoved = new HashSet <string>();

            foreach (var pkgNameDirTup in preferences.PackageDirectoriesToUninstall)
            {
                if (pkgNameDirTup.StartsWith(PathManager.BuiltinPackagesDirectory))
                {
                    // do not delete packages from the built in dir
                    continue;
                }

                try
                {
                    Directory.Delete(pkgNameDirTup, true);
                    pkgDirsRemoved.Add(pkgNameDirTup);
                    Log(String.Format("Successfully uninstalled package from \"{0}\"", pkgNameDirTup));
                }
                catch
                {
                    Log(
                        String.Format(
                            "Failed to delete package directory at \"{0}\", you may need to delete the directory manually.",
                            pkgNameDirTup),
                        WarningLevel.Moderate);
                }
            }

            preferences.PackageDirectoriesToUninstall.RemoveAll(pkgDirsRemoved.Contains);
        }
Ejemplo n.º 51
0
        private void ScanPackageDirectories(string root, IPreferences preferences)
        {
            try
            {
                if (!Directory.Exists(root))
                {
                    string extension = null;
                    if (root != null)
                    {
                        extension = Path.GetExtension(root);
                    }

                    // If the path has a .dll or .ds extension it is a locally imported library
                    // so do not output an error about the directory
                    if (extension == ".dll" || extension == ".ds")
                    {
                        return;
                    }

                    this.Log(string.Format(Resources.InvalidPackageFolderWarning, root));
                    return;
                }

                foreach (var dir in
                         Directory.EnumerateDirectories(root, "*", SearchOption.TopDirectoryOnly))
                {
                    var pkg = ScanPackageDirectory(dir);
                    if (pkg != null && preferences.PackageDirectoriesToUninstall.Contains(dir))
                    {
                        pkg.MarkForUninstall(preferences);
                    }
                }
            }
            catch (UnauthorizedAccessException ex) { }
            catch (IOException ex) { }
            catch (ArgumentException ex) { }
        }
Ejemplo n.º 52
0
        public NuGetService(
            ICacheService cacheProvider,
            IHttpHandlerService httpHandlerService,
            IPreferences preferences,
            IVersionTracking versionTracking,
            IConnectivity connectivity,
            IFileSystem fileSystem,
            ILogger logger)
        {
            _cache  = cacheProvider ?? throw new ArgumentNullException(nameof(cacheProvider));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            _preferences     = preferences;
            _versionTracking = versionTracking;
            _connectivity    = connectivity;

            _httpClient = new HttpClient(httpHandlerService.GetNativeHandler());

            var dbPath = Path.Combine(fileSystem.AppDataDirectory, "nugets.db");

            _db = new LiteDatabase($"Filename={dbPath};Upgrade=true;");
            _db.Pragma("UTC_DATE", true);

            _packageSourceRepo = new EntityRepository <PackageSource>(_db, TimeSpan.FromDays(7), _connectivity);
            _favouriteRepo     = new EntityRepository <FavouritePackage>(_db, TimeSpan.MaxValue, _connectivity);
            _recentRepo        = new EntityRepository <RecentPackage>(_db, TimeSpan.MaxValue, _connectivity);

            _retryPolicy =
                Policy.Handle <WebException>()
                .Or <HttpRequestException>()
                .WaitAndRetryAsync
                (
                    retryCount: 2,
                    sleepDurationProvider: retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))
                );
        }
Ejemplo n.º 53
0
        public ProxyDockItem(AbstractDockItemProvider provider, IPreferences prefs)
        {
            StripMnemonics = false;

            Provider = provider;
            Provider.ItemsChanged += HandleProviderItemsChanged;
            this.prefs             = prefs;

            if (prefs == null)
            {
                currentPos = 0;
            }
            else
            {
                currentPos = prefs.Get <int> ("CurrentIndex", 0);

                if (CurrentPosition >= Provider.Items.Count())
                {
                    CurrentPosition = 0;
                }
            }

            ItemChanged();
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Starts the client when DynamoModel is created. This method initializes
        /// the Analytics service and application life cycle start is tracked.
        /// </summary>
        /// <param name="model"></param>
        public void Start(DynamoModel dynamoModel)
        {
            //Set the preferences, so that we can get live value of analytics
            //reporting approved status.
            preferences = dynamoModel.PreferenceSettings;

            if (Session == null)
            {
                Session = new DynamoAnalyticsSession();
            }

            //Setup Analytics service, StabilityCookie, Heartbeat and UsageLog.
            Session.Start(dynamoModel);

            //Dynamo app version.
            var appversion = dynamoModel.AppVersion;

            //If not ReportingAnalytics, then set the idle time as infinite so idle state is not recorded.
            Service.StartUp(new ProductInfo()
            {
                Name = "Dynamo", VersionString = appversion
            },
                            new UserInfo(Session.UserId), ReportingAnalytics ? TimeSpan.FromMinutes(30) : TimeSpan.MaxValue);
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Constructs DynamoAnalyticsClient with given DynamoModel
        /// </summary>
        /// <param name="dynamoModel">DynamoModel</param>
        public DynamoAnalyticsClient(DynamoModel dynamoModel)
        {
            //Set the preferences, so that we can get live value of analytics
            //reporting approved status.
            preferences = dynamoModel.PreferenceSettings;

            if (Session == null)
            {
                Session = new DynamoAnalyticsSession();
            }

            //Setup Analytics service, and StabilityCookie.
            Session.Start(dynamoModel);

            //Dynamo app version.
            var appversion = dynamoModel.AppVersion;

            var hostName = string.IsNullOrEmpty(dynamoModel.HostName) ? "Dynamo" : dynamoModel.HostName;

            hostInfo = new HostContextInfo()
            {
                ParentId = dynamoModel.HostAnalyticsInfo.ParentId, SessionId = dynamoModel.HostAnalyticsInfo.SessionId
            };

            string buildId = String.Empty, releaseId = String.Empty;

            if (Version.TryParse(dynamoModel.Version, out Version version))
            {
                buildId   = $"{version.Major}.{version.Minor}.{version.Build}"; // BuildId has the following format major.minor.build, ex: 2.5.1
                releaseId = $"{version.Major}.{version.Minor}.0";               // ReleaseId has the following format: major.minor.0; ex: 2.5.0
            }
            product = new ProductInfo()
            {
                Id = "DYN", Name = hostName, VersionString = appversion, AppVersion = appversion, BuildId = buildId, ReleaseId = releaseId
            };
        }
Ejemplo n.º 56
0
        /// <summary>
        /// The DefaultWatch3DViewModel is used in contexts where a complete rendering environment
        /// cannot be established. Typically, this is machines that do not have GPUs, or do not
        /// support DirectX 10 feature levels. For most purposes, you will want to use a <see cref="HelixWatch3DViewModel"/>
        /// </summary>
        /// <param name="parameters">A Watch3DViewModelStartupParams object.</param>
        public DefaultWatch3DViewModel(Watch3DViewModelStartupParams parameters)
        {
            model = parameters.Model;
            scheduler = parameters.Scheduler;
            preferences = parameters.Preferences;
            logger = parameters.Logger;
            engineManager = parameters.EngineControllerManager;

            Name = Resources.BackgroundPreviewDefaultName;
            isGridVisible = parameters.Preferences.IsBackgroundGridVisible;
            logger = parameters.Logger;

            RegisterEventHandlers();

            TogglePanCommand = new DelegateCommand(TogglePan, CanTogglePan);
            ToggleOrbitCommand = new DelegateCommand(ToggleOrbit, CanToggleOrbit);
            ToggleCanNavigateBackgroundCommand = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
            ZoomToFitCommand = new DelegateCommand(ZoomToFit, CanZoomToFit);
            CanBeActivated = true;
        }
Ejemplo n.º 57
0
        private static void InitializePreferences(IPreferences preferences)
        {
            BaseUnit.NumberFormat = preferences.NumberFormat;

            var settings = preferences as PreferenceSettings;
            if (settings != null)
            {
                settings.InitializeNamespacesToExcludeFromLibrary();
            }
        }
Ejemplo n.º 58
0
        private IPreferences CreateOrLoadPreferences(IPreferences preferences)
        {
            if (preferences != null) // If there is preference settings provided...
                return preferences;

            // Is order for test cases not to interfere with the regular preference
            // settings xml file, a test case usually specify a temporary xml file
            // path from where preference settings are to be loaded. If that value
            // is not set, then fall back to the file path specified in PathManager.
            //
            var xmlFilePath = PreferenceSettings.DynamoTestPath;
            if (string.IsNullOrEmpty(xmlFilePath))
                xmlFilePath = pathManager.PreferenceFilePath;

            if (File.Exists(xmlFilePath))
            {
                // If the specified xml file path exists, load it.
                return PreferenceSettings.Load(xmlFilePath);
            }

            // Otherwise make a default preference settings object.
            return new PreferenceSettings();
        }
Ejemplo n.º 59
0
        private void InitializeNodeLibrary(IPreferences preferences)
        {
            // Initialize all nodes inside of this assembly.
            InitializeIncludedNodes();

            List<TypeLoadData> modelTypes;
            List<TypeLoadData> migrationTypes;
            Loader.LoadNodeModelsAndMigrations(pathManager.NodeDirectories,
                Context, out modelTypes, out migrationTypes);

            // Load NodeModels
            foreach (var type in modelTypes)
            {
                // Protect ourselves from exceptions thrown by malformed third party nodes.
                try
                {
                    NodeFactory.AddTypeFactoryAndLoader(type.Type);
                    NodeFactory.AddAlsoKnownAs(type.Type, type.AlsoKnownAs);
                    AddNodeTypeToSearch(type);
                }
                catch (Exception e)
                {
                    Logger.Log(e);
                }
            }

            // Load migrations
            foreach (var type in migrationTypes)
                MigrationManager.AddMigrationType(type);

            // Import Zero Touch libs
            var functionGroups = LibraryServices.GetAllFunctionGroups();
            if (!IsTestMode)
                AddZeroTouchNodesToSearch(functionGroups);
#if DEBUG_LIBRARY
            DumpLibrarySnapshot(functionGroups);
#endif

            // Load local custom nodes
            foreach (var directory in pathManager.DefinitionDirectories)
                CustomNodeManager.AddUninitializedCustomNodesInPath(directory, IsTestMode);
            CustomNodeManager.AddUninitializedCustomNodesInPath(pathManager.CommonDefinitions, IsTestMode);
        }
Ejemplo n.º 60
0
        protected Watch3DViewModelBase(Watch3DViewModelStartupParams parameters)
        {
            model = parameters.Model;
            scheduler = parameters.Scheduler;
            preferences = parameters.Preferences;
            logger = parameters.Logger;
            engineManager = parameters.EngineControllerManager;
            renderPackageFactory = parameters.RenderPackageFactory;
            viewModel = parameters.ViewModel;
            renderPackageFactoryViewModel = parameters.RenderPackageFactoryViewModel;

            Active = parameters.Preferences.IsBackgroundPreviewActive;
            Name = parameters.Name;
            logger = parameters.Logger;

            RegisterEventHandlers();

            TogglePanCommand = new DelegateCommand(TogglePan, CanTogglePan);
            ToggleOrbitCommand = new DelegateCommand(ToggleOrbit, CanToggleOrbit);
            ToggleCanNavigateBackgroundCommand = new DelegateCommand(ToggleCanNavigateBackground, CanToggleCanNavigateBackground);
        }