private void Configure(AzureServiceBusOwinServiceConfiguration config, Action<IAppBuilder> startup)
        {
            if (startup == null)
            {
                throw new ArgumentNullException("startup");
            }

            var options = new StartOptions();
            if (string.IsNullOrWhiteSpace(options.AppStartup))
            {
                // Populate AppStartup for use in host.AppName
                options.AppStartup = startup.Method.ReflectedType.FullName;
            }

            var testServerFactory = new AzureServiceBusOwinServerFactory(config);
            var services = ServicesFactory.Create();
            var engine = services.GetService<IHostingEngine>();
            var context = new StartContext(options)
            {
                ServerFactory = new ServerFactoryAdapter(testServerFactory),
                Startup = startup
            };
            _started = engine.Start(context);
            _next = testServerFactory.Invoke;
        }
Ejemplo n.º 2
0
        public void FixtureSetup()
        {
            _server = WebApp.Start<Startup>(BASE_ADDRESS);

            IHttwrapConfiguration configuration = new HttwrapConfiguration(BASE_ADDRESS);
            _client = new HttwrapClient(configuration);
        }
 public ClientAnnotationViewModel(ISharedDataService sharedDataService, MeetingViewModel meeting) : base(sharedDataService, meeting)
 {
     // create the client annotations property, a mapped version of the agent's properties based on the screen sizes.
     _annotationsChangedSub = _clientAnnotations = AnnotationsModel
                                                       .WhenAnyValue(v => v.Annotations, v => v.Select(p => CreateAnnotationViewModel(p)))
                                                       .ToProperty(this, v => v.Annotations);
 }
Ejemplo n.º 4
0
        public Task StopAsync()
        {
            this.signalrServer?.Dispose();
            this.signalrServer = null;

            return Task.CompletedTask;
        }
Ejemplo n.º 5
0
 public LightningQueuesChannel(Uri address, string queueName, Queue queueManager)
 {
     Address = address;
     _queueName = queueName;
     _queueManager = queueManager;
     _disposable = Disposable.Empty;
 }
		public void Initialize(IDocument document)
		{
			if (this.document == null) {
				this.document = document;
				this.textDocument = (TextDocument)document.GetService(typeof(TextDocument));
				this.changeList = new CompressingTreeList<LineChangeInfo>((x, y) => x.Equals(y));
			}
			
			var fileName = ((ITextEditor)document.GetService(typeof(ITextEditor))).FileName;
			
			InitializeBaseDocument();
			if (watcher != null)
				watcher.Dispose();
			
			if (usedProvider != null)
				watcher = usedProvider.WatchBaseVersionChanges(fileName, HandleBaseVersionChanges);
			
			SetupInitialFileState(fileName != currentFileName);
			currentFileName = fileName;
			
			if (!this.textDocument.LineTrackers.Contains(this)) {
				this.textDocument.LineTrackers.Add(this);
				this.textDocument.UndoStack.PropertyChanged += UndoStackPropertyChanged;
			}
		}
Ejemplo n.º 7
0
        private static void Run()
        {
            if (Arguments.NumClients > 1)
            {
                AppHost = WebApp.Start<Startup>(Arguments.ControllerUrl);

                if (!WaitForClientsToConnect())
                {
                    SignalPhaseChange(ControllerEvents.Abort);
                    for (int attempts = 0; (ClientsConnected > 0) && (attempts < CrankArguments.ConnectionPollAttempts); attempts++)
                    {
                        Thread.Sleep(CrankArguments.ConnectionPollIntervalMS);
                    }

                    AppHost.Dispose();
                    return;
                }
            }

            RunConnect();
            RunSend();
            RunDisconnect();

            WaitForLastSamples();

            if (AppHost != null)
            {
                AppHost.Dispose();
            }

            FlushLog(force:true);
        }
Ejemplo n.º 8
0
        public StateBucketService(ISettingsStore store)
        {
            var converter = new StateBucketConverter();

            bool loading = false;
            var writer = _cache.Connect()
                .ToCollection()
                .Select(buckets => converter.Convert(buckets.ToArray()))
                .Subscribe(state =>
                {
                    if (loading) return;
                    store.Save(SettingStoreKey, state);
                });

            //TODO: Make this error proof

            var initialState = store.Load(SettingStoreKey);
            var initialBuckets = converter.Convert(initialState);

            try
            {
                loading = true;
                _cache.AddOrUpdate(initialBuckets);
            }
            finally
            {
                loading = false;
            }

            _cleanUp = new CompositeDisposable(writer, _cache);
        }
Ejemplo n.º 9
0
 internal TestBlobCache(Action disposer, 
     IScheduler scheduler, 
     IEnumerable<KeyValuePair<string, byte[]>> initialContents)
     : this(scheduler, initialContents)
 {
     inner = Disposable.Create(disposer);
 }
Ejemplo n.º 10
0
        public NodeViewModel(Node node, Vector location, IControlTypesResolver controlTypesResolver)
        {
            Node = node;
            Title = node.Title;
            Location = new CanvasPoint(location);
            ControlTypesResolver = controlTypesResolver;

            foreach (var pin in node.InputPins)
            {
                AddInputPin(pin);
            }

            foreach (var pin in node.OutputPins)
            {
                AddOutputPin(pin);
            }

            node.Processed += OnNodeProcessed;
            node.PinsChanged += OnNodePinsChanged;

            _disposable = Disposable.Create(() =>
            {
                node.PinsChanged -= OnNodePinsChanged;
                node.Processed -= OnNodeProcessed;
            });
        }
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;
            var uri = $"http://*:{portNumber}{siteUrl}";

            SmartDBEntities.SetConnection(Settings.Default.DBServer, Settings.Default.DBName,
                Settings.Default.DBUser,
                Encryption.Decrypt(Settings.Default.DBPassword));

            Program.ProcessLog.Write("Database connection string to " + Settings.Default.DBServer +
                                     " has successfully been made.");
            if (SmartDBEntities.IsDBAvailable)
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer +
                                         " has successfully been made.");
            else
                Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has failed.");
            var options = new StartOptions();
