fly 2 lat temu
rodzic
commit
29b774f77b
4 zmienionych plików z 104 dodań i 101 usunięć
  1. 18 20
      Adapter/BufferAdapter.cs
  2. 71 71
      Adapter/JsonAdapter.cs
  3. 14 10
      NotificationServer.cs
  4. 1 0
      Service/NotificationService.cs

+ 18 - 20
Adapter/BufferAdapter.cs

@@ -1,14 +1,16 @@
 using System;
 using System.Buffers;
 using System.Text;
-using WingInterfaceLibrary.Request.Notification;
+using WingInterfaceLibrary.Notifications;
+using System.Text.Json;
+using  System.IO;
 
 namespace WingNotificationModule.Adapter
 {
     public class BufferAdapter
     {
-        private NotifyMessage _message;
-        public BufferAdapter(NotifyMessage message)
+        private object _message;
+        public BufferAdapter(object message)
         {
             _message = message;
         }
@@ -20,30 +22,26 @@ namespace WingNotificationModule.Adapter
         public byte[] GetMessageBuffer()
         {
             ArrayBufferWriter<byte> bufferWriter = new ArrayBufferWriter<byte>();
-            bufferWriter.Write(GetMessageTypeBytes());
-            bufferWriter.Write(GetNotificationTypeBytes());
-            bufferWriter.Write(GetMessageBytes().Span);
+            //  bufferWriter.Write(GetNotificationTypeBytes());
+             bufferWriter.Write(GetMessageBytes().Span);
             return bufferWriter.WrittenSpan.ToArray();
         }
 
-        private byte[] GetMessageTypeBytes()
-        {
-            var messageTypeValue = (byte)_message.MessageType;
-            return new byte[] { messageTypeValue };
-        }
-
-        private byte[] GetNotificationTypeBytes()
-        {
-            var notificationTypeValue = (byte)_message.NotificationType;
-            return new byte[] { notificationTypeValue };
-        }
+        // private byte[] GetNotificationTypeBytes()
+        // {
+        //     var notificationTypeValue = (byte)_message.NotificationType;
+        //     return new byte[] { notificationTypeValue };
+        // }
 
         private ReadOnlyMemory<byte> GetMessageBytes()
         {
             ArrayBufferWriter<byte> bufferWriter = new ArrayBufferWriter<byte>();
-            var messageBuffer = Encoding.UTF8.GetBytes(_message.Message);
-            var lenBytes = BitConverter.GetBytes(messageBuffer.Length);
-            bufferWriter.Write(lenBytes);
+         //   var messageBuffer = Encoding.UTF8.GetBytes(_message.Message);
+           using var stream = new MemoryStream();
+            JsonSerializer.SerializeAsync(stream, _message);
+            var messageBuffer =  stream.ToArray();
+            // var lenBytes = BitConverter.GetBytes(messageBuffer.Length);
+            // bufferWriter.Write(lenBytes);
             bufferWriter.Write(messageBuffer);
             return bufferWriter.WrittenMemory;
         }

+ 71 - 71
Adapter/JsonAdapter.cs

@@ -1,72 +1,72 @@
-using System;
-using System.IO;
-using System.Text.Json;
-
-namespace WingNotificationModule.Adapter
-{
-    /// <summary>
-    /// This is a utilities class for json serializer and deserializer.
-    /// </summary>
-    public class JsonAdapter
-    {
-        /// <summary>
-        /// Deserializer from json result.
-        /// </summary>
-        /// <typeparam name="T">Type of object.</typeparam>
-        /// <param name="jsonResult">Json string</param>
-        /// <returns>Instance of T.</returns>
-        public static T DeserializerJson<T>(string jsonResult, JsonSerializerOptions jsonSerializerOptions = null) where T : class
-        {
-            return JsonSerializer.Deserialize(jsonResult, typeof(T), jsonSerializerOptions) as T;
-        }
-
-        /// <summary>
-        /// Deserializer from object result.
-        /// </summary>
-        /// <typeparam name="T">Type of object.</typeparam>
-        /// <param name="jsonResult">Json string</param>
-        /// <returns>Instance of T.</returns>
-        public static T DeserializerObject<T>(object jsonObj) where T : class
-        {
-            var jsonDoc = JsonDocument.Parse(SerializerToJson(jsonObj));
-            return DeserializerJson<T>(jsonDoc.RootElement.GetRawText());
-        }
-
-        /// <summary>
-        /// Serialize from instance to json string
-        /// </summary>
-        /// <typeparam name="T">Type of object.</typeparam>
-        /// <param name="instance">Instance need to serialize.</param>
-        /// <param name="useJsonFormatter"></param>
-        /// <returns>The json string</returns>
-        public static string SerializerToJson<T>(T instance, JsonSerializerOptions jsonSerializerOptions = null)
-        {
-            return JsonSerializer.Serialize(instance);
-        }
-
-        /// <summary>
-        /// Deserializer json to object with json file
-        /// </summary>
-        /// <typeparam name="T">Convert type</typeparam>
-        /// <param name="jsonFilePath">Json file path</param>
-        /// <returns></returns>
-        public static T DeserializerJsonFile<T>(string jsonFilePath) where T : class
-        {
-            try
-            {
-                using (var stream = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
-                {
-                    using (var sr = new StreamReader(stream))
-                    {
-                        return DeserializerJson<T>(sr.ReadToEnd());
-                    }
-                }
-            }
-            catch (Exception exception)
-            {
-                Console.WriteLine($"JsonHelper_DeserializerJsonFile error:{exception}");
-                return default(T);
-            }
-        }
-    }
+using System;
+using System.IO;
+using System.Text.Json;
+
+namespace WingNotificationModule.Adapter
+{
+    /// <summary>
+    /// This is a utilities class for json serializer and deserializer.
+    /// </summary>
+    public class JsonAdapter
+    {
+        /// <summary>
+        /// Deserializer from json result.
+        /// </summary>
+        /// <typeparam name="T">Type of object.</typeparam>
+        /// <param name="jsonResult">Json string</param>
+        /// <returns>Instance of T.</returns>
+        public static T DeserializerJson<T>(string jsonResult, JsonSerializerOptions jsonSerializerOptions = null) where T : class
+        {
+            return JsonSerializer.Deserialize(jsonResult, typeof(T), jsonSerializerOptions) as T;
+        }
+
+        /// <summary>
+        /// Deserializer from object result.
+        /// </summary>
+        /// <typeparam name="T">Type of object.</typeparam>
+        /// <param name="jsonResult">Json string</param>
+        /// <returns>Instance of T.</returns>
+        public static T DeserializerObject<T>(object jsonObj) where T : class
+        {
+            var jsonDoc = JsonDocument.Parse(SerializerToJson(jsonObj));
+            return DeserializerJson<T>(jsonDoc.RootElement.GetRawText());
+        }
+
+        /// <summary>
+        /// Serialize from instance to json string
+        /// </summary>
+        /// <typeparam name="T">Type of object.</typeparam>
+        /// <param name="instance">Instance need to serialize.</param>
+        /// <param name="useJsonFormatter"></param>
+        /// <returns>The json string</returns>
+        public static string SerializerToJson<T>(T instance, JsonSerializerOptions jsonSerializerOptions = null)
+        {
+            return JsonSerializer.Serialize(instance);
+        }
+
+        /// <summary>
+        /// Deserializer json to object with json file
+        /// </summary>
+        /// <typeparam name="T">Convert type</typeparam>
+        /// <param name="jsonFilePath">Json file path</param>
+        /// <returns></returns>
+        public static T DeserializerJsonFile<T>(string jsonFilePath) where T : class
+        {
+            try
+            {
+                using (var stream = new FileStream(jsonFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
+                {
+                    using (var sr = new StreamReader(stream))
+                    {
+                        return DeserializerJson<T>(sr.ReadToEnd());
+                    }
+                }
+            }
+            catch (Exception exception)
+            {
+                Console.WriteLine($"JsonHelper_DeserializerJsonFile error:{exception}");
+                return default(T);
+            }
+        }
+    }
 }

+ 14 - 10
NotificationServer.cs

@@ -16,6 +16,7 @@ using WingNotificationModule.Channel.WebSocket;
 using System.Threading.Tasks;
 using WingNotificationModule.Adapter;
 using WingInterfaceLibrary.Enum.NotificationEnum;
+using WingInterfaceLibrary.Notifications;
 
 namespace WingNotificationModule
 {
@@ -86,7 +87,10 @@ namespace WingNotificationModule
                     //check token id valid
                     if (string.IsNullOrEmpty(token))
                     {
-                        await leaf.SendAsync(new NotifyMessage() { MessageType = MessageTypeEnum.Disconnect, Message = "Token can not be empty." });
+                        await leaf.SendAsync(new DisconnectNotification()
+                        {
+
+                        });
                         //scoketLeaf.Close(); //TODO if need to close leaf at server ?
                         return;
                     }
@@ -94,12 +98,13 @@ namespace WingNotificationModule
                     var result = await _authenticationService.ValidateTokenAsync(new ValidateTokenRequest() { Token = token });    //TODO do we need know why the token invalid ? 
                     if (result == null || result.Code != CustomerRpcCode.Ok)
                     {
-                        await leaf.SendAsync(new NotifyMessage() { MessageType = MessageTypeEnum.Disconnect, Message = "Invalid token." });
-                        //scoketLeaf.Close(); //TODO if need to close leaf at server ?
+                        await leaf.SendAsync(new DisconnectNotification()
+                        {
+                        });
                         return;
                     }
 
-                    //cache web socket connection                    
+                    //cache web socket connection
                     _leaves.AddOrUpdate(token, (t) =>
                     {
                         Logger.WriteLineInfo($"Websocket connection with token {token} status:{state}, add leaf");
@@ -110,8 +115,7 @@ namespace WingNotificationModule
                         exist.Close();
                         return leaf;
                     });
-
-                    await leaf.SendAsync(new NotifyMessage() { MessageType = MessageTypeEnum.Connection, Message = "Connected." });
+                    await leaf.SendAsync(new ConnectionNotification());
                 }
                 else
                 {
@@ -247,9 +251,9 @@ namespace WingNotificationModule
             /// The request message from caller
             /// </summary>
             /// <value></value>
-            public NotifyMessage Message { get; }
+            public object Message { get; }
 
-            public PostMessageParam(string token, NotifyMessage message)
+            public PostMessageParam(string token, object message)
             {
                 this.Token = token;
                 this.Message = message;
@@ -271,7 +275,7 @@ namespace WingNotificationModule
             /// </summary>        
             /// <param name="message">The message will be send to client</param>
             /// <returns></returns>
-            public async Task SendAsync(NotifyMessage message)
+            public async Task SendAsync(object message)
             {
                 if (_webSocketIO.IsDisconnected)
                 {
@@ -287,7 +291,7 @@ namespace WingNotificationModule
             /// </summary>        
             /// <param name="message">The message will be send to client</param>
             /// <returns></returns>
-            public void Send(NotifyMessage message)
+            public void Send(object message)
             {
                 if (_webSocketIO.IsDisconnected)
                 {

+ 1 - 0
Service/NotificationService.cs

@@ -9,6 +9,7 @@ using System.Collections.Generic;
 using WingInterfaceLibrary.DTO.Common;
 using JsonRpcLite.Services;
 using WingInterfaceLibrary.Enum;
+using WingInterfaceLibrary.Notifications;
 
 namespace WingNotificationModule.Service
 {