Ejemplo n.º 1
0
        public void Start(IScene scene)
        {
            m_scene = scene;

            m_dataStore = m_scene.Simian.GetAppModule<IDataStore>();
            if (m_dataStore == null)
            {
                m_log.Error("LLPrimitiveLoader requires an IDataStore");
                return;
            }

            m_primMesher = m_scene.GetSceneModule<IPrimMesher>();
            if (m_primMesher == null)
            {
                m_log.Error("LLPrimitiveLoader requires an IPrimMesher");
                return;
            }

            m_writeQueue = new ThrottledQueue<UUID, PrimSerialization>(5, 1000 * 30, true, SerializationHandler);
            m_writeQueue.Start();

            m_scene.OnEntityAddOrUpdate += EntityAddOrUpdateHandler;
            m_scene.OnEntityRemove += EntityRemoveHandler;

            Deserialize();
        }
Ejemplo n.º 2
0
 public ObjectStore(IDataStore dataStore, ISerializer serializer)
 {
     DataStore = dataStore;
     Serializer = serializer;
     CacheObjects = true;
     RemoveBadData = true;
 }
        /// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <param name="datastore">datastore to use </param>
        /// <returns></returns>
        public static PlusService AuthenticateOauth(string clientId, string clientSecret, string userName, IDataStore datastore)
        {

            string[] scopes = new string[] { PlusService.Scope.PlusLogin,  // know your basic profile info and your circles
                                             PlusService.Scope.PlusMe,  // Know who you are on google
                                             PlusService.Scope.UserinfoEmail,   // view your email address
                                             PlusService.Scope.UserinfoProfile};     // view your basic profile info.

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , datastore).Result;

                PlusService service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Authentication Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }
        public void Establish_Context()
        {
            _dataStore = MockRepository.GenerateMock<IDataStore>();
            _repository = new TodoListRepository(_dataStore);

            _repository.Add(new TodoListItem());
        }
 public void init()
 {
     _request = new HttpRequestMessage()
     {
         Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
     };
     _controller = new RecordsController
     {
         Request = _request
     };
     MockRepository repo = new MockRepository();
     _mockDataStore = repo.Stub<IDataStore>();
     SetupResult.For(_mockDataStore.GetRecords()).Return(
         new List<RecordDetail>{
             new RecordDetail
     {
         DateOfBirth = new DateTime(2000, 1, 1),
         FavColor = "Black",
         Gender = "Male",
         FirstName = "test",
         LastName = "testL"
     },new RecordDetail
     {
         DateOfBirth = new DateTime(2001, 1, 1),
         FavColor = "Blue",
         Gender = "Female",
         FirstName = "test",
         LastName = "lasttest"
     }
         }
         );
 }
Ejemplo n.º 6
0
 public StoresViewModel(Page page) : base(page)
 {
     Title = "Locations";
     dataStore = DependencyService.Get<IDataStore>();
     Stores = new ObservableRangeCollection<Store>();
     StoresGrouped = new ObservableRangeCollection<Grouping<string, Store>>();
 }
Ejemplo n.º 7
0
        public AzureProfile(IDataStore store, string profilePath)
        {
            this.store = store;
            this.profilePath = profilePath;

            Load();
        }
Ejemplo n.º 8
0
 public static byte[] LoadDataStoreItemData(string domain, string fileLink, IDataStore storage)
 {
     using (var stream = storage.GetReadStream(domain, fileLink))
     {
         return stream.GetCorrectBuffer();
     }
 }
Ejemplo n.º 9
0
        public BTCMarketsExchange(IDataStore _dataStore, ICurrencyPairRepository _currencyPairRepository)
        {
            wallets = new List<CurrencyWallet>();
            pairsToUpdate = new List<BTCMarketsCurrencyWalletPair>();
            syntheticPairsToUpdate = new List<BTCMarketsSyntheticCurrencyWalletPair>();

            dataStore = _dataStore;
            var btcWallet = new FixedFeeCurrencyWallet(0.001M,0.001M, CurrencyType.Bitcoin , this);
            var ltcWallet = new FixedFeeCurrencyWallet(0.01M, 0.01M, CurrencyType.Litecoin, this);
            var audWallet = new PercentageFeeCurrencyWallet(0.01M, 0.015M, CurrencyType.AUD, this);

            wallets.Add(btcWallet);
            wallets.Add(ltcWallet);
            wallets.Add(audWallet);

            var btcusd = new BTCMarketsCurrencyWalletPair(btcWallet, audWallet, _dataStore, "https://api.btcmarkets.net/market/BTC/AUD/tick");
            var ltcusd = new BTCMarketsCurrencyWalletPair(ltcWallet, audWallet, _dataStore, "https://api.btcmarkets.net/market/LTC/AUD/tick");
            var btcltc = new BTCMarketsSyntheticCurrencyWalletPair(btcWallet, ltcWallet, _dataStore, "https://api.btcmarkets.net/market/BTC/AUD/tick", "https://api.btcmarkets.net/market/LTC/AUD/tick");

            pairsToUpdate.Add(btcusd);
            pairsToUpdate.Add(ltcusd);
            syntheticPairsToUpdate.Add(btcltc);

            _currencyPairRepository.Store(btcusd);
            _currencyPairRepository.Store(ltcusd);
            _currencyPairRepository.Store(btcltc);
        }
