/// <summary>
        /// Initialize cloud state
        /// </summary>
        public async Task InitAsync()
        {
            if (isInitialized)
            {
                return;
            }

            await semaphoreSlim.WaitAsync().ConfigureAwait(false);

            try
            {
                if (!isInitialized)
                {
                    await UpdateAsync().ConfigureAwait(false);

                    if (zooKeeper.getState() != ZooKeeper.States.CONNECTED && zooKeeper.getState() != ZooKeeper.States.CONNECTEDREADONLY)
                    {
                        throw new Exceptions.SolrNetCloudConnectionException($"Cannot connect to the Zookeeper instance {zooKeeperConnection}. Current state: {zooKeeper.getState()} ");
                    }

                    isInitialized = true;
                }
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Connects to the server with the provided details
        /// </summary>
        /// <param name="nick">Nickname to use</param>
        /// <param name="user">Username to use</param>
        /// <param name="realname">Real name to use</param>
        /// <param name="host">Host to which to connect</param>
        /// <param name="port">Port on which to connect</param>
        /// <param name="password">Password to send on connect</param>
        /// <returns></returns>
        public async Task Connect(String nick, String user, String realname, String host, int port = 6667, String password = null)
        {
            lock (_registrationLock)
            {
                Disconnect();
                // Establish connection
                Nick = nick; Username = user; RealName = realname; Host = host; Port = port; Password = password;
                TCP  = new TcpClient();
            }
            Task  connectTask = TCP.ConnectAsync(host, port);
            await connectTask;

            if (connectTask.Exception != null)
            {
                Exception = connectTask.Exception;
                if (OnException != null)
                {
                    foreach (var d in OnException.GetInvocationList())
                    {
                        var task = Task.Run(() => d.DynamicInvoke(this, connectTask.Exception));
                    }
                }
                throw connectTask.Exception; // If connect failed
            }

            Connected = true;

            // If connect succeeded

            streamReader = new System.IO.StreamReader(TCP.GetStream(), Encoding);
            streamWriter = new System.IO.StreamWriter(TCP.GetStream(), Encoding);

            // Register handler to on connect event
            OnRawMessageReceived += RegisterHandler;

            await _streamSemaphore.WaitAsync();

            try
            {
                var readLineTask = streamReader.ReadLineAsync().ContinueWith(OnAsyncRead);
            }
            catch (Exception e)
            {
                Exception = e;
                if (OnException != null)
                {
                    foreach (var d in OnException.GetInvocationList())
                    {
                        var task = Task.Run(() => d.DynamicInvoke(this, e));
                    }
                }
            }
            finally
            {
                _streamSemaphore.Release();
            }
        }
Ejemplo n.º 3
0
        public static async Task <PurchaseHistory> GetPurchaseHistory()
        {
            try
            {
                await semaphore.WaitAsync();

                if (Content != null)
                {
                    return(Content);
                }
                if (!System.IO.File.Exists(Path))
                {
                    return(Content = new PurchaseHistory());
                }
                try
                {
                    Content = await SerializationHelper.DeserializeAsync <PurchaseHistory>(Path);

                    if (Content != null)
                    {
                        return(Content);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Failed to load'{0}'", Path));
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                try
                {
                    Content = await SerializationHelper.DeserializeAsync <PurchaseHistory>(PathBup);

                    if (System.IO.File.Exists(Path))
                    {
                        System.IO.File.Delete(Path);
                    }
                    if (System.IO.File.Exists(PathBup))
                    {
                        System.IO.File.Move(PathBup, Path);
                    }
                    return(Content = Content ?? new PurchaseHistory());
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(String.Format("Failed to load'{0}'", PathBup));
                    System.Diagnostics.Debug.WriteLine(e.Message);
                }
                return(Content = new PurchaseHistory());
            }
            finally
            {
                semaphore.Release();
            }
        }
Ejemplo n.º 4
0
            public KeyValueItemBar()
            {
                this.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(1, GridUnitType.Star)
                });
                this.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(2, GridUnitType.Star)
                });
                this.ColumnDefinitions.Add(new ColumnDefinition {
                    Width = new GridLength(40, GridUnitType.Absolute)
                });
                {
                    ETkey = new MyEntry();
                    ETkey.SetBinding(MyEntry.TextProperty, "Key", BindingMode.TwoWay);
                    this.Children.Add(ETkey, 0, 0);
                }
                {
                    ETvalue = new MyEntry();
                    ETvalue.SetBinding(MyEntry.TextProperty, "Value", BindingMode.TwoWay);
                    this.Children.Add(ETvalue, 1, 0);
                }
                {
                    BTNcancel          = new MyButton("\u2716");//✖
                    BTNcancel.Clicked += async delegate
                    {
                        if (this.BindingContext != null) // && await MyLogger.Ask($"Remove this item?\r\nKey: {ETkey.Text}\r\nValue: {ETvalue.Text}"))
                        {
                            await(this.BindingContext as MyControls.BarsListPanel.MyDisposable).OnDisposed();
                        }
                    };
                    this.Children.Add(BTNcancel, 2, 0);
                }
                System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
                this.Appeared += async(sender) =>
                {
                    this.Opacity = 0;
                    await semaphoreSlim.WaitAsync();

                    //this.Opacity = 1;
                    await this.FadeTo(1, 500);

                    lock (semaphoreSlim) semaphoreSlim.Release();
                };
                this.Disappearing = new Func <Task>(async() =>
                {
                    await semaphoreSlim.WaitAsync();
                    //this.Opacity = 0;
                    await this.FadeTo(0, 500);
                    lock (semaphoreSlim) semaphoreSlim.Release();
                });
            }