#if DEBUG
            options.Urls.Add($"http://{Environment.MachineName}:15000");
            options.Urls.Add("http://localhost:15000/");
#endif
            options.Urls.Add(uri);
            Host = WebApp.Start<Startup>(options);
        }
Ejemplo n.º 12
0
        public void Dispose()
        {
            if(_storeSubscription == null)
                return;

            _storeSubscription.Dispose();
            _storeSubscription = null;

            _pluginChannel.Do(x => x.Value.Dispose());
            _pluginChannel.Clear();
            _pluginChannel = null;

            _pluginServer.Do(x => x.Value.Dispose());
            _pluginServer.Clear();
            _pluginServer = null;

            _pluginGlobal.Do(x => x.Value.Dispose());
            _pluginGlobal.Clear();
            _pluginGlobal = null;

            _channel.Do(x => x.Value.Dispose());
            _channel.Clear();
            _channel = null;

            _server.Do(x => x.Value.Dispose());
            _server.Clear();
            _server = null;

            _global.Dispose();
            _global = null;
        }
        public void OnStart()
        {
            server = WebApp.Start<Startup>("http://+:7774");

            // TODO: Exception handling
            Task.Factory.StartNew(() => provider = new PerformanceDataProvider());
        }
		public MDRefactoringScript (MDRefactoringContext context, CSharpFormattingOptions formattingOptions) : base(context.TextEditor.Document, formattingOptions, context.TextEditor.CreateNRefactoryTextEditorOptions ())
		{
			this.context = context;
			undoGroup  = this.context.TextEditor.OpenUndoGroup ();
			this.startVersion = this.context.TextEditor.Version;

		}