Ejemplo n.º 10
0
    void MainPage_Loaded( object sender, RoutedEventArgs e )
    {
      if( string.IsNullOrEmpty( Defaults.APPLICATION_ID ) || string.IsNullOrEmpty( Defaults.SECRET_KEY ) ||
          string.IsNullOrEmpty( Defaults.VERSION ) )
      {
        NavigationService.Navigate( new Uri( "/ErrorPage.xaml", UriKind.Relative ) ); 
        return;
      }

      Backendless.InitApp( Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION );
      DataStore = Backendless.Persistence.Of<ToDoEntity>();

      EntitiesDataGrid.DataContext = _toDoList;
      _toDoList.CollectionChanged +=
        ( senderObj, args ) => Footer.Visibility = _toDoList.Count == 0 ? Visibility.Collapsed : Visibility.Visible;

      AsyncStartedEvent += () =>
      {
        ProgressBar.Visibility = Visibility.Visible;
        ContentPanel.Opacity = 0.1;
      };
      AsyncFinishedEvent += () =>
      {
        ProgressBar.Visibility = Visibility.Collapsed;
        ContentPanel.Opacity = 1;
      };

      AsyncStartedEvent.Invoke();
      DataStore.Find( new AsyncCallback<BackendlessCollection<ToDoEntity>>( response => Dispatcher.BeginInvoke( () =>
      {
        _toDoList.AddAll( response.GetCurrentPage() );
        AsyncFinishedEvent.Invoke();
      } ), fault => Dispatcher.BeginInvoke( () => AsyncFinishedEvent.Invoke() ) ) );
    }
Ejemplo n.º 11
0
 public ExceptionStateMachine(IWorkItemRepository repository, IDataStore dataStore,
     IWorkflowPathNavigator navigator)
 {
     _repository = repository;
     _dataStore = dataStore;
     _navigator = navigator;
 }
 public AsyncImageLoaderService(IDataStore dataStore)
 {
     _dataStore = dataStore;
     _dispatcherTimer.Interval = TimeSpan.FromMilliseconds(10);
     _dispatcherTimer.Start();
     _dispatcherTimer.Tick += DispatcherTimerOnTick;
 }
Ejemplo n.º 13
0
		public FeedbackListViewModel (Page page) : base(page)
		{
			Title = "Feedback";
			dataStore = DependencyService.Get<IDataStore> ();
			Feedbacks = new ObservableCollection<Feedback> ();
			FeedbacksGrouped = new ObservableCollection<Grouping<string, Feedback>> ();
		}
