Summary description for AppConfigHandler
Inheritance: WebServiceHandler
Example #1
0
        public static void Main()
        {
            Debug.Print(Microsoft.SPOT.Hardware.SystemInfo.OEMString);
            Debug.Print("Model: " + Microsoft.SPOT.Hardware.SystemInfo.SystemID.Model.ToString());
            Debug.Print("OEM: " + Microsoft.SPOT.Hardware.SystemInfo.SystemID.OEM.ToString());
            Debug.Print("SKU: " + Microsoft.SPOT.Hardware.SystemInfo.SystemID.SKU.ToString());

            // Setup the hardware.
            if (MeridianPHarddwareProvider.IsHardwareMeridianP())
            {
                _hardwareController = new MeridianPLedController();
            }
            else
            {
                _hardwareController = new NetduinoLedController();
            }

            _hardwareController.SwitchPressed += hardwareController_SwitchPressed;
            _hardwareController.Initialize();
            _appConfig = _hardwareController.AppConfig;

            // Create a new timer to check the light level.
            new Timer(timerTick, null, 100, 5000);

            Thread.Sleep(Timeout.Infinite);
        }
Example #2
0
 public static void Log(this object e, string logMessage = "", LogType type = LogType.SystemLog, string defaultSchema = "system", int severityLevel = 0)
 {
     if (_logSeverityLevel == -1) _logSeverityLevel = new AppConfig<ApplicationConfiguration>().GetConfigValue<int>("LogSeverityLevel");
     if ((e as Exception) != null) type = LogType.ExceptionLog;
     else if ((e as string) != null) logMessage += e;
     if (severityLevel > _logSeverityLevel) return;
     logMessage = logMessage.Replace("'", "''");
     switch (type)
     {
         case LogType.ExceptionLog:
             var innerException = (Exception)e;
             logMessage += innerException.Message;
             while (innerException.InnerException != null)
             {
                 logMessage += innerException.Message;
                 innerException = innerException.InnerException;
             }
             AppLogger.Error(logMessage);
             break;
         case LogType.SystemLog:
             AppLogger.Info(logMessage);
             break;
         case LogType.ScheduledLog:
             DAL.DefaultDb.ExecuteNonQuery(CommandType.Text, string.Format(Resources.Resources.LogScript_sql, defaultSchema, (int)type, logMessage));
             AppLogger.Info(logMessage);
             break;
     }
 }
Example #3
0
        public static void SaveConfig(string rssUrl, int interval = 15, bool stayOnTop = false)
        {
            // clear latest item if rss url changed
            if (_config != null && rssUrl != _config.RssUrl)
            {
                if (File.Exists(LatestItemFilePath))
                {
                    File.Delete(LatestItemFilePath);
                }
            }

            _config = new AppConfig
            {
                RssUrl = rssUrl,
                Interval = interval,
                StayOnTop = stayOnTop
            };

            using (FileStream stream = File.Create(ConfigFilePath))
            {
                new DataContractJsonSerializer(typeof(AppConfig)).WriteObject(stream, _config);
            }

            if (ConfigSave != null)
            {
                ConfigSave();
            }
        }
 /// <summary>
 /// Protected constructor.
 /// </summary>
 /// <param name="config">The config class.</param>
 protected TraceListener(AppConfig config)
 {
     this.config = config;
       if (this.config.LogToFile) {
     this.writer = new DefaultTraceWriter(config);
       }
 }
Example #5
0
        public MainWindow(AppConfig app_config)
        {
            InitializeComponent();

            // Initialize application data
            this.AppConfig = app_config;
            this.Files = new List<ImageFile>();

            // Initialize Background Workers
            this.ScanWorker = new BackgroundWorker();
            this.ScanWorker.WorkerSupportsCancellation = true;
            this.ScanWorker.DoWork += OnScanPaths;
            this.ScanWorker.RunWorkerCompleted += OnScanFinished;
            this.OptimizeWorker = new BackgroundWorker();
            this.OptimizeWorker.WorkerSupportsCancellation = true;
            this.OptimizeWorker.DoWork += OnOptimize;
            this.OptimizeWorker.RunWorkerCompleted += OnOptimizeFinished;

            // Initialize Refresh Timer
            this.RefreshTimer = new Timer();
            this.RefreshTimer.Interval = 500;
            this.RefreshTimer.Tick += OnRefreshListView;

            // Initialize GUI
            //this.PendingFiles = new List<ImageFile>();
            this.listView.SetObjects(this.Files);
            this.colPath.AspectName = "Path";
            this.colSize.AspectName = "Size";
            this.colSize.AspectToStringConverter = delegate(object x) { return ImageFile.GetReadableSize((long)x); };
            this.colSavings.AspectName = "Savings";
            this.colSavings.AspectToStringConverter = GetSavings;
            //this.colPath.AspectGetter = GetPath;
            SetStatus(State.Ready);
        }