Ejemplo n.º 5
0
        /// <summary>
        /// This is the event handler for PrintDocument.Paginate. It creates print preview pages for the app.
        /// </summary>
        /// <param name="sender">PrintDocument</param>
        /// <param name="e">Paginate Event  </param>
        public virtual async void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
        {
            var paperSize = e.PrintTaskOptions.GetPageDescription(0).PageSize;

            System.Diagnostics.Debug.WriteLine("CreatePrintPreviewPages: {" + paperSize.Width + "," + paperSize.Height + "}");

            //lock (printPreviewPages)
            await _semaphoreSlim.WaitAsync();

            {
                // Clear the cache of preview pages
                printPreviewPages.Clear();

                // Clear the print canvas of preview pages
                PrintCanvas.Children.Clear();

                // Get the PrintTaskOptions
                PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);

                // Get the page description to deterimine how big the page is
                PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);



                if (await GeneratePagesAsync(pageDescription) is List <UIElement> pages)
                {
                    foreach (var page in pages)
                    {
                        PrintCanvas.Children.Add(page);
                    }
                    PrintCanvas.InvalidateMeasure();
                    PrintCanvas.UpdateLayout();

                    await Task.Delay(1000);

                    printPreviewPages.AddRange(pages);
                    await Task.Delay(1000);
                }

                if (PreviewPagesCreated != null)
                {
                    PreviewPagesCreated.Invoke(printPreviewPages, null);
                }

                PrintDocument printDoc = (PrintDocument)sender;

                // Report the number of preview pages created
                printDoc.SetPreviewPageCount(printPreviewPages.Count, PreviewPageCountType.Intermediate);
            }
            _semaphoreSlim.Release();
        }
Ejemplo n.º 6
0
        public async Task SetPressurePercent(double newPercent)
        {
            await pneumaticSemaphore.WaitAsync();

            try
            {
                var deltaPercent = newPercent - PressurePercent;

                if (deltaPercent > 0)
                {
                    // Requires inflation
                    var inflationDurationS = deltaPercent / pneumatic.InflationRatePctPerS;
                    if (newPercent >= 1)
                    {
                        inflationDurationS += 0.25 / pneumatic.InflationRatePctPerS;    // Extra padding to ensure maximum inflation
                    }
                    await pneumatic.Inflate(inflationDurationS);
                }
                else if (deltaPercent < 0)
                {
                    var deflationDurationS = (-deltaPercent) / pneumatic.DeflationRatePctPerS;
                    if (newPercent <= 0)
                    {
                        deflationDurationS += 0.25 / pneumatic.DeflationRatePctPerS;    // Extra padding to ensure absolute zero
                    }
                    await pneumatic.Deflate(deflationDurationS);
                }
                this.PressurePercent = newPercent;
            }
            finally
            {
                pneumaticSemaphore.Release();
            }
        }
        public static Task ConcurrentConnectService <T>(IEnumerable <T> sourse, Func <T, Task> f, int max)
        {
            var initial = (max >> 1);
            var s       = new System.Threading.SemaphoreSlim(initial, max);

            _ = Task.Run(async() => {
                for (int i = initial; i < max; i++)
                {
                    await Task.Delay(100);
                    s.Release();
                }
            });
            return(Task.WhenAll(from item in sourse
                                select Task.Run(async() =>
            {
                await s.WaitAsync();
                try
                {
                    await f(item);
                }
                finally
                {
                    s.Release();
                }
            })));
        }
