Пример #1
0
        /// <summary>
        /// Begins synchronization.
        /// </summary>
        public async Task Start()
        {
            if (_apiService == null)
            {
                Console.WriteLine("That's dope man.");
            }
            DateTime today    = DateTime.Now.Subtract(DateTime.Now.TimeOfDay);
            DateTime tomorrow = today.AddDays(1);
            List <T> list;

            try
            {
                list = await _apiService.GetAllBetweenDatesAsync <T>(_apiResourceUri, today, tomorrow);
            }
            catch (Flurl.Http.FlurlHttpException ex)
            {
                throw;
            }
            Console.WriteLine("Number of initial elements: " + list.Count);
            if (list.Count > 0)
            {
                _repository.AddRange(list);
                NewData?.Invoke(this, new DataSyncEventArgs <T>()
                {
                    ChangedElements = list
                });
            }
            //foreach (T item in _repository.Cast<T>())
            //{
            //    Console.WriteLine(item.GetSyncId());
            //}
            _timer.Start();
        }
Пример #2
0
        private void ReceiveLoop(CancellationToken ct)
        {
            while (!ct.IsCancellationRequested)
            {
                string msg = GetNextMessage();
                if (msg == "")
                {
                    continue;
                }
                XmlDocument doc    = new XmlDocument();
                XmlSchema   schema = new XmlSchema();
                schema.Namespaces.Add("stream", "http://etherx.jabber.org/streams");
                doc.Schemas.Add(schema);

                //quit if the stream has been closed
                if (msg.IndexOf("</stream:stream>") != -1)
                {
                    StreamClosed?.Invoke();
                    return;
                }
                bool wtf = false;
                // Correct XML errors: stream opening should be the only case in which there is an open tag
                if (msg.IndexOf("<stream:stream") != -1)
                {
                    msg += "</stream:stream>";
                    wtf  = true;
                }
                else
                {
                    msg = GetStreamHeader() + msg + "</stream:stream>";
                }

                doc.LoadXml(msg);
                XmlNodeList nodes = null;
                if (wtf)
                {
                    nodes = doc.ChildNodes;
                }
                else
                {
                    nodes = doc.LastChild.ChildNodes;
                }

                foreach (XmlNode node in nodes)
                {
                    NewData?.Invoke(node);
                    if (node.Name.Equals("iq"))
                    {
                        NewIq?.Invoke(node);
                    }
                }
            }
        }
Пример #3
0
 void OnTick(object sender, EventArgs e)
 {
     if (file.BaseStream.Length != oldSize)
     {
         var res   = file.BaseStream.Seek(oldSize, SeekOrigin.Begin);
         var bytes = file.ReadBytes((int)file.BaseStream.Length - oldSize);
         var str   = Encoding.UTF8.GetString(bytes);
         NewData?.Invoke(this, str);
         OnNewData(str);
     }
     oldSize = (int)file.BaseStream.Length;
 }
Пример #4
0
        public async Task FetchAsync()
        {
            var lastEntry = await context.Data.AsQueryable().OrderByDescending(a => a.Timestamp).FirstOrDefaultAsync();

            if (lastEntry?.Timestamp != null && lastEntry.Timestamp.Add(RefreshRate) > DateTime.UtcNow)
            {
                return;
            }

            bool traverse     = true;
            var  foundEntries = new Stack <InstagramData>();

            while (traverse)
            {
                var data = await HttpClient.GetStringAsync(GetMediaUri(100, "id,timestamp,permalink", null));

                var response = JsonConvert.DeserializeObject <InstagramResponse>(data);
                if (response.Paging.Next == null)
                {
                    traverse = false;                               //If there's no next, no need to fetch more
                }
                foreach (var item in response.Data)
                {
                    if (item.Timestamp <= lastEntry?.Timestamp)
                    {
                        traverse = false;
                        break;
                    }

                    var uri = await GetOembedUriAsync(item.Permalink !);

                    var embedData = await HttpClient.GetStringAsync(uri);

                    var embedResponse = JsonConvert.DeserializeObject <OembedData>(embedData, new JsonSerializerSettings
                    {
                        ContractResolver = new DefaultContractResolver
                        {
                            NamingStrategy = new SnakeCaseNamingStrategy()
                        }
                    }) ?? throw new NullReferenceException("Couldn't deserialise Oembed data");

                    var entry = new InstagramData(item.Id !, item.Timestamp !.Value, embedResponse);
                    await context.Data.InsertOneAsync(entry);

                    foundEntries.Push(entry);
                }
            }
            if (foundEntries.Count > 0)
            {
                NewData?.Invoke(this, foundEntries);
            }
        }