Example #6
0
        public void Startup()
        {
            MultipleDisposable.Add(() => Repositories.ForEach(x => x.Dispose()));

            _config = AppConfig.LoadFromFile(ConfigFilePath);
            _config.Repositories.ForEach(r => Repositories.Add(new Repository(r)));
        }
Example #7
0
        static AppConfig getAppConfig()
        {
            var ac = new AppConfig();

            // overwrite with application config
            if (Properties.Settings.Default.MasterPort != 0) ac.masterPort = Properties.Settings.Default.MasterPort;
            if (Properties.Settings.Default.SharedConfigFile != "") ac.sharedCfgFileName = Properties.Settings.Default.SharedConfigFile;
            if (Properties.Settings.Default.StartupPlan != "") ac.startupPlanName = Properties.Settings.Default.StartupPlan;

            // overwrite with command line options
            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(System.Environment.GetCommandLineArgs(), options))
            {
                if (options.MasterPort != 0) ac.masterPort = options.MasterPort;
                if (options.SharedConfigFile != "") ac.sharedCfgFileName = options.SharedConfigFile;
                if (options.LogFile != "") ac.logFileName = options.LogFile;
                if (options.StartupPlan != "") ac.startupPlanName = options.StartupPlan;
            }

            if (ac.logFileName != "")
            {
                SetLogFileName(Path.GetFullPath(ac.logFileName));
            }

            if( ac.sharedCfgFileName != "" )
            {
                ac.sharedCfgFileName = Path.GetFullPath(ac.sharedCfgFileName);
                log.DebugFormat("Loading shared config file '{0}'", ac.sharedCfgFileName);
                ac.scfg = new SharedXmlConfigReader().Load(File.OpenText(ac.sharedCfgFileName));
            }
            return ac;
        }
Example #8
0
 private static void LoadConfig()
 {
     using (FileStream stream = File.OpenRead(ConfigFilePath))
     {
         _config = new DataContractJsonSerializer(typeof(AppConfig)).ReadObject(stream) as AppConfig;
     }
 }
Example #9
0
 static public void LoadAppSrtting()
 {
     string filePath = ResourcePath + "/AppConfig.json";
     if (File.Exists(filePath))
         appConfig = Utility.LoadObjectFromJsonFile<AppConfig>(filePath);
     else
         appConfig = new AppConfig();
 }
 /// <summary>
 /// Instantiates a new OneDriveClient.
 /// </summary>
 public OneDriveClient(
     AppConfig appConfig,
     CredentialCache credentialCache = null,
     IHttpProvider httpProvider = null,
     IServiceInfoProvider serviceInfoProvider = null)
     : base(appConfig, credentialCache, httpProvider, serviceInfoProvider)
 {
 }
 /// <summary>
 /// Instantiates a new OneDriveClient.
 /// </summary>
 public OneDriveClient(
     AppConfig appConfig,
     CredentialCache credentialCache = null,
     IHttpProvider httpProvider = null,
     IServiceInfoProvider serviceInfoProvider = null,
     ClientType clientType = ClientType.Consumer)
     : base(appConfig, credentialCache, httpProvider, serviceInfoProvider, clientType)
 {
 }
Example #12
0
 public AdalClient(
     AppConfig appConfig, 
     CredentialType credentialType, 
     IServiceInfoProvider serviceProvider = null)
     : base(appConfig, credentialType, serviceProvider)
 {
     appConfig.ServiceResource = Constants.Authentication.GraphServiceUrl;
     serviceProvider = new ServiceProvider();
     this.ServiceInformation = _serviceInfoProvider.CreateServiceInfo(appConfig, credentialType).Result;
 }
