예제 #1
0
        /// <inheritdoc/>
        public IRealtimeChannel Get(string name, ChannelOptions options)
        {
            // if the channel cannot be found
            if (!Channels.TryGetValue(name, out var result))
            {
                // create a new instance using the passed in option
                var channel = new RealtimeChannel(name, _realtimeClient.Options.GetClientId(), _realtimeClient, options, _mobileDevice);
                result = Channels.AddOrUpdate(name, channel, (s, realtimeChannel) =>
                {
                    if (options != null)
                    {
                        realtimeChannel.Options = options;
                    }

                    return(realtimeChannel);
                });
                _orderedChannels.Add(result);
            }
            else
            {
                if (options != null)
                {
                    if (result.ShouldReAttach(options))
                    {
                        throw new AblyException(new ErrorInfo("Channels.Get() cannot be used to set channel options that would cause the channel to reattach. Please, use Channel.SetOptions() instead.", ErrorCodes.BadRequest, HttpStatusCode.BadRequest));
                    }

                    result.SetOptions(options);
                }
            }

            return(result);
        }
        public void SendPing(Action <PingSuccess> onPingSuccessCallback, Action <PingFailure> onPingFailureCallback, int numberOfSeparatePings = 10, int timeOutMilliseconds = 5000)
        {
            if (numberOfSeparatePings < 1)
            {
                throw new ArgumentException("Must be at least one", nameof(numberOfSeparatePings));
            }


            CancelPendingPings();
            ClearPingResponseStuff();

            PingSuccessCallback = onPingSuccessCallback;
            PingFailureCallback = onPingFailureCallback;

            Task.Run(() =>
            {
                // We run this on another thread because if an invalid hostname is provided it takes literally five entire seconds
                // for .net to figure that out. F**k you .net
                if (TargetAddress == null)
                {
                    try
                    {
                        TargetAddress = IPParser.ParseAddress(HostNameOrAddress);
                    }
                    catch
                    {
                        TriggerPingFailure(PingFailureReason.AddressNotFound);
                        return;
                    }
                }

                if (TargetAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                {
                    // Sorry about this... Mono's Ping() doesn't support IPv6. I tried to add support (see the 'fixedping' branch) but
                    // Unity's Mono fork has a bug where you can't create IPv6 ICMP sockets. This bug is *not* present on upstream
                    // Mono. I've reported the bug to Unity, as soon as they fix it I should be able to add IPv6 suport to this class.
                    TriggerPingFailure(PingFailureReason.IPv6NotSupported);
                    return;
                }

                for (int i = 0; i <= numberOfSeparatePings; i++)
                {
                    var ping = new Ping();
                    IndividualPings.Add(ping);

                    ping.PingCompleted += OnPingCompleted;
                }

                // Send the pings *after* they've all been created, to make absolutely certain that we recieve no ping responses until
                // we know how many responses are expected. This has actually happened to me a couple of times when pinging localhost,
                // though it's pretty rare.
                lock (IndividualPings.__InternalListLock)
                {
                    foreach (var ping in IndividualPings)
                    {
                        ping.SendAsync(TargetAddress, timeOutMilliseconds, null);
                    }
                }
            });
        }
예제 #3
0
        /// <inheritdoc/>
        public IRestChannel Get(string name, ChannelOptions options)
        {
            if (!_channels.TryGetValue(name, out var result))
            {
                var channel = new RestChannel(_ablyRest, name, options, _mobileDevice);
                result = _channels.AddOrUpdate(name, channel, (s, realtimeChannel) =>
                {
                    if (options != null && realtimeChannel != null)
                    {
                        realtimeChannel.Options = options;
                    }

                    return(realtimeChannel);
                });
                _orderedChannels.Add(result);
            }
            else
            {
                if (options != null)
                {
                    result.Options = options;
                }
            }

            return(result);
        }
예제 #4
0
            public void Add(ProtectedCacheInfo info)
            {
                foreach (var hash in info.Hashes)
                {
                    _cacheManager.Lock(hash);
                }

                _infos.Add(info);
            }
        private void ConvertFilteredTextToWordList(string text, LockedList <string> list)
        {
            if (string.IsNullOrEmpty(text))
            {
                text = "";
            }
            text = text.Replace("*", ModerationHelper.BannedWordWildcardRegexFormat);

            list.Clear();
            foreach (string split in text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
            {
                list.Add(split);
            }
        }
        private void OnPingCompleted(object _, PingCompletedEventArgs args)
        {
            if (args.Cancelled)
            {
                return;
            }

            if (args.Error != null)
            {
                TriggerPingFailure(IPStatus.Unknown);
                return;
            }

            PingReply reply = args.Reply;

            if (reply.Status != IPStatus.Success)
            {
                TriggerPingFailure(reply.Status);
                return;
            }


            PingResponseTimes.Add(reply.RoundtripTime);

            if (PingResponseTimes.Count >= IndividualPings.Count)
            {
                CancelPendingPings();

                long averageTime;

                // Must use the lock here as the extension method iterates over the collection
                lock (PingResponseTimes.__InternalListLock)
                    averageTime = PingResponseTimes.GetMeanRoundedToNearestWhole();

                Dispatcher.InvokeAsync(() =>
                {
                    // Invoke on the main thread
                    PingSuccessCallback?.Invoke(new PingSuccess()
                    {
                        AverageRoundTripTimeMilliseconds = averageTime
                    });
                    ClearPingResponseStuff();
                });
            }
        }
예제 #7
0
        private TestPageModel GetModel()
        {
            this.Session["count"] = (int)this.Session["count"] + 1;


            SafelyIncrementableIntHolder safeInt = this.Session["safeCount"] as SafelyIncrementableIntHolder;
            int safeResult = safeInt.Increment();

            LockedList sessList = this.Session["listCount"] as LockedList;

            sessList.Add(0);


            TestPageModel mdl = new TestPageModel
            {
                Count     = (int)this.Session["count"],
                SafeCount = safeResult,
                ListCount = sessList.Count
            };

            return(mdl);
        }
 public void AddUser(PokerUser user)
 {
     users.Add(user);
 }
예제 #9
0
파일: Miner.cs 프로젝트: tonycody/Library
            public byte[] Create_1(byte[] value, int limit, TimeSpan computationTime)
            {
                if (value == null)
                {
                    throw new ArgumentNullException("value");
                }
                if (value.Length != 32)
                {
                    throw new ArgumentOutOfRangeException("value");
                }

                var info = new ProcessStartInfo(_path);

                info.CreateNoWindow         = true;
                info.UseShellExecute        = false;
                info.RedirectStandardOutput = true;

                {
                    if (limit < 0)
                    {
                        limit = -1;
                    }

                    int timeout;

                    if (computationTime < TimeSpan.Zero)
                    {
                        timeout = -1;
                    }
                    else
                    {
                        timeout = (int)computationTime.TotalSeconds;
                    }

                    info.Arguments = string.Format(
                        "hashcash1 create {0} {1} {2}",
                        NetworkConverter.ToHexString(value),
                        limit,
                        timeout);
                }

                using (var process = Process.Start(info))
                {
                    _processes.Add(process);

                    try
                    {
                        process.PriorityClass = ProcessPriorityClass.Idle;

                        try
                        {
                            var result = process.StandardOutput.ReadLine();

                            process.WaitForExit();
                            if (process.ExitCode != 0)
                            {
                                throw new MinerException();
                            }

                            return(NetworkConverter.FromHexString(result));
                        }
                        catch (MinerException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            throw new MinerException(e.Message, e);
                        }
                    }
                    finally
                    {
                        _processes.Remove(process);
                    }
                }
            }
예제 #10
0
        private void MessageUploadAndDownload(IEnumerable <CoreManager> coreManagers)
        {
            _callback.Invoke("----- CoreManager Message Send and Receive Test -----");
            _callback.Invoke("");

            var coreManagerList = coreManagers.ToList();

            Parallel.ForEach(coreManagerList, coreManager =>
            {
                coreManager.Resize((long)1024 * 1024 * 1024 * 32).Wait();
            });

            var hashList     = new LockedHashSet <Hash>();
            var metadataList = new LockedList <Metadata>();

            Parallel.For(0, 30, new ParallelOptions()
            {
                MaxDegreeOfParallelism = 3
            }, i =>
            {
                var random = RandomProvider.GetThreadRandom();

                using (var stream = new BufferStream(_bufferManager))
                {
                    using (var safeBuffer = _bufferManager.CreateSafeBuffer(1024 * 4))
                    {
                        for (long remain = (long)1024 * 1024 * 32; remain > 0; remain = Math.Max(0, remain - safeBuffer.Value.Length))
                        {
                            int length = (int)Math.Min(remain, safeBuffer.Value.Length);

                            random.NextBytes(safeBuffer.Value);
                            stream.Write(safeBuffer.Value, 0, length);
                        }
                    }

                    stream.Seek(0, SeekOrigin.Begin);
                    hashList.Add(new Hash(HashAlgorithm.Sha256, Sha256.ComputeHash(new WrapperStream(stream, true))));

                    stream.Seek(0, SeekOrigin.Begin);
                    using (var tokenSource = new CancellationTokenSource())
                    {
                        metadataList.Add(coreManagerList[i].VolatileSetStream(stream, new TimeSpan(1, 0, 0), tokenSource.Token).Result);
                    }
                }
            });

            var sw = Stopwatch.StartNew();

            Parallel.ForEach(metadataList, metadata =>
            {
                for (; ;)
                {
                    Thread.Sleep(1000);

                    Stream stream = null;

                    try
                    {
                        stream = coreManagerList[0].VolatileGetStream(metadata, 1024 * 1024 * 256);
                        if (stream == null)
                        {
                            continue;
                        }

                        var hash = new Hash(HashAlgorithm.Sha256, Sha256.ComputeHash(stream));
                        if (!hashList.Contains(hash))
                        {
                            throw new ArgumentException("Broken");
                        }

                        _callback.Invoke($"{sw.Elapsed.ToString("hh\\:mm\\:ss")}: Success {NetworkConverter.ToBase64UrlString(metadata.Hash.Value)}");

                        return;
                    }
                    finally
                    {
                        if (stream != null)
                        {
                            stream.Dispose();
                        }
                    }
                }
            });

            _callback.Invoke("----- End -----");
        }