Пример #5
0
        /// <summary>
        /// Invoke the order event to add a new order
        /// </summary>
        /// <param name="request">String with order information</param>
        /// <returns>Return the order plates and order number</returns>
        private async Task <string> AddOrderAsync(string request)
        {
            var response = "";

            await Task.Run(() =>
            {
                var eventArgs = new OrderEventArgs(request);
                NewData?.Invoke(this, eventArgs);
                response = eventArgs.Response;
            });

            return(response);
        }
Пример #6
0
        /// <summary>
        /// Асинхронный запуск сервера
        /// </summary>
        /// <returns></returns>
        public Task StartAsync()
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    if (MessageEncryptionEnabled)
                    {
                        Console.WriteLine($"Server run on {Port} with encryption channel");
                    }
                    else
                    {
                        Console.WriteLine($"Server run on {Port}");
                    }

                    _listener.Start();

                    while (true)
                    {
                        TcpClient client = _listener.AcceptTcpClient();

                        Task.Factory.StartNew(() =>
                        {
                            var fluffyClient = new FluffyClient(client, this);

                            AddConnectedClient(fluffyClient);

                            StoreInit?.Invoke(fluffyClient);

                            NewClientConnected?.Invoke(fluffyClient);

                            fluffyClient.Disconnected += client1 => { ClientDisconnected?.Invoke(client1); };

                            fluffyClient.NewData += (data) =>
                            {
                                NewData?.Invoke(fluffyClient, data);
                            };

                            fluffyClient.NewPacket += (ref int id, PacketParser <Packet> parser, FluffyClient xFuffyClient) =>
                            {
                                NewPacket?.Invoke(ref id, parser, xFuffyClient);
                            };
                        });
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + " " + e.StackTrace);
                }
            }));
        }