Example #13
0
    private void DrawAppConfig(AppConfig appConfig )
    {
        appConfig.isAssets = EditorGUILayout.Toggle("Load Assets(Editor Only)", appConfig.isAssets);
        appConfig.mCdn = EditorGUILayout.TextField("CDN", appConfig.mCdn);


        if (GUILayout.Button("Apply"))
        {
            AppSetting.SaveAppSetting();
        }
    }
        public void Setup()
        {
            this.appConfig = new AppConfig
            {
                ClientID = "1234567",
                ClientSecret = "supersecret",
                TenantDomain = "contoso"
            };

            this.serviceProvider = new ServiceProvider();
        }
 /// <summary>
 /// Overloaded constructor.
 /// </summary>
 /// <param name="config">The application configuration class for configuring
 /// this instance.</param>
 public DefaultTraceWriter(AppConfig config)
 {
     string logPath = "";
       if (config.LogToFile) {
     logPath = config.LogPath.TrimEnd('\\', '/') + Path.DirectorySeparatorChar;
     if (!Directory.Exists(logPath)) {
       Directory.CreateDirectory(logPath);
     }
     soapFileName = logPath + "soap_xml.log";
     requestInfoFileName = logPath + "request_info.log";
       }
 }
    /// <summary>
    /// Builds an HTTP PUT request with a Range header.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="contentLength">Length of the content.</param>
    /// <param name="range">The range heaer notation.</param>
    /// <param name="config">The configuration instance for customizing the
    /// connection settings.</param>
    /// <returns>The web request for making HTTP call.</returns>
    /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="config"/>
    /// is null.</exception>
    public static WebRequest BuildRangeRequest(string url, int contentLength, string range,
        AppConfig config) {
      if (config == null) {
        throw new ArgumentNullException("config");
      }

      WebRequest request = BuildRequest(url, "PUT", config);

      request.ContentLength = contentLength;
      request.Headers["Content-Range"] = range;

      return request;
    }
        public Task<ServiceInfo> GetServiceInfo(AppConfig appConfig, CredentialCache credentialCache, IHttpProvider httpProvider)
        {
            var microsoftAccountServiceInfo = new MicrosoftAccountServiceInfo
            {
                AppId = appConfig.MicrosoftAccountAppId,
                ClientSecret = appConfig.MicrosoftAccountClientSecret,
                CredentialCache = credentialCache,
                HttpProvider = httpProvider,
                Scopes = appConfig.MicrosoftAccountScopes,
            };

            microsoftAccountServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new OnlineIdAuthenticationProvider(microsoftAccountServiceInfo);
            return Task.FromResult<ServiceInfo>(microsoftAccountServiceInfo);
        }
Example #18
0
        public static App Initialize(AppConfig config)
        {
            var startOptions = new StartOptions();
            startOptions.Urls.Add(config.InternalUri);
            startOptions.Urls.Add(config.PublicUri);

            var nancyOptions = new NancyOptions
            {
                Bootstrapper = new VaultBootstrapper()
            };

            var cts = new CancellationTokenSource();

            var webApp = WebApp.Start(startOptions, x => x.UseNancy(nancyOptions));
            return new App(webApp, cts);
        }
        public Task<ServiceInfo> GetServiceInfo(AppConfig appConfig, CredentialCache credentialCache, IHttpProvider httpProvider)
        {
            var microsoftAccountServiceInfo = new MicrosoftAccountServiceInfo
            {
                AppId = appConfig.MicrosoftAccountAppId,
                ClientSecret = appConfig.MicrosoftAccountClientSecret,
                CredentialCache = credentialCache,
                HttpProvider = httpProvider,
                ReturnUrl = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString(),
                Scopes = appConfig.MicrosoftAccountScopes,
                WebAuthenticationUi = this.webAuthenticationUi,
            };

            microsoftAccountServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new WebAuthenticationBrokerAuthenticationProvider(microsoftAccountServiceInfo);
            return Task.FromResult<ServiceInfo>(microsoftAccountServiceInfo);
        }
Example #20
0
 /// <summary>
 /// Protected constructor. Use this version from a derived class if you want
 /// the library to use all settings from App.config.
 /// </summary>
 /// <remarks>This constructor exists for backward compatibility purposes.
 /// </remarks>
 protected AdsUser(AppConfigBase config, Dictionary<string, string> headers)
 {
     this.config = config;
       MergeValuesFromHeaders(config, headers);
       RegisterServices(GetServiceTypes());
       if (this.config.EnableSoapExtension) {
     listeners.AddRange(GetDefaultListeners());
       }
       SetHeadersFromConfig();
       config.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e) {
     if (e.PropertyName == "OAuth2Mode") {
       SetOAuthProvider(config);
     }
       };
       SetOAuthProvider(config);
 }