Ejemplo n.º 15
0
 public Task StartTimer()
 {
     logger.Info("StartTimer.");
     timer = base.RegisterTimer(TimerTick, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
     
     return TaskDone.Done;
 }
Ejemplo n.º 16
0
		/// <summary>
		/// sets the codec token to be used for video compression
		/// </summary>
		public void SetVideoCodecToken(IDisposable token)
		{
			if (token is CodecToken)
				currVideoCodecToken = (CodecToken)token;
			else
				throw new ArgumentException("AviWriter only takes its own Codec Tokens!");
		}
Ejemplo n.º 17
0
        public void Start()
        {
            var siteUrl = Settings.Default.SiteUrl;
            var portNumber = Settings.Default.PortNumber;
            var uri = string.Format("http://*:{0}{1}", portNumber, siteUrl);

            //SmartDBEntities.SetConnection(Settings.Default.DBServer, Settings.Default.DBName,
            //       Settings.Default.DBUser,
            //       Encryption.Decrypt(Settings.Default.DBPassword));

            SupportCallManagerEntities.SetConnection(@"192.168.0.11\dev", "SupportCallManager",
                  Settings.Default.DBUser,
                  Encryption.Decrypt(Settings.Default.DBPassword));

            Program.ProcessLog.Write("Database connection string to " + Settings.Default.DBServer + " has successfully been made.");

            //if (SupportCallManagerEntities.IsDBAvailable)
            //    Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has successfully been made.");
            //else
            //    Program.ProcessLog.Write("Database connection  " + Settings.Default.DBServer + " has failed.");

            StartOptions options = new StartOptions();


#if DEBUG
            options.Urls.Add(string.Format("http://{0}:10000", Environment.MachineName));
            options.Urls.Add("http://+:10000/");
            options.Urls.Add("http://192.168.0.146:10000/");
#endif
            options.Urls.Add(uri);
            host = WebApp.Start<Startup>(options);
        }
Ejemplo n.º 18
0
        public void Initialize()
        {
            try
            {
                HostingEnvironment.RegisterObject(this);

                // Normally when the AppDomain shuts down IRegisteredObject.Stop gets called, except that
                // ASP.NET waits for requests to end before calling IRegisteredObject.Stop. This can be
                // troublesome for some frameworks like SignalR that keep long running requests alive.
                // These are more aggressive checks to see if the app domain is in the process of being shutdown and
                // we trigger the same cts in that case.
                if (HttpRuntime.UsingIntegratedPipeline)
                {
                    if (RegisterForStopListeningEvent())
                    {
                    }
                    else if (UnsafeIISMethods.CanDetectAppDomainRestart)
                    {
                        // Create a timer for polling when the app pool has been requested for shutdown.
#if NET40
                        // Use the existing timer
                        _checkAppPoolTimer = SharedTimer.StaticTimer.Register(CheckForAppDomainRestart, state: null);
#else
                        _checkAppPoolTimer = new Timer(CheckForAppDomainRestart, state: null,
                            dueTime: TimeSpan.FromSeconds(10), period: TimeSpan.FromSeconds(10));
#endif
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 19
0
        protected override void OnInitialize()
        {
            base.OnInitialize();

             var _ecgObservable = EcgSimulator.SimulateEcgAsObservable();
            _disposable = _ecgObservable.Subscribe(s => Debug.WriteLine(s));
        }
        /// <summary>
        /// Creates a new group containing two disposable resources that are disposed together.
        /// </summary>
        /// <param name="disposable1">The first disposable resoruce to add to the group.</param>
        /// <param name="disposable2">The second disposable resoruce to add to the group.</param>
        /// <returns>Group of disposable resources that are disposed together.</returns>
        public static ICancelable Create(IDisposable disposable1, IDisposable disposable2)
        {
            if (disposable1 == null) throw new ArgumentNullException("disposable1");
            if (disposable2 == null) throw new ArgumentNullException("disposable2");

            return new Binary(disposable1, disposable2);
        }
        // global instances that keep controller and windows service alive

        public void Start(QueueMessageManager manager = null)
        {
            if (manager == null)
                manager = new QueueMessageManagerSql();

            LogManager.Current.LogInfo("Start called");

            var config = QueueMessageManagerConfiguration.Current;

            Controller = new QueueController()
            {
                ConnectionString = config.ConnectionString,
                QueueName = config.QueueName,
                WaitInterval = config.WaitInterval,
                ThreadCount = config.ControllerThreads                
            };
            

            LogManager.Current.LogInfo("Controller created.");
            
            // asynchronously start the SignalR hub
            SignalR = WebApplication.Start<SignalRStartup>("http://*:8080/");

            // *** Spin up n Number of threads to process requests
            Controller.StartProcessingAsync();

            LogManager.Current.LogInfo(String.Format("QueueManager Controller Started with {0} threads.",
                                       Controller.ThreadCount));            

            // Set static instances so that these 'services' stick around
            GlobalService.Controller = Controller;
            GlobalService.Service = this;
        }
 public ConfigHandler()
 {
     _binder = SwitchXmlSearchBinding.Bind(XmlCallback,
         switch_xml_section_enum_t.SWITCH_XML_SECTION_DIRECTORY |
         switch_xml_section_enum_t.SWITCH_XML_SECTION_DIALPLAN);
     
 }
        public VirtualListVewModel(SynchronizationContext bindingContext, DataService service)
        {
            _virtualRequest = new BehaviorSubject<VirtualRequest>(new VirtualRequest(0,10));

            Items = new BindingList<Poco>();

            var sharedDataSource = service
                .DataStream
                .Do(x => Trace.WriteLine($"Service -> {x}"))
                .ToObservableChangeSet()
                .Publish();

            var binding = sharedDataSource
                          .Virtualise(_virtualRequest)
                          .ObserveOn(bindingContext)
                          .Bind(Items)
                          .Subscribe();
            
            //the problem was because Virtualise should fire a noticiation if count changes, but it does not [BUG]
            //Therefore take the total count from the underlying data NB: Count is DD.Count() not Observable.Count()
            Count = sharedDataSource.Count().DistinctUntilChanged();

            Count.Subscribe(x => Trace.WriteLine($"Count = {x}"));

            var connection = sharedDataSource.Connect();
            _disposables = new CompositeDisposable(binding, connection);
        }
		public bool BeginTransaction ()
		{
			if (inTransaction)
				throw new InvalidOperationException ("Already in a transaction");
			
			transactionLock = LockWrite ();
			try {
				updatingLock = new FileStream (UpdateDatabaseLockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
			} catch (IOException) {
				// The database is already being updated. Can't do anything for now.
				return false;
			} finally {
				transactionLock.Dispose ();
			}

			// Delete .new files that could have been left by an aborted database update
			
			transactionLock = LockRead ();
			CleanDirectory (rootDirectory);
			
			inTransaction = true;
			foldersToUpdate = new Hashtable ();
			deletedFiles = new Hashtable ();
			deletedDirs = new Hashtable ();
			return true;
		}
Ejemplo n.º 25
0
        public static void Open(params string[] hostUrls)
        {
            try
            {
                if (_CloseOWin == null)
                {
                    // Start OWIN host
                    StartOptions so = new StartOptions();
                    foreach (string s in hostUrls)
                    {
                        so.Urls.Add(s);
                    }
                    _CloseOWin = WebApp.Start<SNStartup>(so);
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException is System.Net.HttpListenerException)
                {
                    throw new Exception("监听IP有错误");
                }

                if (_CloseOWin != null)
                {
                    _CloseOWin.Dispose();//必须
                    _CloseOWin = null;//必须
                }

                throw;
            }
        }
        public AggregationViewModel()
        {
            var sourceList = new SourceList<AggregationItem>();

            sourceList.AddRange(Enumerable.Range(1, 15).Select(i => new AggregationItem(i)));

            //Load items to display to user and allow them to include items or not
         
            var listLoader = sourceList.Connect()
                .Sort(SortExpressionComparer<AggregationItem>.Ascending(vm => vm.Number))
                .ObserveOnDispatcher()
                .Bind(out _items)
                .Subscribe();

            // share the connection because we are doing multiple aggregations
            var aggregatable = sourceList.Connect()
                .FilterOnProperty(vm => vm.IncludeInTotal, vm => vm.IncludeInTotal)
                .Publish();

            //Do a custom aggregation (ToCollection() produces a readonly collection of underlying data)
            var sumOfOddNumbers = aggregatable.ToCollection()
                .Select(collection => collection.Where(i => i.Number%2 == 1).Select(ai => ai.Number).Sum())
                .Subscribe(sum => SumOfOddNumbers = sum);
            
            _cleanUp = new CompositeDisposable(sourceList, 
                listLoader,
                aggregatable.Count().Subscribe(count => Count = count),
                aggregatable.Sum(ai => ai.Number).Subscribe(sum => Sum = sum),
                aggregatable.Avg(ai => ai.Number).Subscribe(average => Avg = Math.Round(average,2)),
                aggregatable.Minimum(ai => ai.Number).Subscribe(max => Max = max),
                aggregatable.Maximum(ai => ai.Number).Subscribe(min => Min = min),
                aggregatable.StdDev(ai => ai.Number).Subscribe(std => StdDev = Math.Round(std, 2)),
                sumOfOddNumbers,
                aggregatable.Connect());
        }
 public void Add(IDisposable component)
 {
     if (component != null)
     {
         this.components.Add(component);
     }
 }
 /// <summary>
 ///   Initializes a new instance of the <see cref = "ItemAutoSubscription" /> class.
 /// </summary>
 /// <param name = "item">
 ///   The subscribed item.
 /// </param>
 /// <param name = "itemPosition">
 ///   The item position.
 /// </param>
 /// <param name = "itemRegion">
 ///   The item Region.
 /// </param>
 /// <param name = "subscription">
 ///   The subscription.
 /// </param>
 public ItemAutoSubscription(Item item, Vector itemPosition, Region itemRegion, IDisposable subscription)
 {
     this.ItemPosition = itemPosition;
     this.item = item;
     this.subscription = subscription;
     this.WorldRegion = itemRegion;
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SPOEmulationContext"/> class.
        /// </summary>
        /// <param name="isolationLevel">The level.</param>
        /// <param name="connectionInformation">The connection informations for the target web.</param>
        public SPOEmulationContext(IsolationLevel isolationLevel, ConnectionInformation connectionInformation)
        {
            this._isolationLevel = isolationLevel;

            switch (isolationLevel)
            {
                case IsolationLevel.Fake:
                    // create shim context
                    _shimsContext = ShimsContext.Create();

                    // initialize all simulated types
                    _clientContext = InitializeSimulatedAPI(connectionInformation.Url);
                    break;
                case IsolationLevel.Integration:
                    // create shim context
                    _shimsContext = ShimsContext.Create();
                    Connect(connectionInformation);
                    break;
                case IsolationLevel.None:
                    Connect(connectionInformation);
                    break;
                default:
                    throw new InvalidOperationException();
            }
        }
Ejemplo n.º 30
0
 public void Connect(IEventStream stream)
 {
     subscription = stream.Of<IEventPattern<IDevice, ISensed>>().Subscribe(sensed =>
     {
         var type = topicRegistry.Find(sensed.EventArgs.Topic);
         switch (type)
         {
             case TopicType.Boolean:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Payload.ToBoolean(sensed.EventArgs.Payload), clock.Now));
                 break;
             case TopicType.Number:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Payload.ToNumber(sensed.EventArgs.Payload), clock.Now));
                 break;
             case TopicType.String:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Payload.ToString(sensed.EventArgs.Payload), clock.Now));
                 break;
             case TopicType.Void:
                 stream.Push(sensed.Sender, Impulse.Create(sensed.EventArgs.Topic, Unit.Default, clock.Now));
                 break;
             case TopicType.Unknown:
             default:
                 // TODO: throw? Report?
                 break;
         }
     });
 }
Ejemplo n.º 31
0
 internal unsafe MemoryMappedFileBlock(IDisposable accessor, SafeBuffer safeBuffer, long offset, int size)
 {
     _data = new DisposableData(accessor, safeBuffer, offset);
     _size = size;
 }
Ejemplo n.º 32
0
 public CarefulAccount(Log log, IResolverContext scope) : base(log)
 {
     _scope = scope;
 }
Ejemplo n.º 33
0
 public ObserveOn(ObserveOnObservable <T> parent, IObserver <T> observer, IDisposable cancel) : base(observer, cancel)
 {
     this.parent = parent;
 }
Ejemplo n.º 34
0
            public IDisposable Run()
            {
                IDisposable sourceDisposable = parent.source.Subscribe(this);

                return(StableCompositeDisposable.Create(sourceDisposable, isDisposed));
            }
Ejemplo n.º 35
0
 public ObserveOn_(ObserveOnObservable <T> parent, ISchedulerQueueing scheduler, IObserver <T> observer, IDisposable cancel) : base(observer, cancel)
 {
     this.parent     = parent;
     this.scheduler  = scheduler;
     this.isDisposed = new BooleanDisposable();
     this.onNext     = new Action <T>(OnNext_); // cache delegate
 }
Ejemplo n.º 36
0
        public SearchOptionsProxy([NotNull] SearchMetadata searchMetadata,
                                  [NotNull] IColourProvider colourProvider,
                                  [NotNull] IThemeProvider themeProvider,
                                  [NotNull] IconSelector iconSelector,
                                  [NotNull] Action <SearchMetadata> removeAction,
                                  [NotNull] IDefaultIconSelector defaultIconSelector,
                                  Guid parentId)
        {
            if (searchMetadata == null)
            {
                throw new ArgumentNullException(nameof(searchMetadata));
            }
            if (colourProvider == null)
            {
                throw new ArgumentNullException(nameof(colourProvider));
            }
            if (themeProvider == null)
            {
                throw new ArgumentNullException(nameof(themeProvider));
            }
            if (iconSelector == null)
            {
                throw new ArgumentNullException(nameof(iconSelector));
            }
            if (removeAction == null)
            {
                throw new ArgumentNullException(nameof(removeAction));
            }
            if (defaultIconSelector == null)
            {
                throw new ArgumentNullException(nameof(defaultIconSelector));
            }

            _searchMetadata      = searchMetadata;
            _defaultIconSelector = defaultIconSelector;

            IconSelector = iconSelector;
            ParentId     = parentId;
            Highlight    = _searchMetadata.Highlight;
            Filter       = _searchMetadata.Filter;
            UseRegex     = searchMetadata.UseRegex;
            IgnoreCase   = searchMetadata.IgnoreCase;
            Position     = searchMetadata.Position;
            Hues         = colourProvider.Hues;
            HighlightHue = searchMetadata.HighlightHue;

            ShowIconSelectorCommand = new Command(ShowIconSelector);
            RemoveCommand           = new Command(() => removeAction(searchMetadata));
            HighlightCommand        = new Command <Hue>(newHue =>
            {
                HighlightHue = newHue;
            });

            IconKind = _searchMetadata.IconKind.ParseEnum <PackIconKind>()
                       .ValueOr(() => PackIconKind.ArrowRightBold);

            //combine system with user choice.
            var defaultHue = this.WhenValueChanged(vm => vm.HighlightHue)
                             .CombineLatest(themeProvider.Accent, (user, system) => user == Hue.NotSpecified ? system : user).Publish();

            Foreground = defaultHue.Select(h => h.ForegroundBrush).ForBinding();
            Background = defaultHue.Select(h => h.BackgroundBrush).ForBinding();

            _cleanUp = new CompositeDisposable(IconSelector, Foreground, Background, defaultHue.Connect());
        }
Ejemplo n.º 37
0
 public void AddDisposable(IDisposable disposable)
 {
     _disposables.Add(disposable);
 }
Ejemplo n.º 38
0
 /// <summary>
 /// Inicializa una nueva instancia de la clase <see cref="RequestServer"/>
 /// </summary>
 /// <param name="baseAddress">String que indica la dirección en la que se van a encontrar los controladores</param>
 public RequestServer(string baseAddress)
 {
     this.baseAddress = string.Format("http://*:5800/{0},https://*:5801/{0}", baseAddress);
     httpServiceHost  = StartHttp();
 }
Ejemplo n.º 39
0
 public _(GroupByUntil <TSource, TKey, TElement, TDuration> parent, IObserver <IGroupedObservable <TKey, TElement> > observer, IDisposable cancel)
     : base(observer, cancel)
 {
     _parent   = parent;
     _map      = new Map <TKey, ISubject <TElement> >(_parent._capacity, _parent._comparer);
     _nullGate = new object();
 }
Ejemplo n.º 40
0
 public L(K k, IResolverContext scope)
 {
     K     = k;
     Scope = scope;
 }
Ejemplo n.º 41
0
        public void Security_AuthorizeEndpointTests(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var applicationUrl = deployer.Deploy(hostType, AuthServerHappyPathConfiguration);

                IDisposable clientEndpoint = null;
                try
                {
                    clientEndpoint = WebApp.Start(Client_Redirect_Uri, app => app.Run(context => { return(context.Response.WriteAsync(context.Request.QueryString.Value)); }));

                    string tokenEndpointUri = applicationUrl + "TokenEndpoint";
                    var    basicClient      = new HttpClient();
                    var    headerValue      = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", "123", "invalid")));
                    basicClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", headerValue);

                    HttpClient          httpClient          = new HttpClient();
                    string              requestUri          = null;
                    Uri                 landingUri          = null;
                    Uri                 applicationUri      = new Uri(applicationUrl);
                    HttpResponseMessage httpResponseMessage = null;

                    //Happy path - response_type:code
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Happy path - response_type:token
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "token", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    landingUri = new Uri(landingUri.AbsoluteUri.Replace('#', '?'));
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["access_token"]);
                    Assert.NotNull(landingUri.ParseQueryString()["expires_in"]);
                    Assert.Equal <string>("bearer", landingUri.ParseQueryString()["token_type"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);

                    //Invalid redirect URI - pass error to application
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_passonerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>("error: invalid_request\r\n", httpResponseMessage.Content.ReadAsStringAsync().Result);
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");

                    //Invalid redirect URI - Display error by middleware
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", "invalid_uri_displayerror", "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //What happens if we don't set Validated explicitly. Send an invalid clientId => We don't set Validated for this case.
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "token", "invalidClient", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //OnValidateAuthorizeRequest - Rejecting a request. Send an invalid state as we validate it there. Client should receive all the error code & description that we send
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "invalidstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    landingUri          = httpResponseMessage.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("state.invalid", landingUri.ParseQueryString()["error"]);
                    Assert.Equal <string>("state.invaliddescription", landingUri.ParseQueryString()["error_description"]);
                    Assert.Equal <string>("state.invaliduri", landingUri.ParseQueryString()["error_uri"]);
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error=state.invalid&error_description=state.invaliddescription&error_uri=state.invaliduri"), "Did not receive an error when provider did not set Validated");

                    //Missing response_type
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, null, "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("invalid_request", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Unsupported response_type
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "invalid_response_type", "123", Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.Equal <string>(Client_Redirect_Uri, httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Path));
                    Assert.Equal <string>("unsupported_response_type", httpResponseMessage.RequestMessage.RequestUri.ParseQueryString()["error"]);

                    //Missing client_id
                    requestUri          = AuthZ.CreateAuthZUri(applicationUrl, "token", null, Client_Redirect_Uri, "scope1", "validstate");
                    httpResponseMessage = httpClient.GetAsync(requestUri).Result;
                    Assert.True(httpResponseMessage.RequestMessage.RequestUri.GetLeftPart(UriPartial.Authority).StartsWith(applicationUri.GetLeftPart(UriPartial.Authority)), "Should not be redirected on invalid redirect_uri");
                    Assert.True(httpResponseMessage.Content.ReadAsStringAsync().Result.StartsWith("error: invalid_request"), "Did not receive an error for an invalid redirect_uri");

                    //Missing state - Should succeed
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", null);
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <bool>(false, landingUri.ParseQueryString().ContainsKey("state"));

                    //Token endpoint tests
                    //Invalid client (client_id, client_secret) - As form parameters
                    var formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "invalid") });
                    var responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    var jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_client", jToken.SelectToken("error").Value <string>());

                    //Invalid client (client_id, client_secret) - As Basic auth headers
                    responseMessage = basicClient.GetAsync(tokenEndpointUri).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_client", jToken.SelectToken("error").Value <string>());

                    //grant_type=authorization_code - invalid code being sent
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", "InvalidCode"), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_grant", jToken.SelectToken("error").Value <string>());

                    //grant_type=authorization_code - Full scenario
                    requestUri = AuthZ.CreateAuthZUri(applicationUrl, "code", "123", Client_Redirect_Uri, "scope1", "validstate");
                    landingUri = httpClient.GetAsync(requestUri).Result.RequestMessage.RequestUri;
                    Assert.Equal <string>(Client_Redirect_Uri, landingUri.GetLeftPart(UriPartial.Path));
                    Assert.NotNull(landingUri.ParseQueryString()["code"]);
                    Assert.Equal <string>("validstate", landingUri.ParseQueryString()["state"]);
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "authorization_code"), new kvp("code", landingUri.ParseQueryString()["code"]), new kvp("redirect_uri", Client_Redirect_Uri) });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=password -- Resource owner credentials -- Invalid credentials
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "invalid"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.Equal <string>("invalid_grant", jToken.SelectToken("error").Value <string>());

                    //grant_type=password -- Resource owner credentials
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "password"), new kvp("username", "user1"), new kvp("password", "password1"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=refresh_token -- Use the refresh token issued on the previous call
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "refresh_token"), new kvp("refresh_token", jToken.SelectToken("refresh_token").Value <string>()), new kvp("scope", "scope1 scope2") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                    Assert.NotNull(jToken.SelectToken("refresh_token").Value <string>());

                    //grant_type=client_credentials - Bug# https://github.com/Katana/katana/issues/562
                    formContent     = AuthZ.CreateTokenEndpointContent(new[] { new kvp("client_id", "123"), new kvp("client_secret", "secret123"), new kvp("grant_type", "client_credentials"), new kvp("scope", "scope1 scope2 scope3") });
                    responseMessage = httpClient.PostAsync(tokenEndpointUri, formContent).Result.Content.ReadAsStringAsync().Result;
                    jToken          = JToken.Parse(responseMessage);
                    Assert.NotNull(jToken.SelectToken("access_token").Value <string>());
                    Assert.Equal <string>("bearer", jToken.SelectToken("token_type").Value <string>());
                    Assert.NotNull(jToken.SelectToken("expires_in").Value <string>());
                    Assert.Equal <string>("value1", jToken.SelectToken("param1").Value <string>());
                    Assert.Equal <string>("value2", jToken.SelectToken("param2").Value <string>());
                }
                finally
                {
                    //Finally close the client endpoint
                    if (clientEndpoint != null)
                    {
                        clientEndpoint.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 42
0
        protected override IDisposable Run(IObserver <IGroupedObservable <TKey, TElement> > observer, IDisposable cancel, Action <IDisposable> setSink)
        {
            _groupDisposable    = new CompositeDisposable();
            _refCountDisposable = new RefCountDisposable(_groupDisposable);

            var sink = new _(this, observer, cancel);

            setSink(sink);
            _groupDisposable.Add(_source.SubscribeSafe(sink));

            return(_refCountDisposable);
        }
Ejemplo n.º 43
0
        void DoDuplicateUrl(string url)
        {
            var tests = new DupeUrlTest[] {
                new DupeUrlTest(
                    null,
                    () => Factory.PublisherCreate(url).Unwrap(),
                    false),
                new DupeUrlTest(
                    null,
                    () => Factory.PullerCreate(url, true).Unwrap(),
                    false),
                new DupeUrlTest(
                    () => Factory.PusherCreate(url, true).Unwrap(),
                    () => Factory.PullerCreate(url, false).Unwrap(),
                    true),
                new DupeUrlTest(
                    null,
                    () => Factory.PusherCreate(url, true).Unwrap(),
                    false),
                new DupeUrlTest(
                    () => Factory.PullerCreate(url, true).Unwrap(),
                    () => Factory.PusherCreate(url, false).Unwrap(),
                    true),
                new DupeUrlTest(
                    null,
                    () => Factory.ReplierCreate(url).Unwrap(),
                    false),
                new DupeUrlTest(
                    () => Factory.ReplierCreate(url).Unwrap(),
                    () => Factory.RequesterCreate(url).Unwrap(),
                    true),
                new DupeUrlTest(
                    () => Factory.PublisherCreate(url).Unwrap(),
                    () => Factory.SubscriberCreate(url).Unwrap(),
                    true),
            };

            for (int i = 0; i < tests.Length; ++i)
            {
                var         test = tests[i];
                IDisposable pre  = null;
                IDisposable obj0 = null;
                IDisposable obj1 = null;
                try
                {
                    if (test.pre != null)
                    {
                        pre = test.pre.Invoke();
                        Assert.NotNull(pre);
                    }
                    obj0 = test.func();
                    if (test.isOk)
                    {
                        obj1 = test.func();
                        Assert.NotNull(obj1);
                    }
                    else
                    {
                        Assert.ThrowsAny <Exception>(() => obj1 = test.func());
                    }
                }
                finally
                {
                    pre?.Dispose();
                    obj0?.Dispose();
                    obj1?.Dispose();
                }
            }
        }
 public void TestInitialize()
 {
     _shimObject = ShimsContext.Create();
 }
 private ClientRequestActivity()
 {
     _relatedActivityId = ActivityStack.Id;
     _popWhenDispose    = ActivityStack.Push(_activityId);
 }
Ejemplo n.º 46
0
        public override Expression VisitSelect(SelectExpression selectExpression)
        {
            Check.NotNull(selectExpression, nameof(selectExpression));

            IDisposable subQueryIndent = null;

            if (selectExpression.Alias != null)
            {
                _rcbsql.AppendLine("(");

                subQueryIndent = _rcbsql.Indent();
            }

            _rcbsql.Append("SELECT ");

            var projectionAdded = false;

            if (selectExpression.IsProjectStar)
            {
                _rcbsql.Append("*");
                projectionAdded = true;
            }

            if (selectExpression.Projection.Count > 0)
            {
                if (selectExpression.IsProjectStar)
                {
                    _rcbsql.Append(", ");
                }

                for (int i = 0; i < selectExpression.Projection.Count; i++)
                {
                    var col = (ColumnExpression)selectExpression.Projection[i];
                    _rcbsql.Append($"{col.Name} ");
                    if (i < selectExpression.Projection.Count - 1)
                    {
                        _rcbsql.Append(", ");
                    }
                }
                projectionAdded = true;
            }

            if (!projectionAdded)
            {
                _rcbsql.Append("1");
            }

            if (selectExpression.Tables.Count > 0)
            {
                _rcbsql.AppendLine()
                .Append("FROM ");

                GenerateList(selectExpression.Tables, tx =>
                {
                    var te     = ((TableExpression)tx);
                    var schema = string.IsNullOrEmpty(te.Schema) ? __taosConnectionStringBuilder.DataBase : te.Schema;
                    _rcbsql.Append($"{schema}.{te.Table}");
                }, null);
            }
            else
            {
                GeneratePseudoFromClause();
            }

            if (selectExpression.Predicate != null)
            {
                GeneratePredicate(selectExpression.Predicate);
            }

            if (selectExpression.GroupBy.Count > 0)
            {
                _rcbsql.AppendLine();

                _rcbsql.Append("GROUP BY ");
                GenerateList(selectExpression.GroupBy);
            }

            if (selectExpression.Having != null)
            {
                GenerateHaving(selectExpression.Having);
            }

            if (selectExpression.OrderBy.Count > 0)
            {
                var orderByList = new List <Ordering>(selectExpression.OrderBy);

                // Filter out constant and parameter expressions (SELECT 1) if there is no skip or take #10410
                if (selectExpression.Limit == null && selectExpression.Offset == null)
                {
                    //   orderByList.RemoveAll(o => IsOrderByExpressionConstant(ApplyOptimizations(o.Expression, searchCondition: false)));
                }

                if (orderByList.Count > 0)
                {
                    _rcbsql.AppendLine();

                    GenerateOrderBy(orderByList);
                }
            }

            GenerateLimitOffset(selectExpression);

            if (subQueryIndent != null)
            {
                subQueryIndent.Dispose();

                _rcbsql.AppendLine()
                .Append(")");

                if (selectExpression.Alias.Length > 0)
                {
                    _rcbsql
                    .Append(AliasSeparator)
                    .Append(SqlGenerator.DelimitIdentifier(selectExpression.Alias));
                }
            }

            return(selectExpression);
        }
Ejemplo n.º 47
0
        public void Start(int interval)
        {
            var task = Observable.Timer(TimeSpan.Zero, TimeSpan.FromHours(interval));

            subscription = task.Subscribe(DownloadImage);
        }
Ejemplo n.º 48
0
 public void Stop()
 {
     subscription.Dispose();
     subscription = null;
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Take responsibility for a new queues that was assigned to me via a new range.
        /// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer.
        /// ERROR HANDLING:
        ///     The resposibility to handle initializatoion and shutdown failures is inside the INewQueueAdapterReceiver code.
        ///     The agent will call Initialize once and log an error. It will not call initiliaze again.
        ///     The receiver itself may attempt later to recover from this error and do initialization again.
        ///     The agent will assume initialization has succeeded and will subsequently start calling pumping receive.
        ///     Same applies to shutdown.
        /// </summary>
        /// <param name="qAdapter"></param>
        /// <param name="queueAdapterCache"></param>
        /// <param name="failureHandler"></param>
        /// <returns></returns>
        public async Task Initialize(Immutable <IQueueAdapter> qAdapter, Immutable <IQueueAdapterCache> queueAdapterCache, Immutable <IStreamFailureHandler> failureHandler)
        {
            if (qAdapter.Value == null)
            {
                throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
            }
            if (failureHandler.Value == null)
            {
                throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null");
            }

            logger.Info(ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.",
                        GetType().Name, GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode());

            // Remove cast once we cleanup
            queueAdapter               = qAdapter.Value;
            streamFailureHandler       = failureHandler.Value;
            lastTimeCleanedPubSubCache = DateTime.UtcNow;

            try
            {
                receiver = queueAdapter.CreateReceiver(QueueId);
            }
            catch (Exception exc)
            {
                logger.Error(ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc);
                return;
            }

            try
            {
                if (queueAdapterCache.Value != null)
                {
                    queueCache = queueAdapterCache.Value.CreateQueueCache(QueueId);
                }
            }
            catch (Exception exc)
            {
                logger.Error(ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc);
                return;
            }

            try
            {
                var task = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(config.InitQueueTimeout));
                task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, String.Format("QueueAdapterReceiver {0} failed to Initialize.", QueueId.ToStringWithHashCode()));
                await task;
            }
            catch
            {
                // Just ignore this exception and proceed as if Initialize has succeeded.
                // We already logged individual exceptions for individual calls to Initialize. No need to log again.
            }
            // Setup a reader for a new receiver.
            // Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization.
            var randomTimerOffset = safeRandom.NextTimeSpan(config.GetQueueMsgsTimerPeriod);

            timer = base.RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, config.GetQueueMsgsTimerPeriod);

            logger.Info((int)ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode());
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Subscribes to progress reports.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="disposables">The disposables.</param>
        /// <param name="mergeType">Type of the merge.</param>
        protected virtual void SubscribeToProgressReports(long id, CompositeDisposable disposables, MergeType mergeType)
        {
            fileMergeProgressHandler?.Dispose();
            modCompressProgressHandler?.Dispose();
            freeSpaceCheckHandler?.Dispose();

            freeSpaceCheckHandler = modMergeFreeSpaceCheckHandler.Subscribe(s =>
            {
                var message         = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.DiskInfoOverlay);
                var overlayProgress = Smart.Format(localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Overlay_Progress), new
                {
                    PercentDone = s.Percentage.ToLocalizedPercentage(),
                    Count       = 1,
                    TotalCount  = 3
                });
                TriggerOverlay(id, true, message, overlayProgress);
            }).DisposeWith(disposables);

            if (mergeType == MergeType.Basic)
            {
                fileMergeProgressHandler = modFileMergeProgressHandler.Subscribe(s =>
                {
                    string message;
                    if (s.Step == 1)
                    {
                        message = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Basic.Overlay_Gathering_Mod_Info);
                    }
                    else
                    {
                        message = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Basic.Overlay_Writing_Files);
                    }
                    var overlayProgress = Smart.Format(localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Overlay_Progress), new
                    {
                        PercentDone = s.Percentage.ToLocalizedPercentage(),
                        Count       = s.Step + 1,
                        TotalCount  = 3
                    });
                    TriggerOverlay(id, true, message, overlayProgress);
                }).DisposeWith(disposables);
            }
            else
            {
                modCompressProgressHandler = modCompressMergeProgressHandler.Subscribe(s =>
                {
                    string message;
                    if (s.Step == 1)
                    {
                        message = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Compress.Overlay_Gathering_Mod_Info);
                    }
                    else
                    {
                        message = localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Compress.Overlay_Compressing_Files);
                    }
                    var overlayProgress = Smart.Format(localizationManager.GetResource(LocalizationResources.Collection_Mods.MergeCollection.Overlay_Progress), new
                    {
                        PercentDone = s.Percentage.ToLocalizedPercentage(),
                        Count       = s.Step + 1,
                        TotalCount  = 3
                    });
                    TriggerOverlay(id, true, message, overlayProgress);
                }).DisposeWith(disposables);
            }
        }