Пример #7
0
        private async void SyncWithDatabase(object sender, EventArgs e)
        {
            var list = await _dataSyncDelegate(_apiService, _apiResourceUri, _repository.Count > 0?_repository.Max(x => x.GetSyncId()) : -1);

            //Console.WriteLine("Sync Call made");
            if (list.Count > 0)
            {
                Console.WriteLine("More than 0 ({0}) new elements retrieved!", list.Count);
                _repository.AddRange(list);
                NewData?.Invoke(this, new DataSyncEventArgs <T>()
                {
                    ChangedElements = list
                });
            }

            //If there are no elements, nothing can change
            if (_repository.Count == 0)
            {
                return;
            }


            var alteredList = await ItemsAlteredFetchFunc(_apiService, _apiResourceUri, _repository.Min(x => x.GetSyncDate()));

            if (alteredList.Count > 0)
            {
                //This is needed because the minimum date might be lower than the first processed element's date due to appointments taking priority.
                //Probably should be moved to an upper layer as this behaviour is CheckIn specific and this class is otherwise trying to be as generic as possible
                List <T> notifyWithList = new List <T>();
                foreach (var item in alteredList)
                {
                    //Console.WriteLine(item.GetSyncId() + ": " + item.GetSyncDate());
                    T removable = _repository.SingleOrDefault(x => x.GetSyncId() == item.GetSyncId());
                    if (removable != null)
                    {
                        _repository.Remove(removable);
                        notifyWithList.Add(item);
                    }
                }
                if (notifyWithList.Count > 0)
                {
                    AlteredData?.Invoke(this, new DataSyncEventArgs <T>()
                    {
                        ChangedElements = notifyWithList
                    });
                }
            }
        }
        // Since each wave form is periodic, new data events are generated at standard time intervals
        // with duration specified by the sendInterval property.
        async void ReadNext()
        {
            while (true)
            {
                try {
                    await Task.Delay(TimeSpan.FromSeconds(this.readDelta));

                    double val = 0;

                    switch (waveType)
                    {
                    case Waves.Sine:
                        val = sine(cur); break;

                    case Waves.Square:
                        val = square(cur); break;

                    case Waves.Sawtooth:
                        val = sawTooth(cur); break;

                    case Waves.Triangle:
                        val = triangle(cur); break;

                    default: break;
                    }

                    // if the configuration is set accordingly, add a uniform random number to value before
                    // reporting it
                    if (isNoisy && cur >= start && cur < start + duration)
                    {
                        val += minNoiseBound + rnd.NextDouble() * (maxNoiseBound - minNoiseBound);
                    }

                    cur = (cur + readDelta) % period;

                    //raise new data event
                    NewData?.Invoke(this, new NewDataArgs(val));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ERROR] Unexpected Exception {ex.Message}");
                    Console.WriteLine($"\t{ex.ToString()}");
                }
            }
        }
Пример #9
0
        public async Task UserOpenFile()
        {
            OpenFileDialog fd = new OpenFileDialog();

            fd.ShowDialog();
            MainWindow.Instance.Title = fd.FileName;
            var stream = fd.OpenFile();

            if (stream == null)
            {
                return;
            }
            string content;

            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                content = await reader.ReadToEndAsync();
            }
            NewData?.Invoke(content);
        }
Пример #10
0
        private void SimReceivingLoop(int delay)
        {
            DateTime starttime = DateTime.Now;

            simconnected = true;
            do
            {
                var thisE = (int)(1023 * Math.Sin(DateTime.Now.Millisecond / 1000.0 * 2 * Math.PI));
                var thisI = (int)(1023 * Math.Cos(DateTime.Now.Millisecond / 1000.0 * 2 * Math.PI));
                var milli = (ulong)((DateTime.Now - starttime).TotalMilliseconds);
                NewData?.Invoke(this, new NewDataEventArgs(milli, 0, thisE, thisI));
                _Buffer = 123;
                System.Threading.Thread.Sleep(delay);
            } while (!CancelListen.IsCancellationRequested);
            simconnected = false;
            //Disconnected?.Invoke(this, new DisconnectedEventArgs("Cancel"));
            context.Post(new SendOrPostCallback(delegate(object state)
            {
                Disconnected?.Invoke(this, new DisconnectedEventArgs("Cancel"));
            }), null);
        }
Пример #11
0
        private async void Extract()
        {
            if (Parser == null || Settings == null)
            {
                IsRun = false;
                return;
            }

            for (int i = Settings.StartPage; i <= Settings.EndPage; i++)
            {
                if (IsRun)                                        //проверяем активность парсера
                {
                    string source = await _loader.GetHtmlCode(i); //Получаем код страницы

                    HtmlParser    htmlParser = new HtmlParser();
                    IHtmlDocument document   = await htmlParser.ParseDocumentAsync(source);

                    Data.AddRange(Parser.Parse(document)); // сохраняем полученные данные
                    NewData?.Invoke(this, Data.ToArray()); // возвращаем полученные за итерацию данные
                }
            }
            Complited?.Invoke(this); // событие отвечающее за информирование о завершении парсинга
            IsRun = false;
        }
Пример #12
0
 public override void UpstreamProcess(MockData1 protocol)
 {
     protocol.Verify();
     NewData?.Invoke(protocol);
 }