Example #21
0
        public JsonResult Update(AppConfig AppConfig)
        {
            var Message = new { @Message = "", @Error = 0 };
            try
            {
                var Config = Unit.ConfigRepository.Get(filter: c => c.Key == AppConfig.Key).FirstOrDefault();
                Config.Value = AppConfig.Value;
                Unit.ConfigRepository.Update(Config);
                Unit.Save();

            }
            catch (Exception e)
            {
                Message = new { @Message = e.Message, @Error = 1 };
            }
            return Json(Message);
        }
    /// <summary>
    /// Retrieves an asset from the web given its url.
    /// </summary>
    /// <param name="assetUrl">The url of the asset to be retrieved.</param>
    /// <param name="config">The application configuration instance.</param>
    /// <returns>Asset data, as an array of bytes.</returns>
    /// <exception cref="ArgumentNullException">Thrown if
    /// <paramref name="assetUrl"/> or <paramref name="config"/>is null.
    /// </exception>
    public static byte[] GetAssetDataFromUrl(Uri assetUrl, AppConfig config) {
      if (assetUrl == null) {
        throw new ArgumentNullException("assetUrl");
      }

      if (config == null) {
        throw new ArgumentNullException("config");
      }

      WebRequest request = HttpUtilities.BuildRequest(assetUrl.AbsoluteUri, "GET", config);
      WebResponse response = request.GetResponse();

      MemoryStream memStream = new MemoryStream();
      using (Stream responseStream = response.GetResponseStream()) {
        CopyStream(responseStream, memStream);
      }
      return memStream.ToArray();
    }
        /// <summary>
        /// Creates a OneDrive client for use against OneDrive consumer.
        /// </summary>
        /// <param name="appId">The application ID for Microsoft Account authentication.</param>
        /// <param name="returnUrl">The application return URL for Microsoft Account authentication.</param>
        /// <param name="scopes">The requested scopes for Microsoft Account authentication.</param>
        /// <param name="clientSecret">The client secret for Microsoft Account authentication.</param>
        /// <param name="credentialCache">The cache instance for storing user credentials.</param>
        /// <param name="httpProvider">The <see cref="IHttpProvider"/> for sending HTTP requests.</param>
        /// <param name="serviceInfoProvider">The <see cref="IServiceInfoProvider"/> for initializing the <see cref="IServiceInfo"/> for the session.</param>
        /// <returns>The <see cref="IOneDriveClient"/> for the session.</returns>
        public static IOneDriveClient GetMicrosoftAccountClient(
            string appId,
            string returnUrl,
            string[] scopes,
            string clientSecret,
            CredentialCache credentialCache = null,
            IHttpProvider httpProvider = null,
            IServiceInfoProvider serviceInfoProvider = null)
        {
            var appConfig = new AppConfig
            {
                MicrosoftAccountAppId = appId,
                MicrosoftAccountReturnUrl = returnUrl,
                MicrosoftAccountScopes = scopes,
            };

            return new OneDriveClient(appConfig, credentialCache, httpProvider, serviceInfoProvider);
        }
        public void SetUp ()
        {
            _sessionIds = new List<string> ();

            _slot1 = new Slot {
                StartTime = new DateTime (2014, 10, 1, 8, 0, 0),
                EndTime = new DateTime (2014, 10, 1, 8, 50, 0),
                SessionIds = _sessionIds
            };

            _slot2 = new Slot {
                StartTime = new DateTime (2014, 10, 1, 9, 0, 0),
                EndTime = new DateTime (2014, 10, 1, 9, 50, 0),
                SessionIds = _sessionIds
            };

            _days = new List<Day> {
                new Day {
                    Date = new DateTime(2014, 10, 1),
                    Slots = new List<Slot> {
                        _slot1,
                        _slot2
                    }
                }
            };

            _schedule = new Schedule { Days = _days };
            _appConfig = new AppConfig ();

            _repository = new MockRepository {
                GetDaysResult = _days,
                GetScheduleResult = _schedule,
                GetAppConfigResult = _appConfig
            };

            _sessions = new List<Session> ();
            _repository.GetSessionsResults [_sessionIds] = _sessions;

            _timeService = new MockTimeService ();
            _twitterService = new MockTwitterService ();
            _sut = new HomeViewModel (_repository, _timeService, _twitterService);
        }