Ejemplo n.º 51
0
        public void Release <T>(T component)
        {
            IDisposable disposable = component as IDisposable;

            disposable?.Dispose();
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Constructs a new SingleInstance object
        /// </summary>
        /// <param name="appname">The application name</param>
        /// <param name="basefolder">The folder in which the control file structure is placed</param>
        public SingleInstance(string appname, string basefolder)
        {
            if (!System.IO.Directory.Exists(basefolder))
            {
                System.IO.Directory.CreateDirectory(basefolder);
            }

            m_controldir = System.IO.Path.Combine(basefolder, CONTROL_DIR);
            if (!System.IO.Directory.Exists(m_controldir))
            {
                System.IO.Directory.CreateDirectory(m_controldir);
            }

            m_lockfilename = System.IO.Path.Combine(m_controldir, CONTROL_FILE);
            m_file         = null;

            System.IO.Stream temp_fs = null;

            try
            {
                if (Library.Utility.Utility.IsClientLinux)
                {
                    temp_fs = UnixSupport.File.OpenExclusive(m_lockfilename, System.IO.FileAccess.Write);
                }
                else
                {
                    temp_fs = System.IO.File.Open(m_lockfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
                }

                if (temp_fs != null)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(temp_fs);
                    sw.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Id);
                    sw.Flush();
                    //Do not dispose sw as that would dispose the stream
                    m_file = temp_fs;
                }
            }
            catch
            {
                if (temp_fs != null)
                {
                    try { temp_fs.Dispose(); }
                    catch {}
                }
            }

            //If we have write access
            if (m_file != null)
            {
                m_filewatcher                     = new System.IO.FileSystemWatcher(m_controldir);
                m_filewatcher.Created            += new System.IO.FileSystemEventHandler(m_filewatcher_Created);
                m_filewatcher.EnableRaisingEvents = true;

                DateTime startup = System.IO.File.GetLastWriteTime(m_lockfilename);

                //Clean up any files that were created before the app launched
                foreach (string s in System.IO.Directory.GetFiles(m_controldir))
                {
                    if (s != m_lockfilename && System.IO.File.GetCreationTime(s) < startup)
                    {
                        try { System.IO.File.Delete(s); }
                        catch { }
                    }
                }
            }
            else
            {
                //Wait for the initial process to signal that the filewatcher is activated
                int retrycount = 5;
                while (retrycount > 0 && new System.IO.FileInfo(m_lockfilename).Length == 0)
                {
                    System.Threading.Thread.Sleep(500);
                    retrycount--;
                }

                //HACK: the unix file lock does not allow us to read the file length when the file is locked
                if (new System.IO.FileInfo(m_lockfilename).Length == 0)
                {
                    if (!Library.Utility.Utility.IsClientLinux)
                    {
                        throw new Exception("The file was locked, but had no data");
                    }
                }

                //Notify the other process that we have started
                string filename = System.IO.Path.Combine(m_controldir, COMM_FILE_PREFIX + Guid.NewGuid().ToString());

                //Write out the commandline arguments
                string[] cmdargs = System.Environment.GetCommandLineArgs();
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Library.Utility.Utility.IsClientLinux ? UnixSupport.File.OpenExclusive(filename, System.IO.FileAccess.Write) : new System.IO.FileStream(filename, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None)))
                    for (int i = 1; i < cmdargs.Length; i++) //Skip the first, as that is the filename
                    {
                        sw.WriteLine(cmdargs[i]);
                    }

                //Wait for the other process to delete the file, indicating that it is processed
                retrycount = 5;
                while (retrycount > 0 && System.IO.File.Exists(filename))
                {
                    System.Threading.Thread.Sleep(500);
                    retrycount--;
                }

                //This may happen if the other process is closing as we write the command
                if (System.IO.File.Exists(filename))
                {
                    //Try to clean up, so the other process does not spuriously show this
                    try { System.IO.File.Delete(filename); }
                    catch { }

                    throw new Exception("The lock file was locked, but the locking process did not respond to the start command");
                }
            }
        }