Пример #13
0
 public void LoadString(string content)
 {
     NewData?.Invoke(content);
 }
Пример #14
0
        private void ReceiveDataStart(int receiveBufferLength)
        {
            try
            {
                _disconnectTimer.Stop();
                _disconnectTimer.Start();

                _disconnectTimer.Elapsed += (sender, args) =>
                {
                    Console.WriteLine("Client disconnected by timeout");
                    CloseConnect();
                };

                using (NetworkStream stream = TcpClient.GetStream())
                {
                    while (TcpClient.Connected)
                    {
                        if (TcpClient.Available < HeaderLength)
                        {
                            Thread.Sleep(5);
                            continue;
                        }

                        int messageLength = ReceiveHeaderData(stream);

                        if (messageLength > _server.MaxReceivePacketLength)
                        {
                            CloseConnect();
                            return;
                        }

                        int remaining = messageLength;

                        byte[] finalDataBuffer = new byte[messageLength];

                        int index = 0;

                        while (remaining > 0)
                        {
                            if (remaining < receiveBufferLength)
                            {
                                receiveBufferLength = remaining;
                            }

                            while (TcpClient.Available < receiveBufferLength)
                            {
                                Thread.Sleep(5);
                            }

                            byte[] buffer = new byte[receiveBufferLength];

                            stream.Read(buffer, 0, receiveBufferLength);

                            for (int i = 0; i < buffer.Length; i++)
                            {
                                finalDataBuffer[index++] = buffer[i];
                            }

                            remaining -= receiveBufferLength;
                        }

                        if (Aes256Key != null)
                        {
                            finalDataBuffer = MyAes.DecryptBytes(finalDataBuffer, Aes256Key, MyAes.Iv);
                        }

                        Console.WriteLine("Readed from client bytes length " + (finalDataBuffer.Length));

                        if (ByteArrayCompare(finalDataBuffer, PingData))
                        {
                            Send(PongData);

                            _disconnectTimer.Stop();
                            _disconnectTimer.Start();

                            Console.WriteLine("Ping data received " + (messageLength + HeaderLength) + " bytes. Pong data sent");
                        }
                        else
                        {
                            NewData?.Invoke(finalDataBuffer);

                            try
                            {
                                object packet = null;

                                int packetId = BitConverter.ToInt32(finalDataBuffer.Take(4).ToArray(), 0);

                                if (_server.MessageEncryptionEnabled)
                                {
                                    if (this.Aes256Key == null)
                                    {
                                        if (packetId != -122030 && packetId != -42142)
                                        {
                                            Console.WriteLine("Пришел пакет, который не ожидался");
                                            continue;
                                        }
                                    }
                                }

                                NewPacket?.Invoke(ref packetId, (t) =>
                                {
                                    using (MemoryStream ms = new MemoryStream(finalDataBuffer.Skip(4).ToArray()))
                                        using (BsonReader reader = new BsonReader(ms))
                                        {
                                            JsonSerializer serializer = new JsonSerializer();

                                            packet = serializer.Deserialize(reader, t);
                                        }

                                    return((Packet)packet);
                                }, this);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message + " " + e.StackTrace);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Debug
                Console.WriteLine(e.Message + " " + e.StackTrace);
            }
            finally
            {
                Disconnected?.Invoke(this);

                CloseConnect();
            }
        }
Пример #15
0
        //public Action<int> NewData;

        public void Next(int data)
        {
            NewData?.Invoke(this, data);
            //NewData?.Invoke(data);
        }
Пример #16
0
        private void ReceivingLoop()
        {
            var rx = new Regex("m(\\d+)u(\\d+)E(\\d+)I(\\d+)");

            Port.DiscardInBuffer();
            int fails = 0;

            Port.ReadTimeout = 10000;
            reallyconnected  = true;
            _TotalUpdates    = 0;
            try
            {
                do
                {
                    //Write commands
                    if (Command != null)
                    {
                        Port.WriteLine(Command);
                        Command = null;
                    }
                    //Read some data when available, or wait
                    if (Port.BytesToRead > 0)
                    {
                        var line = Port.ReadLine();
                        if (line.StartsWith("SSSTART"))
                        {
                            //Record Single Shot
                            List <ulong> Time = new List <ulong>();
                            List <int>   E    = new List <int>();
                            List <int>   I    = new List <int>();
                            do
                            {
                                line = Port.ReadLine();
                                if (rx.IsMatch(line))
                                {
                                    var SSmatch     = rx.Match(line);
                                    var SSthisMilli = ulong.Parse(SSmatch.Groups[1].Value);
                                    var SSthisMicro = ulong.Parse(SSmatch.Groups[2].Value);
                                    var SSthisE     = int.Parse(SSmatch.Groups[3].Value);
                                    var SSthisI     = int.Parse(SSmatch.Groups[4].Value);
                                    Time.Add(SSthisMicro);
                                    E.Add(SSthisE);
                                    I.Add(SSthisI);
                                }
                            } while (line != "SSEND");
                            context.Post(new SendOrPostCallback(delegate(object state)
                            {
                                GotSingleShot?.Invoke(this, new SingleShotEventArgs(Time, E, I));
                            }), null);
                            continue;
                        }
                        if (!rx.IsMatch(line))
                        {
                            fails++;
                            if (fails > 10)
                            {
                                throw new Exception("No matching text. Baudrate wrong?");
                            }
                            continue;
                        }
                        fails = 0;
                        var match     = rx.Match(line);
                        var thisMilli = ulong.Parse(match.Groups[1].Value);
                        var thisMicro = ulong.Parse(match.Groups[2].Value);
                        var thisE     = int.Parse(match.Groups[3].Value);
                        var thisI     = int.Parse(match.Groups[4].Value);
                        NewData?.Invoke(this, new NewDataEventArgs(thisMilli, thisMicro, thisE, thisI));
                        _TotalUpdates++;
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(5);
                    }
                    _Buffer = Port.BytesToRead;
                } while (!CancelListen.IsCancellationRequested);
                //Disconnected?.Invoke(this, new DisconnectedEventArgs("Cancel"));
                context.Post(new SendOrPostCallback(delegate(object state)
                {
                    Disconnected?.Invoke(this, new DisconnectedEventArgs("Cancel"));
                }), null);
            }
            catch (Exception ex)
            {
                //Disconnected?.Invoke(this, new DisconnectedEventArgs("Exception: " + ex.Message));
                context.Post(new SendOrPostCallback(delegate(object state)
                {
                    Disconnected?.Invoke(this, new DisconnectedEventArgs("Exception: " + ex.Message));
                }), null);
            } finally
            {
                Port?.Close();
                reallyconnected = false;
            }
        }
Пример #17
0
 void waveIn_DataAvailable(object sender, WaveInEventArgs e)
 {
     // add received data to waveProvider buffer
     bwp.AddSamples(e.Buffer, 0, e.BytesRecorded);
     NewData?.Invoke();
 }
Пример #18
0
        public bool Connect()
        {
            if (_client?.Connected == true)
            {
                return(true);
            }

            try
            {
                _client = new TcpClient();
                _client.Connect(_address, _port);

                _drs = new DataReceiveService(_client, this);


                Task.Factory.StartNew(() =>
                {
                    _drs.Disconnected += client =>
                    {
                        Disconnected?.Invoke();
                    };

                    _drs.NewData += (data) =>
                    {
                        NewData?.Invoke(data);

                        try
                        {
                            object packet = null;

                            int packetId = BitConverter.ToInt32(data.Take(4).ToArray(), 0);

                            NewPacket?.Invoke(ref packetId, (t) =>
                            {
                                using (MemoryStream ms = new MemoryStream(data.Skip(4).ToArray()))
                                    using (BsonReader reader = new BsonReader(ms))
                                    {
                                        JsonSerializer serializer = new JsonSerializer();

                                        packet = serializer.Deserialize(reader, t);
                                    }

                                return((Packet)packet);
                            }, this);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message + " " + e.StackTrace);
                        }
                    };

                    _drs.Run();
                });

                var waitPacket = SendPacketAndGetResponse <ConnectionRequest, ConnectionConfig>(new ConnectionRequest());

                if (waitPacket?.CryptoEnabled == true)
                {
                    RsaClientSide rsaClientSide = new RsaClientSide();

                    var publicKey = rsaClientSide.PublicKeyString;

                    var rsaHandshakeResponse =
                        SendPacketAndGetResponse <RsaHandshakeRequest, RsaHandshakeResponse>(
                            new RsaHandshakeRequest()
                    {
                        PublicKey = publicKey
                    });

                    if (rsaHandshakeResponse == null)
                    {
                        throw new Exception();
                    }

                    var decryptedData = rsaClientSide.Step2(rsaHandshakeResponse.EncryptedData);

                    Console.WriteLine($"Receive decrypted AES-256 Key: {Convert.ToBase64String(decryptedData)}");

                    Aes256Key = decryptedData;

                    var pinger = new PingService(this);
                    pinger.StartAsync();
                }
                else
                {
                    var pinger = new PingService(this);
                    pinger.StartAsync();
                }
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
 public override TProtocol DownstreamProcess(object data) => null; // Not applicable
 public override void UpstreamProcess(TProtocol protocol) => NewData?.Invoke(protocol);
        private void OnTimerElapsed()
        {
            PriceQuote nextData = GetNextData();

            NewData?.Invoke(nextData);
        }
Пример #21
0
 public void Update(int time, int score)
 {
     NewData?.Invoke(time, score);
 }
Пример #22
0
        } // Work.

        // Зажигатели событий.
        protected virtual void OnNewData(object arg1, T arg2)
        {
            NewData?.Invoke(arg1, arg2);
        } // OnNewData.
Пример #23
0
 public void Log(string msg)
 {
     NewData.Invoke(msg);
 }
Пример #24
0
        public void Run(int receiveBufferLength = 4096)
        {
            try
            {
                using (NetworkStream stream = _client.GetStream())
                {
                    while (_client.Connected)
                    {
                        if (_client.Available < HeaderLength)
                        {
                            Thread.Sleep(5);
                            continue;
                        }

                        int messageLength = ReceiveHeaderData(stream);

                        int remaining = messageLength;

                        byte[] finalDataBuffer = new byte[messageLength];

                        int index = 0;

                        while (remaining > 0)
                        {
                            if (remaining < receiveBufferLength)
                            {
                                receiveBufferLength = remaining;
                            }

                            while (_client.Available < receiveBufferLength)
                            {
                                Thread.Sleep(5);
                            }

                            byte[] buffer = new byte[receiveBufferLength];

                            stream.Read(buffer, 0, receiveBufferLength);

                            for (int i = 0; i < buffer.Length; i++)
                            {
                                finalDataBuffer[index++] = buffer[i];
                            }

                            remaining -= receiveBufferLength;
                        }

                        if (_fluffyNetClient.Aes256Key != null)
                        {
                            finalDataBuffer = MyAes.DecryptBytes(finalDataBuffer, _fluffyNetClient.Aes256Key, MyAes.Iv);
                        }

                        Console.WriteLine("Readed data from socket " + finalDataBuffer.Length + " bytes");

                        if (!ByteArrayCompare(PongData, finalDataBuffer))
                        {
                            NewData?.Invoke(finalDataBuffer);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Debug
                Console.WriteLine(e.Message + " " + e.StackTrace);
            }
            finally
            {
                _fluffyNetClient.CloseConnect();

                Disconnected?.Invoke(_fluffyNetClient);
            }
        }