public void GetReadings() { //we initialize the thread that will read from RabbitMQ if (t == null) { lock (oLock) { if (t == null) { t = new Thread(() => { ConnectToRabbit(); }); t.IsBackground = true; t.Start(); } } } //put the available data to json - java script will love it DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(RemoteMover)); string rez = ""; HttpContext.Current.Response.ContentType = "application/json"; using (System.IO.MemoryStream sw = new System.IO.MemoryStream()) { if (dictGrid.Count > 0) { RemoteMover rmLast = (RemoteMover)dictGrid.Last().Value; sw.Write(System.Text.UTF8Encoding.UTF8.GetBytes("[\r\n"), 0, 3); foreach (RemoteMover rm in dictGrid.Values) { dcjs.WriteObject(sw, rm); if (rmLast != rm) { sw.Write(System.Text.UTF8Encoding.UTF8.GetBytes(",\r\n"), 0, 3); } } sw.Write(System.Text.UTF8Encoding.UTF8.GetBytes("]\r\n"), 0, 3); rez = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray()); } } HttpContext.Current.Response.Write(rez); }
public RemoteMover JsonToRemoteMover(string json) { try { DataContractJsonSerializer jdcs = new DataContractJsonSerializer(typeof(RemoteMover)); System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(json)); RemoteMover rm = (RemoteMover)jdcs.ReadObject(ms); return(rm); } catch (InvalidCastException) { return(null); } catch (SerializationException) { return(null); } }
//this function starts the first time the GetReadings function called public void ConnectToRabbit() { ConnectionFactory cf = new ConnectionFactory(); DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(RemoteMover)); cf.HostName = "localhost"; cf.UserName = "******"; cf.Password = "******"; //connect to RabbitMQ using (IConnection conn = cf.CreateConnection()) { using (IModel channel = conn.CreateModel()) { channel.ExchangeDeclare(exchange: "miscari", type: "fanout", durable: true); var queueName = channel.QueueDeclare().QueueName; channel.QueueBind(queue: queueName, exchange: "miscari", routingKey: ""); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = System.Text.UTF8Encoding.UTF8.GetString(body); RemoteMover rm = JsonToRemoteMover(message); if (rm != null) { WriteToDb(rm); } }; channel.BasicConsume(queue: queueName, noAck: true, consumer: consumer); //not nice, but ... it does wait while (true) { Thread.Sleep(50); } } } }
private void WriteToDb(RemoteMover rm) { using (MySqlConnection conn = new MySqlConnection(WebService1.connString)) { try { conn.Open(); } catch (Exception) { return; } using (MySqlCommand mysqlComm = new MySqlCommand("insert into timeline(id_agent,x,y) values(@id_agent,@x,@y)", conn)) { mysqlComm.Parameters.AddWithValue("@id_agent", rm.id); mysqlComm.Parameters.AddWithValue("@x", rm.point.x); mysqlComm.Parameters.AddWithValue("@y", rm.point.y); mysqlComm.ExecuteNonQuery(); //only show what was written dictGrid[rm.id] = rm; } } }