Ejemplo n.º 8
0
        private static async Task <BookInfo[]> LoadAsyncOne(Windows.Storage.StorageFile file, System.Threading.SemaphoreSlim sem)
        {
            if (file == null)
            {
                return(null);
            }

            await sem.WaitAsync();

            try
            {
                using (var s = (await file.OpenAsync(Windows.Storage.FileAccessMode.Read)).AsStream())
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(BookInfo[]));
                    return((BookInfo[])serializer.Deserialize(s));
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                sem.Release();
            }
        }
Ejemplo n.º 9
0
        public async Task FreeMemory()
        {
            for (int i = 0; i < _parallelCompilations; i++)
            {
                await _semaphore.WaitAsync();

                await _semaphoreCss.WaitAsync();
            }
            try
            {
                foreach (var compiler in _pool)
                {
                    compiler.Dispose();
                }
                _pool.Clear();
                foreach (var processor in _poolCss)
                {
                    processor.Dispose();
                }
                _poolCss.Clear();
            }
            finally
            {
                for (int i = 0; i < _parallelCompilations; i++)
                {
                    _semaphore.Release();
                    _semaphoreCss.Release();
                }
            }
        }
Ejemplo n.º 10
0
        public static async Task <T> DeserializeAsync <T>(Windows.Storage.StorageFolder folder, string fileName, System.Threading.SemaphoreSlim semaphore) where T : class
        {
            await semaphore.WaitAsync();

            try
            {
                if (await folder.TryGetItemAsync(fileName) is Windows.Storage.StorageFile f)
                {
                    using (var s = (await f.OpenAsync(Windows.Storage.FileAccessMode.Read)).AsStream())
                    {
                        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                        return((T)serializer.Deserialize(s));
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
            finally
            {
                semaphore.Release();
            }
        }
Ejemplo n.º 11
0
        public async Task ProcessExecutionTraceAnalysis(ExecutionTraceAnalysis traceAnalysis)
        {
            // Obtain our thread ID
            int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

            // Create a thread state for this thread
            MeadowDebugAdapterThreadState threadState = new MeadowDebugAdapterThreadState(traceAnalysis, threadId);

            // Acquire the semaphore for processing a trace.
            await _processTraceSemaphore.WaitAsync();

            // Set the thread state in our lookup
            ThreadStates[threadId] = threadState;

            // Send an event that our thread has exited.
            Protocol.SendEvent(new ThreadEvent(ThreadEvent.ReasonValue.Started, threadState.ThreadId));

            // Continue our execution.
            ContinueExecution(threadState, DesiredControlFlow.Continue);

            // Lock execution is complete.
            await threadState.Semaphore.WaitAsync();

            // Remove the thread from our lookup.
            ThreadStates.Remove(threadId, out _);

            // Unlink our data for our thread id.
            ReferenceContainer.UnlinkThreadId(threadId);

            // Send an event that our thread has exited.
            Protocol.SendEvent(new ThreadEvent(ThreadEvent.ReasonValue.Exited, threadState.ThreadId));

            // Release the semaphore for processing a trace.
            _processTraceSemaphore.Release();
        }
Ejemplo n.º 12
0
        private static async void AnalyticsManager_OnUpdate()
        {
            await analyticsUpdateSyncRoot.WaitAsync();

            try
            {
                var updates = new Dictionary <BaseSubscription, SubscriptionUpdateBase>();
                foreach (var subscription in InfoConnectionManager.GetActiveSubscriptions())
                {
                    var update = default(SubscriptionUpdateBase);
                    switch (subscription)
                    {
                    case DepthsSubscription depthsSubscription:
                    {
                        var depth = AnalyticsManager.MarketDepthsManager.GetDepth(depthsSubscription.Market, depthsSubscription.Precision);
                        update = MarketDepthUpdate.Generate(depth, depthsSubscription.Name);
                    }
                    break;

                    case PriceHistorySubscription priceHistorySubscription:
                    {
                        var priceFrames = await AnalyticsManager.PriceHistoryManager.GetPriceHistory(0, priceHistorySubscription.Market, priceHistorySubscription.FramePeriod);

                        update = PriceHistoryUpdate.Generate(priceFrames.frames, priceHistorySubscription.Name);
                    }
                    break;

                    case TradesFeedSubscription tradesFeedSubscription:
                    {
                        var trades = AnalyticsManager.TradesHistoryManager.GetTrades(tradesFeedSubscription.Market);
                        update = TradesFeedUpdate.Generate(trades, tradesFeedSubscription.Name);
                    }
                    break;

                    case AllMarketTickersSubscription allMarketTickersSubscription:
                    {
                        var allTickers = AnalyticsManager.MarketTickersManager.GetAllTickers();
                        update = AllTickersUpdate.Generate(allTickers, allMarketTickersSubscription.Name);
                    }
                    break;

                    case MarketTickerSubscription marketTickerSubscription:
                    {
                        var marketTicker = AnalyticsManager.MarketTickersManager.GetMarketTicker(marketTickerSubscription.Market);
                        update = MarketTickerUpdate.Generate(marketTicker, marketTickerSubscription.Name);
                    }
                    break;
                    }
                    if (update != null)
                    {
                        updates.Add(subscription, update);
                    }
                }
                InfoConnectionManager.SendSubscriptionUpdates(updates);
            }
            finally
            {
                analyticsUpdateSyncRoot.Release();
            }
        }
Ejemplo n.º 13
0
        public static async Task SerializeAsync <T>(T data, string path)
        {
            await semaphore.WaitAsync();

            try
            {
                var xs = new XmlSerializer(typeof(T));
                using (var sw = new StreamWriter(path))
                {
                    await Task.Run(() => { try { xs.Serialize(sw, data); } catch { } });
                }
            }
            finally
            {
                semaphore.Release();
            }
        }
Ejemplo n.º 14
0
        // シリアライズする
        public static async Task SerializeAsync <T>(T data, string filePath)
        {
            await _semaphore.WaitAsync(); // ロックを取得する

            try
            {
                var xmlSerializer = CachingXmlSerializerFactory.Create(typeof(T));
                using (var streamWriter = new StreamWriter(filePath, false, new UTF8Encoding(false)))
                {
                    await Task.Run(() => xmlSerializer.Serialize(streamWriter, data));

                    await streamWriter.FlushAsync();  // .NET Framework 4.5以降
                }
            }
            finally
            {
                _semaphore.Release(); // ロックを解放する
            }
        }
Ejemplo n.º 15
0
        public static async System.Threading.Tasks.Task StdErrLogAsync(string message, EventLogEntryType eventLogEntryType)
        {
            await consoleErrorLock.WaitAsync();

            try {
                await System.Console.Error.WriteLineAsync(GetConsoleLogString(message, eventLogEntryType));
            }
            finally {
                consoleErrorLock.Release();
            }
        }
Ejemplo n.º 16
0
        public FileTransferContentView()
        {
            System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
            var newTaskCreatedEventHandler = new CloudFile.Networker.NewTaskCreatedEventHandler((networker) =>
            {
                OnStatusEnter(networker, previousStatus[networker] = networker.Status);
                var statusChangedEventHandler = new CloudFile.Networker.NetworkStatusChangedEventHandler(async() =>
                {
                    await semaphoreSlim.WaitAsync();
                    OnStatusLeave(networker, previousStatus[networker]);
                    OnStatusEnter(networker, previousStatus[networker] = networker.Status);
                    lock (semaphoreSlim) semaphoreSlim.Release();
                    if (networker.Status == CloudFile.Networker.NetworkStatus.ErrorNeedRestart)
                    {
                        if (todoWhenTaskFailed != null)
                        {
                            await todoWhenTaskFailed(networker);
                        }
                    }
                });
                networker.StatusChanged += statusChangedEventHandler;
                var data = new NetworkingItemBarViewModel(networker);
                MyControls.BarsListPanel.MyDisposable.MyDisposableEventHandler dataDisposedEventHandler = null;
                dataDisposedEventHandler = new MyControls.BarsListPanel.MyDisposable.MyDisposableEventHandler(async delegate
                {
                    networker.StatusChanged -= statusChangedEventHandler;
                    data.Disposed           -= dataDisposedEventHandler;
                    await semaphoreSlim.WaitAsync();
                    OnStatusLeave(networker, previousStatus[networker]);
                    previousStatus.Remove(networker);
                    lock (semaphoreSlim) semaphoreSlim.Release();
                });
                data.Disposed += dataDisposedEventHandler;
                this.PushBack(data);
            });

            CloudFile.Modifiers.FolderCreator.NewFolderCreateCreated    += newTaskCreatedEventHandler;
            CloudFile.Downloaders.FileDownloader.NewFileDownloadCreated += newTaskCreatedEventHandler;
            CloudFile.Uploaders.FileUploader.NewFileUploadCreated       += newTaskCreatedEventHandler;
            CloudFile.Uploaders.FolderUploader.NewFolderUploadCreated   += newTaskCreatedEventHandler;
        }
Ejemplo n.º 17
0
        private async void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem == null || !(e.SelectedItem is IWordViewModel))
            {
                return;
            }
            if (Pushing)
            {
                return;
            }
            try
            {
                Pushing = true;
                await WordsPageSemaphore.WaitAsync();

                if (!Pushing)
                {
                    return;
                }

                if (this.Model.Words.Count > 300)
                {
                    var page = new WordPage((IWordViewModel)e.SelectedItem);
                    await Navigation.PushAsync(page);
                }
                else
                {
                    var page = WordsPage;
                    try
                    {
                        await page.CanPushSemaphore.WaitAsync();

                        page.SelectedItem = (IWordViewModel)e.SelectedItem;
                        if (page.Parent == null)
                        {
                            await Navigation.PushAsync(page);
                        }
                    }
                    finally
                    {
                        page.CanPushSemaphore.Release();
                    }
                }
            }
            catch { }
            finally
            {
                WordsPageSemaphore.Release();
                Pushing = false;
            }

            (sender as ListView).SelectedItem = null;
        }
Ejemplo n.º 18
0
    static async Task F(int i)
    {
        Console.WriteLine($"F{i} starts on " + GetCurrentThreadId());
        await Semaphore.WaitAsync();

        Console.WriteLine($"F{i} continues on " + GetCurrentThreadId());
        await Task.Delay(6000);         //.ConfigureAwait(false); //<- uncomment to solve deadlock

        Console.WriteLine($"F{i} ends on " + GetCurrentThreadId());
        Semaphore.Release(1);
        //DeadLock();
    }
Ejemplo n.º 19
0
        public async Task <TData> GetAsync <TData>(CacheContentType type, string parameter = null)
        {
            await _cacheLock.WaitAsync();

            try
            {
                if (!_dataProviders.TryGetValue(type, out var dataProvider))
                {
                    throw new NoDataProviderException($"{type} data provider doesn't exist in cache.");
                }

                if (!_items.ContainsKey(new Tuple <CacheContentType, string>(type, parameter)))
                {
                    var data = await FetchDataFromProvider(dataProvider, parameter, null);

                    _items.TryAdd(new Tuple <CacheContentType, string>(type, parameter), new CacheItem(data));
                    _cacheItemsAdded++;

                    _logger.Info($"Cache data added ({type})");

                    ApplyPatches(type, data);
                    return((TData)data);
                }

                var cachedItem        = _items[new Tuple <CacheContentType, string>(type, parameter)];
                var lifetimeAttribute = type.GetEnumMemberAttribute <CacheLifetimeAttribute>(type);

                if ((DateTime.Now - cachedItem.UpdateTime).TotalMinutes >= lifetimeAttribute.Lifetime)
                {
                    var data = await FetchDataFromProvider(dataProvider, parameter, cachedItem.Data);

                    if (data != cachedItem.Data)
                    {
                        ApplyPatches(type, data);
                        cachedItem.Update(data);

                        _logger.Info($"Cache data updated ({type})");
                    }

                    _cacheItemsUpdated++;
                }
                else
                {
                    _cacheItemsHit++;
                }

                return((TData)cachedItem.Data);
            }
            finally
            {
                _cacheLock.Release();
            }
        }
Ejemplo n.º 20
0
        public async Task <MessageResult> Handle(CreateBooking message)
        {
            await semaphoreSlim.WaitAsync();

            try
            {
                // TODO validations etc.
                var startAt   = DateTime.Parse(message.StartAt);
                var serviceId = int.Parse(message.ServiceId);

                if (await unitOfWork.Exists <Booking>(b => b.StartAt == startAt && b.ServiceId == serviceId))
                {
                    throw new Domain.BookingAlreadyExists();
                }

                var createdUtc = DateTime.UtcNow;
                var booking    = new Booking
                {
                    Email            = message.Email,
                    Name             = message.Name,
                    Surname          = message.Surname,
                    Phone            = message.Phone,
                    BookingAt        = DateTime.Parse(message.BookingAt),
                    StartAt          = startAt,
                    ServiceId        = serviceId,
                    Quantity         = int.Parse(message.Quantity),
                    Price            = decimal.Parse(message.Price),
                    Comment          = message.Comment,
                    BookingCreatedAt = createdUtc,
                    Status           = (int)Domain.BookingStatus.Created
                };
                await unitOfWork.Add(booking);

                await unitOfWork.Save();

                var bookingCreated = new Domain.BookingCreated
                {
                    CreatedAt = createdUtc,
                    BookingId = booking.Id,
                };

                await unitOfWork.Add(BookingEvent.CreateFrom(bookingCreated));

                await unitOfWork.Save();

                return(new MessageResult(201, new { booking.Id }));
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
Ejemplo n.º 21
0
        public static async Task <Place> PlaceFromNameAsync(string name)
        {
            var newNumFormat = (System.Globalization.NumberFormatInfo)System.Globalization.NumberFormatInfo.CurrentInfo.Clone();

            newNumFormat.NumberDecimalSeparator = ".";      //tizedespont tizedesvessző helyett
            XDocument xdoc;
            await semaphore.WaitAsync();

            do
            {
                string content = "";        //üres string, hogy VisualStudio ne panaszkodjon
                bool   isValid = false;
                do
                {
                    try
                    {
                        content = await httpClient.GetStringAsync(geoLocApi + name);

                        isValid = true;
                        xdoc    = XDocument.Parse(content);
                    }
                    catch (HttpRequestException)
                    {
                        isValid = false;        //az kellene legyen alapból, de a biztonság kedvéért...
                        await Task.Delay(20);   //kis delay
                    }
                } while (!isValid);
                xdoc = XDocument.Parse(content);
            } while (xdoc.Root.Element("status").Value == "OVER_QUERY_LIMIT");
            semaphore.Release();
            if (xdoc.Root.Element("status").Value == "ZERO_RESULTS")
            {
                Console.WriteLine("Zero results: {0}", name);
                return(null);        //null-lal jelezzük, hogy nincs ilyen hely
            }
            string country;

            if (xdoc.Descendants("address_component").Descendants("type").Where(x => x.Value == "country").Count() != 0)
            {
                country = xdoc.Descendants("address_component").Descendants("type").Where(x => x.Value == "country").First().Parent.Element("long_name").Value;
            }
            else
            {
                country = "-";
            }
            return(new Place(
                       name,
                       country,
                       xdoc.Descendants("formatted_address").First().Value,
                       Convert.ToDouble(xdoc.Root.Descendants("location").First().Element("lat").Value, newNumFormat),
                       double.Parse(xdoc.Root.Descendants("location").First().Element("lng").Value, newNumFormat)));
        }
Ejemplo n.º 22
0
        private async Task ExclusiveAsync(Func <Task> funcAsync)
        {
            await _semaphore.WaitAsync();

            try
            {
                await funcAsync();
            }
            finally
            {
                _semaphore.Release();
            }
        }
        public async Task Run(Func <Task> handler)
        {
            await _semaphoreSlim.WaitAsync();

            try
            {
                await handler();
            }
            finally
            {
                _semaphoreSlim.Release();
            }
        }
Ejemplo n.º 24
0
        public NetworkingItemBar()
        {
            InitializeViews();
            System.Threading.SemaphoreSlim semaphoreSlim = new System.Threading.SemaphoreSlim(1, 1);
            this.Appeared += async(sender) =>
            {
                this.Opacity = 0;
                await semaphoreSlim.WaitAsync();

                //this.Opacity = 1;
                await this.FadeTo(1, 500);

                lock (semaphoreSlim) semaphoreSlim.Release();
            };
            this.Disappearing = new Func <Task>(async() =>
            {
                await semaphoreSlim.WaitAsync();
                //this.Opacity = 0;
                await this.FadeTo(0, 500);
                lock (semaphoreSlim) semaphoreSlim.Release();
            });
        }
Ejemplo n.º 25
0
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult> CopyAsync(System.String SourceBucketName, System.String[] SourceStorageFileNames, System.String TargetBucketName, System.String[] TargetStorageFileNames, System.Boolean Overwrite)
        {
            SoftmakeAll.SDK.CloudStorage.AWS.Environment.Validate();

            SoftmakeAll.SDK.OperationResult OperationResult = new SoftmakeAll.SDK.OperationResult();

            if ((System.String.IsNullOrWhiteSpace(SourceBucketName)) || (SourceStorageFileNames == null) || (SourceStorageFileNames.Length == 0) || (System.String.IsNullOrWhiteSpace(TargetBucketName)) || (TargetStorageFileNames == null) || (TargetStorageFileNames.Length == 0))
            {
                OperationResult.Message = "The SourceBucketName, SourceStorageFileNames, TargetBucketName and TargetStorageFileNames cannot be null.";
                return(OperationResult);
            }

            if (SourceStorageFileNames.Length != TargetStorageFileNames.Length)
            {
                OperationResult.Message = "The SourceStorageFileNames and TargetStorageFileNames must be the same length.";
                return(OperationResult);
            }

            try
            {
                using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(SourceStorageFileNames.Length))
                {
                    System.Collections.Generic.List <System.Threading.Tasks.Task> CopyTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                    for (System.Int32 i = 0; i < SourceStorageFileNames.Length; i++)
                    {
                        await SemaphoreSlim.WaitAsync();

                        CopyTasks.Add(System.Threading.Tasks.Task.Run(async() =>
                        {
                            await SoftmakeAll.SDK.CloudStorage.AWS.Environment._S3Client.CopyObjectAsync(new Amazon.S3.Model.CopyObjectRequest {
                                SourceBucket = SourceBucketName, SourceKey = SourceStorageFileNames[i], DestinationBucket = TargetBucketName, DestinationKey = TargetStorageFileNames[i]
                            });
                            SemaphoreSlim.Release();
                        }));
                    }

                    if (CopyTasks.Any())
                    {
                        await System.Threading.Tasks.Task.WhenAll(CopyTasks);
                    }
                }
            }
            catch (System.Exception ex)
            {
                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Initialize cloud state
        /// </summary>
        public async Task InitAsync()
        {
            if (isInitialized)
            {
                return;
            }

            await semaphoreSlim.WaitAsync().ConfigureAwait(false);

            try
            {
                if (!isInitialized)
                {
                    await UpdateAsync().ConfigureAwait(false);

                    isInitialized = true;
                }
            }
            finally
            {
                semaphoreSlim.Release();
            }
        }
Ejemplo n.º 27
0
        public static async Task RunAsync(this System.Threading.SemaphoreSlim semaphore, Func <Task> action,
                                          System.Threading.CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            try
            {
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
                await action().ConfigureAwait(false);
            }
            finally
            {
                semaphore.Release();
            }
        }
Ejemplo n.º 28
0
        private static async System.Threading.Tasks.Task fileLogAsync(string message, string entryType = "DEBUG")
        {
            if (CurrentLogLevel == LogLevel.Debug)
            {
                using (IsolatedStorageFile isoFile = GetIsolatedStorageFile()) {
                    await logFileLock.WaitAsync();

                    try {
                        //IsolatedStorage will be something like: C:\WINDOWS\system32\config\systemprofile\AppData\Local\IsolatedStorage\arpzpldm.neh\4hq14imw.y2b\Publisher.5yo4swcgiijiq5te00ddqtmrsgfhvrp4\AssemFiles\
                        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(ApplicationName + ".log", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read, isoFile)) {
                            //stream.Seek(0, System.IO.SeekOrigin.End);

                            if (debugLogEventCount == 0)
                            {
                                try {
                                    string path = stream.GetType().GetField("m_FullPath", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(stream).ToString();
                                    if (logToEventLog && eventLogWriteEntryAction != null)
                                    {
                                        await System.Threading.Tasks.Task.Run(() => eventLogWriteEntryAction("Saving debug log to " + path, EventLogEntryType.Information));
                                    }
                                    else
                                    {
                                        await ConsoleLogAsync("Saving debug log to " + path, EventLogEntryType.Information);
                                    }
                                }
                                catch { }
                            }
                            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream)) {
                                await writer.WriteLineAsync(DateTime.UtcNow.ToString("s", System.Globalization.CultureInfo.InvariantCulture) + "\t[" + entryType + "]\t" + message);
                            }
                        }
                    }
                    catch (System.IO.IOException e) {
                        if (debugLogEventCount == 0 && eventLogWriteEntryAction != null)
                        {
                            await System.Threading.Tasks.Task.Run(() => eventLogWriteEntryAction(e.Message, EventLogEntryType.Error));
                        }
                    }
                    catch (System.NullReferenceException) {
                        LogToFile = false;
                    }
                    finally {
                        logFileLock.Release();
                        System.Threading.Interlocked.Increment(ref debugLogEventCount);
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public async System.Threading.Tasks.Task <SoftmakeAll.SDK.OperationResult> DeleteAsync(System.String ShareName, System.String[] StorageFileNames)
        {
            SoftmakeAll.SDK.CloudStorage.Azure.Environment.Validate();

            SoftmakeAll.SDK.OperationResult OperationResult = new SoftmakeAll.SDK.OperationResult();

            if ((System.String.IsNullOrWhiteSpace(ShareName)) || (StorageFileNames == null) || (StorageFileNames.Length == 0))
            {
                OperationResult.Message = "The ShareName and StorageFileName cannot be null.";
                return(OperationResult);
            }

            try
            {
                global::Azure.Storage.Files.Shares.ShareClient          ShareClient          = new global::Azure.Storage.Files.Shares.ShareClient(SoftmakeAll.SDK.CloudStorage.Azure.Environment._ConnectionString, ShareName);
                global::Azure.Storage.Files.Shares.ShareDirectoryClient ShareDirectoryClient = ShareClient.GetRootDirectoryClient();

                using (System.Threading.SemaphoreSlim SemaphoreSlim = new System.Threading.SemaphoreSlim(StorageFileNames.Length))
                {
                    System.Collections.Generic.List <System.Threading.Tasks.Task> DeleteTasks = new System.Collections.Generic.List <System.Threading.Tasks.Task>();
                    foreach (System.String StorageFileName in StorageFileNames)
                    {
                        global::Azure.Storage.Files.Shares.ShareFileClient ShareFileClient = ShareDirectoryClient.GetFileClient(StorageFileName);
                        if (!(await ShareFileClient.ExistsAsync()))
                        {
                            continue;
                        }

                        await SemaphoreSlim.WaitAsync();

                        DeleteTasks.Add(System.Threading.Tasks.Task.Run(async() => { await ShareFileClient.DeleteAsync(); SemaphoreSlim.Release(); }));
                    }

                    if (DeleteTasks.Any())
                    {
                        await System.Threading.Tasks.Task.WhenAll(DeleteTasks);
                    }
                }
            }
            catch (System.Exception ex)
            {
                OperationResult.Message = ex.Message;
                return(OperationResult);
            }

            OperationResult.ExitCode = 0;
            return(OperationResult);
        }
Ejemplo n.º 30
0
 public WordsPage(WordbookImpressViewModel model) : this()
 {
     this.BindingContext    = model.Words;
     model.PropertyChanged += async(s, e) =>
     {
         if (e.PropertyName == nameof(model.Words))
         {
             await Task.Run(async() =>
             {
                 await CanPushSemaphore.WaitAsync();
                 this.BindingContext = model.Words;
                 CanPushSemaphore.Release();
             });
         }
     };
 }