public void TestParsing() { var dateTime = DateTime.Now; var usage = new NetworkLicenseUsage("computerId", "ip", "userName", "licenseSignature", dateTime); Assert.AreEqual("computerId", usage.ComputerId); Assert.AreEqual("ip", usage.Ip); Assert.AreEqual("licenseSignature", usage.LicenseSignature); Assert.AreEqual("userName", usage.UserName); //Assert.IsTrue(ObjectHelper.AreEqual(dateTime, usage.StartDateTime)); var networkString = usage.ToNetworkMessage(); var usage2 = NetworkLicenseUsage.Parse(networkString); Assert.AreEqual(usage.ComputerId, usage2.ComputerId); Assert.AreEqual(usage.Ip, usage2.Ip); Assert.AreEqual(usage.LicenseSignature, usage2.LicenseSignature); Assert.AreEqual(usage.UserName, usage2.UserName); //Assert.IsTrue(ObjectHelper.AreEqual(usage.StartDateTime, usage2.StartDateTime)); }
private List <NetworkLicenseUsage> BroadcastMessage(string ipAddress, string message, int maxTimeout = 1000) { var licenseUsages = new Dictionary <string, NetworkLicenseUsage>(); Log.Debug("Broadcasting via ip '{0}' to see how much users are currently using the license", ipAddress); try { using (var udpClient = new UdpClient()) { udpClient.Client.ReceiveTimeout = maxTimeout; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.EnableBroadcast = true; udpClient.Client.Bind(new IPEndPoint(IPAddress.Parse(ipAddress), 0)); var sendBuffer = Encoding.ASCII.GetBytes(message); var remoteEndPoint = new IPEndPoint(IPAddress.Broadcast, Port); udpClient.Send(sendBuffer, sendBuffer.Length, remoteEndPoint); var endDateTime = DateTime.Now.AddMilliseconds(maxTimeout); while (endDateTime >= DateTime.Now) { try { var ipEndPoint = new IPEndPoint(IPAddress.Any, 0); var receiveBuffer = udpClient.Receive(ref ipEndPoint); if (receiveBuffer != null && receiveBuffer.Length > 0) { var receivedMessage = Encoding.ASCII.GetString(receiveBuffer); Log.Debug("Received message '{0}' from '{1}'", receivedMessage, ipEndPoint.Address); var licenseUsage = NetworkLicenseUsage.Parse(receivedMessage); if (licenseUsage == null) { continue; } if (string.Equals(licenseUsage.LicenseSignature, message)) { Log.Debug("Received message from '{0}' that license is being used", ipEndPoint.Address); var computerId = licenseUsage.ComputerId; var add = true; // Only update if this is an older timestamp if (licenseUsages.ContainsKey(computerId) && (licenseUsages[computerId].StartDateTime < licenseUsage.StartDateTime)) { add = false; } if (add) { licenseUsages[computerId] = licenseUsage; } } } } catch (SocketException) { // ignore } } } } catch (Exception ex) { Log.Error(ex, "Failed to broadcast message, defaulting to 0 currently active licences"); } return(licenseUsages.Values.ToList()); }