Ejemplo n.º 14
0
        public MultiDataStoreProxy(IDataStore dataStore, string connectionString,XPDictionary dictionary=null) : base(dataStore){
            if (dictionary==null)
                dictionary=XpandModuleBase.Dictiorary;

            _dataStoreManager = new DataStoreManager(connectionString);
            FillDictionaries(dictionary);
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Test constructor.
 /// </summary>
 /// <param name="httpContext"></param>
 /// <param name="container"></param>
 /// <param name="dataStore"></param>
 /// <param name="helpContentManager"></param>
 internal HttpModule(HttpContextBase httpContext, IContainer container, IDataStore dataStore, IHelpContentManager helpContentManager)
 {
     _httpContext = httpContext;
     _container = container;
     _dataStore = dataStore;
     _helpContentManager = helpContentManager;
 }
Ejemplo n.º 16
0
        ///<summary>
        /// Copy from one module to another. Can copy from s3 to disk and vice versa
        ///</summary>
        ///<param name="srcStore"></param>
        ///<param name="srcDomain"></param>
        ///<param name="srcFilename"></param>
        ///<param name="dstStore"></param>
        ///<param name="dstDomain"></param>
        ///<param name="dstFilename"></param>
        ///<returns></returns>
        ///<exception cref="ArgumentNullException"></exception>
        public static Uri CrossCopy(IDataStore srcStore, string srcDomain, string srcFilename, IDataStore dstStore,
                                    string dstDomain, string dstFilename)
        {
            if (srcStore == null) throw new ArgumentNullException("srcStore");
            if (srcDomain == null) throw new ArgumentNullException("srcDomain");
            if (srcFilename == null) throw new ArgumentNullException("srcFilename");
            if (dstStore == null) throw new ArgumentNullException("dstStore");
            if (dstDomain == null) throw new ArgumentNullException("dstDomain");
            if (dstFilename == null) throw new ArgumentNullException("dstFilename");
            //Read contents
            using (Stream srcStream = srcStore.GetReadStream(srcDomain, srcFilename))
            {
                using (var memoryStream = TempStream.Create())
                {
                    //Copy
                    var buffer = new byte[4096];
                    int readed;
                    while ((readed = srcStream.Read(buffer, 0, 4096)) != 0)
                    {
                        memoryStream.Write(buffer, 0, readed);
                    }

                    memoryStream.Position = 0;
                    return dstStore.Save(dstDomain, dstFilename, memoryStream);
                }
            }
        }
Ejemplo n.º 17
0
        public QueueProcessor(Logger log, IDataStore dataStore, IHubContext<IMatchmakingClient> hub, ITracker tracker, IMatchEvaluator matchBuilder, CircularBuffer<TimeSpan> timeToMatch)
        {
            _log = log;
            _dataStore = dataStore;
            _hub = hub;
            _tracker = tracker;
            _matchBuilder = matchBuilder;
            _timeToMatch = timeToMatch;

            _queueSleepMin = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepMin") );
            _queueSleepMax = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepMax") );
            _queueSleepLength = Int32.Parse( CloudConfigurationManager.GetSetting("QueueSleepLength") );

            Task.Run( async () =>
            {
                _log.Info("Running QueueProcessor...");

                while( true )
                {
                    var sleepTime = _queueSleepMax;

                    try
                    {
                        await processQueue();
                        sleepTime = _queueSleepMax - (_dataStore.DocumentDbPopulation * (_queueSleepMax/_queueSleepLength));
                    }
                    catch(Exception ex)
                    {
                        _log.Error(ex);
                    }

                    Thread.Sleep(sleepTime < _queueSleepMin ? _queueSleepMin : sleepTime);
                }
            });
        }
Ejemplo n.º 18
0
 public void Setup()
 {
     _db = new JsonStore<EventDescriptor>();
       _db.DeleteAll();
       _serializer= new JsonSerializer();
       _sut = new Store( _db, _serializer);
 }
Ejemplo n.º 19
0
		public FeedbackViewModel (Page page) : base (page)
		{
			
			this.dataStore = DependencyService.Get<IDataStore> ();
			this.Title = "Leave Feedback";
			StoreName = string.Empty;
		}
Ejemplo n.º 20
0
		public static void InvokeDatabaseExported(IDataStore db)
		{
			if (OnDatabaseExported != null)
			{
				OnDatabaseExported.Invoke(new DatabaseExportedEventArgs(db));
			}
		}
Ejemplo n.º 21
0
        /// <summary>
        /// Handles the provided data store as part of the batch.
        /// </summary>
        /// <param name="store">The data store being handled as part of the batch.</param>
        public static void Handle(IDataStore store)
        {
            using (LogGroup logGroup = LogGroup.Start("Adding a data store to the batch.", LogLevel.Debug))
            {
                LogWriter.Debug("Batch stack: " + BatchState.Batches.Count.ToString());

                if (BatchState.IsRunning)
                {
                    Stack<Batch> batches = BatchState.Batches;

                    // Get the position of the outermost batch
                    // The stack is reversed so the last position is the outermost batch
                    int outerPosition = batches.Count-1;

                    // Get the outermost batch and add the data store to it
                    Batch batch = batches.ToArray()[outerPosition];

                    if (!batch.DataStores.Contains(store))
                    {
                        LogWriter.Debug("Data store added.");
                        batch.DataStores.Add(store);

                        // Commit the batch stack to state
                        Batches = batches;
                    }
                    else
                    {
                        LogWriter.Debug("Data store already found. Not added.");
                    }
                }
                else
                    throw new InvalidOperationException("No batch running. Use Batch.IsRunning to check before calling this method.");
            }
        }
Ejemplo n.º 22
0
 public void Initialize(IDataStoreManager dataStoreManager)
 {
     variableTypeStore = dataStoreManager.Get("ConjugationTypes");
     variableStore = dataStoreManager.Get("Variables");
     irregularStore = dataStoreManager.Get("Irregulars");
     conjugator = new Conjugator(irregularStore);
 }
Ejemplo n.º 23
0
        public HomeModule(IDataStore dataStore) {
            Get["/"] = _ => {
                var model = this.GetDefaultModel<StartContent>();
                model.Page.Title = "Start";

                using (var session = dataStore.DocumentStore.OpenSession()) {
                    session.Store(new Member() { Id = Guid.NewGuid(), Firstname = "Test", Lastname = "Last", Email = "*****@*****.**" });
                    session.SaveChanges();
                }

                using (var session = dataStore.DocumentStore.OpenSession()) {
                    var content = new StartContent();
                    content.Members = session.Query<Member>().ToList();
                    model.Content = content;
                }

                return View["start.cshtml", model];
            };

            Get["/cleanup"] = _ => {
                var model = this.GetDefaultModel<StartContent>();
                model.Page.Title = "Cleanup";

                using (var session = dataStore.DocumentStore.OpenSession()) {
                    //dataStore.DocumentStore.DatabaseCommands.DeleteByIndex
                    //session.SaveChanges();
                }

                return View["start.cshtml", model];
            };

            Get["/error"] = _ => { throw new NotImplementedException(); };
        }
Ejemplo n.º 24
0
        public void GenerateStat(IDataStore data)
        {
            Velocity.Init();

            var menu = PageBuilders.Select(x => new
            {
                url = x.PageTemplate,
                name = x.PageName
            });
            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            version = version.Substring(0, version.LastIndexOf('.'));

            foreach (var builder in PageBuilders)
            {
                if (builder.TargetDir == null)
                {
                    builder.TargetDir = TargetDir;
                }

                VelocityContext context = new VelocityContext();
                context.Put("menu", menu);
                context.Put("version", version);
                using (var s = data.OpenSession())
                {
                    foreach (var obj in builder.BuildData(s))
                    {
                        context.Put(obj.Key, obj.Value);
                    }
                }

                using (MemoryStream pageContent = new MemoryStream())
                using (TextWriter writer = new StreamWriter(pageContent))
                {
                    Velocity.MergeTemplate(
                        TemplateDir + "/" + builder.PageTemplate,
                        Encoding.UTF8.WebName,
                        context,
                        writer
                    );
                    writer.Flush();

                    pageContent.Seek(0, SeekOrigin.Begin);
                    context.Put("content", new StreamReader(pageContent).ReadToEnd());
                    using (TextWriter writer2 = new StreamWriter(OutputDir + "/" + builder.PageTemplate))
                    {
                        Velocity.MergeTemplate(
                            TemplateDir + "/" + SharedPageTemplate,
                            Encoding.UTF8.WebName,
                            context,
                            writer2
                        );
                    }
                }
            }
            foreach (var fileToCopy in FilesToCopy)
            {
                File.Copy(TemplateDir + "/" + fileToCopy, OutputDir + "/" + fileToCopy, true);
            }
        }
Ejemplo n.º 25
0
        public ActivityRunnerTests()
        {
            _dataStore = Substitute.For<IDataStore>();
            _repository = Substitute.For<IWorkItemRepository>();
            _workflowPathNavigator = Substitute.For<IWorkflowPathNavigator>();

            _activityRunner = new ActivityRunner(_workflowPathNavigator, _dataStore, _repository);
        }
Ejemplo n.º 26
0
        public void Initialize(IDataStoreManager dataStoreManager)
        {
            quotesDataStore = dataStoreManager.Get("Quotes");

            variableHandler.DefineMagicVariable("quote",
                                                msg =>
                                                GetRandomQuoteFromAnyUser());
        }
Ejemplo n.º 27
0
 public ExportForm(IDataStore dataStore)
 {
     _dataStore = dataStore;
     InitializeComponent();
     var now = DateTime.Now;
     dateTimeRangePicker.From = now;
     dateTimeRangePicker.To = now;
 }
        /// <summary>
        /// Creates a new instance of the Publish Exclusions Repository
        /// </summary>
        /// <param name="dataProvider">Publish Exclusions data provider</param>
        /// <param name="dataStore">Publish Exclusions data store</param>
        public PublishExclusionsRepository(IPublishExclusionsProvider<IDatabaseConnection> dataProvider, IDataStore<IDatabaseConnection> dataStore)
        {
            Condition.Requires<IPublishExclusionsProvider<IDatabaseConnection>>(dataProvider, "dataProvider").IsNotNull<IPublishExclusionsProvider<IDatabaseConnection>>();
            Condition.Requires<IDataStore<IDatabaseConnection>>(dataStore, "dataStore").IsNotNull<IDataStore<IDatabaseConnection>>();

            _dataStore = dataStore;
            _dataProvider = dataProvider;
        }
Ejemplo n.º 29
0
 public LinqToSqlOrmFramework(IDataStore dataStore, RequestContext context)
     : base(context.Zeus.Output)
 {
     this._dataStore = dataStore;
     this._context = context;
     this._database = context.Database;
     this._dialog = context.Dialog;
 }
 public ExceptionStateMachineTests()
 {
     _dataStore = Substitute.For<IDataStore>();
     _workItemRepo = new InMemoryWorkItemRepository();
     _navigator = Substitute.For<IWorkflowPathNavigator>();
     _engine = Substitute.For<IEngine>();
     _stateMachine = new ExceptionStateMachine(_workItemRepo, _dataStore, _navigator);
 }
 partial void OnGetUserDataStore(ref IDataStore <Authentication.Entities.UserEntity> result);
Ejemplo n.º 32
0
 /// <summary>
 /// Gets a query provider
 /// </summary>
 /// <param name="dStore">the datastore to attach it to</param>
 /// <returns></returns>
 public IQueryProvider GetQueryProvider(IDataStore dStore)
 {
     return(new TSqlQueryProvider(dStore));
 }
Ejemplo n.º 33
0
 public ImpostersAsMockConfiguration(Imposter[] imposters,
                                     IDataStore dataStore)
 {
     Imposters = imposters;
     DataStore = dataStore;
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Instantiates a Property object by reading metadata about
        /// the given property.
        /// </summary>
        /// <param name="obj">The object reference used to fetch the current value of the property.</param>
        /// <param name="metadata">Property metadata.</param>
        public Property(object obj, PropertyInfo metadata)
        {
            IModel model = obj as IModel;

            ID   = Guid.NewGuid();
            Name = metadata.GetCustomAttribute <DescriptionAttribute>()?.ToString();
            if (string.IsNullOrEmpty(Name))
            {
                Name = metadata.Name;
            }

            Tooltip    = metadata.GetCustomAttribute <TooltipAttribute>()?.Tooltip;
            Separators = metadata.GetCustomAttributes <SeparatorAttribute>()?.Select(s => s.ToString())?.ToList();

            Value = metadata.GetValue(obj);
            if (metadata.PropertyType == typeof(DateTime) || (metadata.PropertyType == typeof(DateTime?) && Value != null))
            {
                // Note: ToShortDateString() uses the current culture, which is what we want in this case.
                Value = ((DateTime)Value).ToShortDateString();
            }
            // ?else if property type isn't a struct?
            else if (Value != null && typeof(IModel).IsAssignableFrom(Value.GetType()))
            {
                Value = ((IModel)Value).Name;
            }
            else if (metadata.PropertyType.IsEnum)
            {
                Value = VariableProperty.GetEnumDescription((Enum)Enum.Parse(metadata.PropertyType, Value?.ToString()));
            }
            else if (metadata.PropertyType != typeof(bool) && metadata.PropertyType != typeof(System.Drawing.Color))
            {
                Value = ReflectionUtilities.ObjectToString(Value, CultureInfo.CurrentCulture);
            }

            // fixme - need to fix this unmaintainable mess brought across from the old PropertyPresenter
            DisplayAttribute attrib      = metadata.GetCustomAttribute <DisplayAttribute>();
            DisplayType      displayType = attrib?.Type ?? DisplayType.None;

            // For compatibility with the old PropertyPresenter, assume a default of
            // DisplayType.DropDown if the Values property is specified.
            if (displayType == DisplayType.None && !string.IsNullOrEmpty(attrib?.Values))
            {
                displayType = DisplayType.DropDown;
            }

            if (attrib != null && !string.IsNullOrEmpty(attrib.VisibleCallback))
            {
                BindingFlags flags  = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
                MethodInfo   method = metadata.DeclaringType.GetMethod(attrib.VisibleCallback, flags);
                if (method == null)
                {
                    // Try a property with this name.
                    PropertyInfo visibleProperty = metadata.DeclaringType.GetProperty(attrib.VisibleCallback, flags);
                    if (visibleProperty == null)
                    {
                        throw new InvalidOperationException($"Unable to evaluate visible callback {attrib.VisibleCallback} for property {metadata.Name} on type {metadata.DeclaringType.FullName} - method or property does not exist");
                    }

                    if (visibleProperty.PropertyType != typeof(bool))
                    {
                        throw new InvalidOperationException($"Property {visibleProperty.Name} is not a valid enabled callback, because it has a return type of {visibleProperty.PropertyType}. It should have a bool return type.");
                    }
                    if (!visibleProperty.CanRead)
                    {
                        throw new InvalidOperationException($"Property {visibleProperty.Name} is not a valid enabled callback, because it does not have a get accessor.");
                    }

                    Visible = (bool)visibleProperty.GetValue(obj);
                }
                else
                {
                    if (method.ReturnType != typeof(bool))
                    {
                        throw new InvalidOperationException($"Method {metadata.Name} is not a valid enabled callback, because it has a return type of {method.ReturnType}. It should have a bool return type.");
                    }
                    ParameterInfo[]      parameters            = method.GetParameters();
                    List <ParameterInfo> nonOptionalParameters = parameters.Where(p => !p.IsOptional).ToList();
                    if (nonOptionalParameters.Count != 0)
                    {
                        throw new InvalidOperationException($"Method {metadata.Name} is not a valid enabled callback, because it takes {nonOptionalParameters.Count} non-optional arguments ({string.Join(", ", nonOptionalParameters.Select(p => p.Name))}). It should take 0 arguments");
                    }

                    Visible = (bool)method.Invoke(obj, null);
                }
            }
            else
            {
                Visible = true;
            }

            if (attrib != null && !string.IsNullOrEmpty(attrib.EnabledCallback))
            {
                BindingFlags flags  = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
                MethodInfo   method = metadata.DeclaringType.GetMethod(attrib.EnabledCallback, flags);
                if (method == null)
                {
                    // Try a property with this name.
                    PropertyInfo enabledProperty = metadata.DeclaringType.GetProperty(attrib.EnabledCallback, flags);
                    if (enabledProperty == null)
                    {
                        throw new InvalidOperationException($"Unable to evaluate enabled callback {attrib.EnabledCallback} for property {metadata.Name} on type {metadata.DeclaringType.FullName} - method or property does not exist");
                    }

                    if (enabledProperty.PropertyType != typeof(bool))
                    {
                        throw new InvalidOperationException($"Property {enabledProperty.Name} is not a valid enabled callback, because it has a return type of {enabledProperty.PropertyType}. It should have a bool return type.");
                    }
                    if (!enabledProperty.CanRead)
                    {
                        throw new InvalidOperationException($"Property {enabledProperty.Name} is not a valid enabled callback, because it does not have a get accessor.");
                    }

                    Enabled = (bool)enabledProperty.GetValue(obj);
                }
                else
                {
                    if (method.ReturnType != typeof(bool))
                    {
                        throw new InvalidOperationException($"Method {metadata.Name} is not a valid enabled callback, because it has a return type of {method.ReturnType}. It should have a bool return type.");
                    }
                    ParameterInfo[]      parameters            = method.GetParameters();
                    List <ParameterInfo> nonOptionalParameters = parameters.Where(p => !p.IsOptional).ToList();
                    if (nonOptionalParameters.Count != 0)
                    {
                        throw new InvalidOperationException($"Method {metadata.Name} is not a valid enabled callback, because it takes {nonOptionalParameters.Count} non-optional arguments ({string.Join(", ", nonOptionalParameters.Select(p => p.Name))}). It should take 0 arguments");
                    }

                    Enabled = (bool)method.Invoke(obj, null);
                }
            }
            else
            {
                Enabled = true;
            }

            switch (displayType)
            {
            case DisplayType.None:
                if (metadata.PropertyType.IsEnum)
                {
                    // Enums use dropdown
                    DropDownOptions = Enum.GetValues(metadata.PropertyType).Cast <Enum>()
                                      .Select(e => VariableProperty.GetEnumDescription(e))
                                      .ToArray();
                    DisplayMethod = PropertyType.DropDown;
                }
                else if (typeof(IModel).IsAssignableFrom(metadata.PropertyType))
                {
                    // Model selector - use a dropdown containing names of all models in scope.
                    DisplayMethod   = PropertyType.DropDown;
                    DropDownOptions = model.FindAllInScope()
                                      .Where(m => metadata.PropertyType.IsAssignableFrom(m.GetType()))
                                      .Select(m => m.Name)
                                      .ToArray();
                }
                else if (metadata.PropertyType == typeof(bool))
                {
                    DisplayMethod = PropertyType.Checkbox;
                }
                else if (metadata.PropertyType == typeof(System.Drawing.Color))
                {
                    DisplayMethod = PropertyType.Colour;
                }
                else
                {
                    DisplayMethod = PropertyType.SingleLineText;
                }
                break;

            case DisplayType.FileName:
                DisplayMethod = PropertyType.File;
                break;

            case DisplayType.FileNames:
                DisplayMethod = PropertyType.Files;
                break;

            case DisplayType.DirectoryName:
                DisplayMethod = PropertyType.Directory;
                break;

            case DisplayType.DropDown:
                string methodName = metadata.GetCustomAttribute <DisplayAttribute>().Values;
                if (methodName == null)
                {
                    throw new ArgumentNullException($"When using DisplayType.DropDown, the Values property must be specified.");
                }
                BindingFlags flags  = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
                MethodInfo   method = model.GetType().GetMethod(methodName, flags);

                object[] args = metadata.GetCustomAttribute <DisplayAttribute>().ValuesArgs;

                // Attempt to resolve links - populating the dropdown may
                // require access to linked models.
                Simulations sims = model.FindAncestor <Simulations>();
                if (sims != null)
                {
                    sims.Links.Resolve(model, allLinks: true, throwOnFail: false);
                }

                DropDownOptions = ((IEnumerable <object>)method.Invoke(model, args))?.Select(v => v?.ToString())?.ToArray();
                DisplayMethod   = PropertyType.DropDown;
                break;

            case DisplayType.CultivarName:
                DisplayMethod = PropertyType.DropDown;
                IPlant       plant         = null;
                PropertyInfo plantProperty = model.GetType().GetProperties().FirstOrDefault(p => typeof(IPlant).IsAssignableFrom(p.PropertyType));
                if (plantProperty != null)
                {
                    plant = plantProperty.GetValue(model) as IPlant;
                }
                else
                {
                    plant = model.FindInScope <IPlant>();
                }
                if (plant != null)
                {
                    DropDownOptions = PropertyPresenterHelpers.GetCultivarNames(plant);
                }
                break;

            case DisplayType.TableName:
                DisplayMethod   = PropertyType.DropDown;
                DropDownOptions = model.FindInScope <IDataStore>()?.Reader?.TableNames?.ToArray();
                break;

            case DisplayType.FieldName:
                DisplayMethod = PropertyType.DropDown;
                IDataStore   storage           = model.FindInScope <IDataStore>();
                PropertyInfo tableNameProperty = model.GetType().GetProperties().FirstOrDefault(p => p.GetCustomAttribute <DisplayAttribute>()?.Type == DisplayType.TableName);
                string       tableName         = tableNameProperty?.GetValue(model) as string;
                if (storage != null && storage.Reader.TableNames.Contains(tableName))
                {
                    DropDownOptions = storage.Reader.ColumnNames(tableName).ToArray();
                }
                break;

            case DisplayType.LifeCycleName:
                DisplayMethod = PropertyType.DropDown;
                Zone zone = model.FindInScope <Zone>();
                if (zone != null)
                {
                    DropDownOptions = PropertyPresenterHelpers.GetLifeCycleNames(zone);
                }
                break;

            case DisplayType.LifePhaseName:
                DisplayMethod = PropertyType.DropDown;
                LifeCycle lifeCycle = null;
                if (attrib.LifeCycleName != null)
                {
                    lifeCycle = model.FindInScope <LifeCycle>(attrib.LifeCycleName);
                }
                else
                {
                    foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (property.PropertyType == typeof(string))
                        {
                            string    value = property.GetValue(model) as string;
                            LifeCycle match = model.FindInScope <LifeCycle>(value);
                            if (match != null)
                            {
                                lifeCycle = match;
                                break;
                            }
                        }
                    }
                }
                if (lifeCycle != null)
                {
                    DropDownOptions = PropertyPresenterHelpers.GetPhaseNames(lifeCycle).ToArray();
                }
                break;

            case DisplayType.Model:
                DisplayMethod   = PropertyType.DropDown;
                DropDownOptions = model.FindAllInScope().Where(m => metadata.PropertyType.IsAssignableFrom(m.GetType()))
                                  .Select(m => m.Name)
                                  .ToArray();
                break;

            case DisplayType.ResidueName:
                if (model is SurfaceOrganicMatter surfaceOM)
                {
                    DisplayMethod   = PropertyType.DropDown;
                    DropDownOptions = surfaceOM.ResidueTypeNames().ToArray();
                    break;
                }
                else
                {
                    throw new NotImplementedException($"Display type {displayType} is only supported on models of type {typeof(SurfaceOrganicMatter).Name}, but model is of type {model.GetType().Name}.");
                }

            case DisplayType.MultiLineText:
                DisplayMethod = PropertyType.MultiLineText;
                if (Value is IEnumerable enumerable && metadata.PropertyType != typeof(string))
                {
                    Value = string.Join(Environment.NewLine, ((IEnumerable)metadata.GetValue(obj)).ToGenericEnumerable());
                }
                break;

            // Should never happen - presenter should handle this(?)
            //case DisplayType.SubModel:
            default:
                throw new NotImplementedException($"Unknown display type {displayType}");
            }

            // If the list of dropdown options doesn't contain the actual value of the
            // property, add that value to the list of valid options.
            if (DisplayMethod == PropertyType.DropDown && Value != null)
            {
                if (DropDownOptions == null)
                {
                    DropDownOptions = new string[1] {
                        Value.ToString()
                    }
                }
                ;
                else if (!DropDownOptions.Contains(Value.ToString()))
                {
                    List <string> values = DropDownOptions.ToList();
                    values.Add(Value.ToString());
                    DropDownOptions = values.ToArray();
                }
            }
        }
Ejemplo n.º 35
0
 public CoinsCommands(IServiceProvider services)
 {
     dataStore = services.GetRequiredService <IDataStore>();
     config    = services.GetRequiredService <Configuration>();
     logger    = services.GetRequiredService <ILoggerFactory>().CreateLogger <CoinsCommands>();
 }
Ejemplo n.º 36
0
 public EntityFrameworkOrmFramework(IDataStore dataStore, RequestContext context)
     : this(dataStore, context, null)
 {
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OktaClient"/> class.
 /// </summary>
 /// <param name="dataStore">The <see cref="IDataStore">DataStore</see> to use.</param>
 /// <param name="configuration">The client configuration.</param>
 /// <param name="requestContext">The request context, if any.</param>
 /// <remarks>This overload is used internally to create cheap copies of an existing client.</remarks>
 protected OktaClient(IDataStore dataStore, OktaClientConfiguration configuration, RequestContext requestContext)
 {
     _dataStore      = dataStore ?? throw new ArgumentNullException(nameof(dataStore));
     Configuration   = configuration;
     _requestContext = requestContext;
 }
 public override void SyncData(IDataStore dataStore)
 {
     dataStore.SyncData("partiedJoinedMapEvent", ref _partiedJoinedMapEvent);
 }
Ejemplo n.º 39
0
        public DetailsPage(IDataStore <Equipment> dataStore)
        {
            _dataStore = dataStore;

            InitializeComponent();
        }
Ejemplo n.º 40
0
 public DataFileService(ILogger logger, IDataStore data)
 {
     _data   = data;
     _logger = logger.ForContext <DataFileService>();
 }
Ejemplo n.º 41
0
 //--- Constructors ---
 public EncryptionBL(IDataStore session, IChallengeBL challengeBL, IRedisClientsManager redisClients)
 {
     _session      = session;
     _challengeBL  = challengeBL;
     _redisClients = redisClients;
 }
Ejemplo n.º 42
0
 public MessageController(IDataStore _data)
 {
     this._data = _data;
 }
Ejemplo n.º 43
0
 public DynamicTypeParser(IDataStore dstore)
 {
     _dstore = dstore;
 }
Ejemplo n.º 44
0
 public GoogleCalendar(IPlanerConfig planerConfig, IDataStore dataStore, IHttpContextAccessor httpContextAccessor)
 {
     _planerConfig        = planerConfig;
     _dataStore           = dataStore;
     _httpContextAccessor = httpContextAccessor;
 }
Ejemplo n.º 45
0
 // Todo: can be altered after removing Obsolete client calls
 public OptimizeRequest(Uri imageUrl, Uri callbackUrl, IDataStore dataStore) : base(imageUrl, callbackUrl)
 {
     S3Store = dataStore;
 }
 public override void SyncData(IDataStore dataStore)
 {
 }
 public PermissionRolesDataStore(IOpenModDataStoreAccessor dataStoreAccessor)
 {
     m_DataStore = dataStoreAccessor.DataStore;
     AsyncHelper.RunSync(InitAsync);
 }
Ejemplo n.º 48
0
        private static void SaveStartDocument(IFolderDao folderDao, IFileDao fileDao, object folderId, string path, IDataStore storeTemplate)
        {
            foreach (var file in storeTemplate.ListFilesRelative("", path, "*", false))
            {
                SaveFile(fileDao, folderId, path + file, storeTemplate);
            }

            if (storeTemplate is S3Storage)
            {
                return;
            }

            foreach (var folderUri in storeTemplate.List(path, false))
            {
                var folderName = Path.GetFileName(folderUri.ToString());

                var subFolderId = folderDao.SaveFolder(new Folder
                {
                    Title          = folderName,
                    ParentFolderID = folderId
                });

                SaveStartDocument(folderDao, fileDao, subFolderId, path + folderName + "/", storeTemplate);
            }
        }
Ejemplo n.º 49
0
 public Step_UpdateCode(IPlugin_HistoryData historyData, IDataStore dataStore)
 {
     this.codes           = historyData.GetInstruments();
     this.instrumentStore = dataStore.CreateInstrumentStore();
 }
Ejemplo n.º 50
0
        public static void GenerateThumbnail(Stream stream, string outputPath, ref ImageInfo imageInfo, IDataStore store)
        {
            ThumbnailGenerator _generator = new ThumbnailGenerator(null, true,
                                                                   maxSize,
                                                                   maxSize,
                                                                   maxWidthPreview,
                                                                   maxHeightPreview);

            _generator.store = store;
            _generator.DoThumbnail(stream, outputPath, ref imageInfo);
        }
Ejemplo n.º 51
0
        public WhmcsApi(string username, string password, string domain, bool secure, IDataStore dataStore)
        {
            this.username  = username;
            this.password  = md5Converter.ToMD5(password);
            this.dataStore = dataStore;
            url            = (secure ? "https://" : "http://") + domain + "/includes/api.php";

            formData = new NameValueCollection()
            {
                { "username", this.username },
                { "password", this.password },
                { "responsetype", "json" }
            };
        }
 public PolicyTerminatedHandler(IDataStore dataStore)
 {
     this.dataStore = dataStore;
 }
 public ResourceUsageDetectionServiceTest(IDataStore dataStore, IFunctionMetadataService functionMetadataService)
 {
     _dataStore = dataStore;
     _functionMetadataService = functionMetadataService;
 }
Ejemplo n.º 54
0
 // Todo: can be altered after removing Obsolete client calls
 public OptimizeWaitRequest(Uri imageUrl, IDataStore dataStore) : base(imageUrl)
 {
     BlobStore = dataStore;
 }
Ejemplo n.º 55
0
 public RequestService(IDataStore dataStore, IPositionService positionService, ICustomerService customerService)
 {
     _dataStore       = dataStore;
     _positionService = positionService;
     _customerService = customerService;
 }
Ejemplo n.º 56
0
 public void ResolveConflicts(IDataStore localDataStore, IConflictsManager conflictsManager)
 {
 }
Ejemplo n.º 57
0
 /// <summary>
 /// Gets a delete formatter
 /// </summary>
 /// <param name="dstore">the datastore to attach it to</param>
 /// <returns></returns>
 public IDeleteFormatter GetDeleteFormatter(IDataStore dstore)
 {
     return(new DeleteTSqlFormatter(dstore));
 }
 public SessionController(IDataStore <ISession> DataStore)
 {
     this._DataStore = DataStore;
 }
Ejemplo n.º 59
0
        private static void SaveFile(IFileDao fileDao, object folder, string filePath, IDataStore storeTemp)
        {
            using (var stream = storeTemp.IronReadStream("", filePath, 10))
            {
                var fileName = Path.GetFileName(filePath);
                var file     = new File
                {
                    Title         = fileName,
                    ContentLength = stream.Length,
                    FolderID      = folder,
                };
                stream.Position = 0;
                try
                {
                    file = fileDao.SaveFile(file, stream);

                    FileMarker.MarkAsNew(file);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
 partial void OnGetInventoryItemDataStore(ref IDataStore <Inventory.Entities.InventoryItemEntity> result);