Ejemplo n.º 53
0
 public FakedClass(IDisposable someInterface)
 {
     ParameterListLengthsForAttemptedConstructors.Add(1);
 }
Ejemplo n.º 54
0
 public void Add(IDisposable instance)
 {
     disposables.Add(new WeakReference(instance));
 }
Ejemplo n.º 55
0
 public override void MyTestInitialize()
 {
     base.MyTestInitialize();
     m_PresenterTransaction = PresenterFactory.BeginSharedPresenterTransaction(m_Container, new BaseForm());
 }
Ejemplo n.º 56
0
 void SetKeepaliveTimer()
 {
     timerHandle?.Dispose();
     timerHandle = Observable.Timer(DateTimeOffset.Now.AddMilliseconds(keepAliveTimeout))
         .Subscribe(CheckKeepAlive);
 }
Ejemplo n.º 57
0
 public Cast(IObserver <TResult> observer, IDisposable cancel)
     : base(observer, cancel)
 {
 }
Ejemplo n.º 58
0
 public void StartServer()
 {
     _webServer = Microsoft.Owin.Hosting.WebApp.Start <Startup>(_url);
     _looper.Start();
     _dataMeterStateLooper.Start();
 }
Ejemplo n.º 59
0
 protected override IDisposable SubscribeCore(IObserver <TResult> observer, IDisposable cancel)
 {
     return(source.Subscribe(new Cast(observer, cancel)));
 }
Ejemplo n.º 60
0
 internal void AddDisposable(IDisposable disposable)
 {
     _Disposables.Add(disposable);
 }