Example #25
0
        public void Given()
        {
            var customConfigResourceName =
                GetType().Assembly.GetManifestResourceNames().Single(r => r.EndsWith("Custom.config"));

            var configFilename = Path.Combine(Environment.CurrentDirectory, "Custom.config");
            using (var resourceStream = GetType().Assembly.GetManifestResourceStream(customConfigResourceName))
            {
                if (resourceStream == null)
                {
                    throw new ApplicationException("Expected to find embedded resource file for custom config test");
                }
                using (var configFile = File.Create(configFilename))
                {
                    resourceStream.CopyTo(configFile);
                }
            }

            _configFileContext = AppConfig.Change(configFilename);
        }
    /// <summary>
    /// Builds an HTTP request with a specified method.
    /// </summary>
    /// <param name="url">The URL.</param>
    /// <param name="method">The HTTP method.</param>
    /// <param name="config">The configuration instance for customizing the
    /// connection settings.</param>
    /// <returns>The web request for making HTTP call.</returns>
    /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="config"/>
    /// is null.</exception>
    public static WebRequest BuildRequest(string url, string method, AppConfig config) {
      if (config == null) {
        throw new ArgumentNullException("config");
      }

      HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);

      request.Method = method;
      request.Proxy = config.Proxy;
      request.Timeout = config.Timeout;
      request.UserAgent = config.GetUserAgent();

      if (config.EnableGzipCompression) {
        (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip
            | DecompressionMethods.Deflate;
      } else {
        (request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.None;
      }
      return request;
    }
Example #27
0
        public virtual Task<ServiceInformation> CreateServiceInfo(AppConfig appConfig, CredentialType credentialType)
        {
            var activeDirectoryServiceInfo = new AdalServiceInformation
            {
                ClientID = appConfig.ClientID,
                ClientSecret = appConfig.ClientSecret,
                Tenant = appConfig.TenantDomain,
                ServiceResource = appConfig.ServiceResource
            };

            if (credentialType == CredentialType.Certificate)
            {
                activeDirectoryServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new AdalCertificateAuthenticationProvider(activeDirectoryServiceInfo);
            }
            else
            {
                activeDirectoryServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new AdalClientAuthenticationProvider(activeDirectoryServiceInfo);
            }

            return Task.FromResult<ServiceInformation>(activeDirectoryServiceInfo);
        }
        public static void Log(this object e, string logMessage = "", LogType type = LogType.SystemLog, string defaultSchema = "system", int severityLevel = 0)
        {
            if (_logSeverityLevel == -1)
                _logSeverityLevel = new AppConfig<ApplicationConfiguration>().GetConfigValue<int>(ApplicationConfiguration.LogSeverityLevel);

            if (severityLevel > _logSeverityLevel) return;

            logMessage = logMessage.Replace("'", "''");

            if ((e as Exception) != null)
            {
                logMessage += ((Exception)e).Message;
                type = LogType.ExceptionLog;
            }
            else if ((e as string) != null)
            {
                logMessage += e;
            }

            DAL.DefaultDb.ExecuteNonQuery(CommandType.Text,
                    string.Format(Properties.Resources.LogScript_sql, defaultSchema, (int)type, logMessage));
        }
Example #29
0
    public void Initialize(AppConfig config)
    {
        if (map != null) {
            map.Dispose ();
        }

        fileName = config.MapFileName;
        userDragSpeed = config.UserDragSpeed;

        server = new TileServer (config.MapSize.x, config.MapSize.y, prefab.GetPrefabCount (), config.RefreshIntervalSeconds, networkLatency);

        ITileFactory factory;
        if (config.RefreshTiles) {
            factory = new TimedProxyTileFactory (server, config.RefreshIntervalSeconds);
        } else {
            factory = new ProxyTileFactory (server);
        }

        ITileLoadingStrategy tileLoadingStrategy;
        if (config.LoadPotentialTiles) {
            tileLoadingStrategy = new EagerLoadingStrategy ();
        } else {
            tileLoadingStrategy = new LazyLoadingStrategy ();
        }

        storage = new TileStorage (factory);

        Map simpleMap = new Map (storage.Load (fileName), factory, tileLoadingStrategy, prefab, config.MapSize.x, config.MapSize.y);

        if (config.LimitTilesCount) {
            map = new LimitedMap (simpleMap, config.MaxTilesCount);
        } else {
            map = simpleMap;
        }

        area = new VisibleArea (map);

        initialized = true;
    }
Example #30
0
        public static void Main(params string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

            var range = args.FirstOrDefault() ?? "8";

            var config = new AppConfig
            {
                PublicUri = "http://127.0.0.1:" + range + "001",
                InternalUri = "http://127.0.0.1:" + range + "002",
            };

            var app = App.Initialize(config);
            Console.WriteLine(
                "Console app started on {0} and {1}",
                config.PublicUri,
                config.InternalUri
                );

            Console.ReadLine();
            app.RequestStop();
            Console.WriteLine("App terminated");
            Console.ReadLine();
        }