예제 #1
0
        public string ProcessMessage(string message, ChatHistory chat)
        {
            try
            {
                var parsedTime = DateTime.ParseExact(message, "HH:mm",
                                                     System.Globalization.CultureInfo.InvariantCulture);
                int      minutesMultiplier = 60;
                DateTime eventDate         = chat.EventDate.AddMinutes(parsedTime.Hour * minutesMultiplier + parsedTime.Minute);
                if (eventDate < DateTime.Now.Date)
                {
                    return(Resource.ResponseMessages.TIME_SMALLER_THAN_NOW);
                }

                var eventToAdd = new IncomingEvent()
                {
                    ChatId         = chat.Id,
                    Description    = chat.Description,
                    InvocationTime = eventDate
                };

                this.eventStorageService.AddEventToStore(eventToAdd);
                this.chatStorageService.RemoveChat(chat);
                return(Resource.ResponseMessages.TIME_RESPONSE_MESSAGE);
            }
            catch (Exception)
            {
                return(Resource.ResponseMessages.TIME_CANNOT_PARSE);
            }
        }
예제 #2
0
        public async Task FetchHistory(int currentuserid, int respectiveUserid)
        {
            string groupname = "";
            int    i         = currentuserid;
            int    j         = respectiveUserid;

            if (i < j)
            {
                groupname = i + "-" + j;
            }
            else
            {
                groupname = j + "-" + i;
            }
            await Groups.AddToGroupAsync(Context.ConnectionId, groupname);

            ChatHistory chatHistory = await appContext.ChatHistory.Where(p => p.UserId == currentuserid && p.GrpName == groupname).FirstOrDefaultAsync();

            string history;

            if (chatHistory == null)
            {
                chatHistory          = new ChatHistory();
                chatHistory.UserId   = currentuserid;
                chatHistory.ChatData = "";
                chatHistory.GrpName  = groupname;
                appContext.ChatHistory.Add(chatHistory);
                await appContext.SaveChangesAsync();
            }
            history = chatHistory.ChatData;

            SaveLog("FetchHistory for Userid " + currentuserid + " with connection id" + Context.ConnectionId + " for respective user " + respectiveUserid + " Group Name " + groupname + " History " + history);

            await Clients.Client(Context.ConnectionId).SendAsync("OpenChatWi", appContext.ChatMessage.Where(p => p.IsLoggedIn == 1), respectiveUserid, history);
        }
예제 #3
0
        public void SetupHere()
        {
            var chatAuthenticationService = new Mock <IChatAuthenticationService>();

            chatAuthenticationService.Setup(m => m.GetUser(It.IsAny <string>()))
            .ReturnsAsync(new ChatUser("peter#123", "AB", new ProfilePicture()));
            _chatAuthenticationService = chatAuthenticationService.Object;
            _banRepository             = new Mock <IBanRepository>().Object;
            _connectionMapping         = new ConnectionMapping();
            _chatHistory        = new ChatHistory();
            _settingsRepository = new SettingsRepository(MongoClient);
            _chatHub            = new ChatHub(_chatAuthenticationService, _banRepository, _settingsRepository,
                                              _connectionMapping, _chatHistory, null, null);

            var clients = new Mock <IHubCallerClients>();

            clients.Setup(c => c.Group(It.IsAny <string>())).Returns(new Mock <IClientProxy>().Object);
            clients.Setup(c => c.Caller).Returns(new Mock <IClientProxy>().Object);
            _chatHub.Clients = clients.Object;

            var context = new Mock <HubCallerContext>();

            context.Setup(c => c.ConnectionId).Returns("TestId");
            _chatHub.Context = context.Object;
            _chatHub.Groups  = new Mock <IGroupManager>().Object;
        }
예제 #4
0
 public async Task <IActionResult> SaveMessageAsync(ChatHistory message)
 {
     message.FromUserId  = _currentUserService.UserId;
     message.ToUserId    = message.ToUserId;
     message.CreatedDate = DateTime.Now;
     return(Ok(await _chatService.SaveMessageAsync(message)));
 }
예제 #5
0
 public string ProcessMessage(string message, ChatHistory chat)
 {
     chat.ChatProgress = ChatStatusEnum.DescriptionEntered;
     chat.Description  = message;
     this.chatStorageService.AddUpdateChat(chat);
     return(Resource.ResponseMessages.DESCRIPTION_RESPONSE_MESSAGE);
 }
예제 #6
0
        //Constructor used for application code
        public MessageHistoryViewModel(GroupsContent group)
        {
            composeCommand  = new DelegateCommand(toggleCanvasView);
            receiveCommand  = new DelegateCommand(receive);
            addCommand      = new DelegateCommand(addUsers);
            sendTextCommand = new DelegateCommand(sendText);

            model      = new MessageHistoryModel();
            navService = NavigationService.getNavigationServiceInstance();

            LoadingIndicator = true;
            History          = new ChatHistory(group.group.id);
            LoadingIndicator = false;

            this.group = group;

            // replace with group name when field is supplied
            if (group.group.Name != null)
            {
                this._groupName = group.group.Name;
            }
            else
            {
                this._groupName = "GROUP NAME";
            }
        }
예제 #7
0
        /// <summary>
        /// Called when somebody joins the room. Should call base.
        /// </summary>
        public virtual void SendHistory(Connection connection)
        {
            if (IsPrivate)
            {
                if (connection.Session == null)
                {
                    ClearScrollbackFor(connection);
                    connection.SendSysMessage("You must login to view this room.");
                    return;
                }

                if (IsBanned(connection.Session.Account.Name))
                {
                    ClearScrollbackFor(connection);
                    connection.SendSysMessage("You are banned from this room.");
                    return;
                }
            }

            var lines       = GetHistoryLines(connection);
            var chatHistory = new ChatHistory {
                ShortName = RoomInfo.ShortName, Requested = false, Lines = lines
            };

            connection.Send(chatHistory);
        }
예제 #8
0
 // Scroll chat when text changed
 private void ChatHistory_TextChanged(object sender, EventArgs e)
 {
     ChatHistory.Font           = new Font("Microsoft Sans Serif", 8, FontStyle.Regular);
     ChatHistory.SelectionFont  = new Font("Microsoft Sans Serif", 8, FontStyle.Regular);
     ChatHistory.SelectionStart = ChatHistory.Text.Length;
     ChatHistory.ScrollToCaret();
 }
예제 #9
0
        private async Task SubmitAsync()
        {
            if (!string.IsNullOrEmpty(CurrentMessage) && !string.IsNullOrEmpty(CId))
            {
                //Save Message to DB
                var chatHistory = new ChatHistory()
                {
                    Message     = CurrentMessage,
                    ToUserId    = CId,
                    CreatedDate = DateTime.Now
                };
                var response = await _chatManager.SaveMessageAsync(chatHistory);

                if (response.Succeeded)
                {
                    var state = await _stateProvider.GetAuthenticationStateAsync();

                    var user = state.User;
                    CurrentUserId          = user.GetUserId();
                    chatHistory.FromUserId = CurrentUserId;
                    var userName = $"{user.GetFirstName()} {user.GetLastName()}";
                    await hubConnection.SendAsync("SendMessageAsync", chatHistory, userName);

                    CurrentMessage = string.Empty;
                }
                else
                {
                    foreach (var message in response.Messages)
                    {
                        _snackBar.Add(localizer[message], Severity.Error);
                    }
                }
            }
        }
예제 #10
0
        /// <inheritdoc />
        public void SendMessage(string message, string author = "Server", long playerId = 0, string font = MyFontEnum.Red)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            ChatHistory.Add(new ChatMessage(DateTime.Now, 0, author, message));
            if (_commandManager.IsCommand(message))
            {
                var response = _commandManager.HandleCommandFromServer(message);
                ChatHistory.Add(new ChatMessage(DateTime.Now, 0, author, response));
            }
            else
            {
                var msg = new ScriptedChatMsg {
                    Author = author, Font = font, Target = playerId, Text = message
                };
                MyMultiplayerBase.SendScriptedChatMessage(ref msg);
                var character = MySession.Static.Players.TryGetIdentity(playerId)?.Character;
                var steamId   = GetSteamId(playerId);
                if (character == null)
                {
                    return;
                }

                var addToGlobalHistoryMethod = typeof(MyCharacter).GetMethod("OnGlobalMessageSuccess", BindingFlags.Instance | BindingFlags.NonPublic);
                _networkManager.RaiseEvent(addToGlobalHistoryMethod, character, steamId, steamId, message);
            }
        }
        void ReleaseDesignerOutlets()
        {
            if (ChatHistory != null)
            {
                ChatHistory.Dispose();
                ChatHistory = null;
            }

            if (MessageBox != null)
            {
                MessageBox.Dispose();
                MessageBox = null;
            }

            if (ChatView != null)
            {
                ChatView.Dispose();
                ChatView = null;
            }

            if (SendButton != null)
            {
                SendButton.Dispose();
                SendButton = null;
            }
        }
        public async Task <IActionResult> PutChatHistory(int id, ChatHistory chatHistory)
        {
            if (id != chatHistory.Id)
            {
                return(BadRequest());
            }

            _context.Entry(chatHistory).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ChatHistoryExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <ActionResult <ChatHistory> > PostChatHistory([FromBody] ChatHistory chatHistory)
        {
            _context.ChatHistories.Add(chatHistory);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetChatHistory", new { id = chatHistory.Id }, chatHistory));
        }
예제 #14
0
        public void WhenMessageArrives(BrokeredMessage message)
        {
            var chatMessage = message.GetBody <ChatMessage>();

            //We must run on UI Thread!!
            Execute.OnUIThread(() => ChatHistory.Insert(0, chatMessage));
        }
예제 #15
0
        private void OnRecvChatMessage(IChannel channel, Message message)
        {
            Console.WriteLine("OnRecvChatMessage");
            CChatMessage request = message as CChatMessage;
            Player       player  = (Player)channel.GetContent();
            string       toWho   = request.toName;
            string       content = request.chatContext;

            SChatMessage chatMessage = new SChatMessage()
            {
                fromName    = player.user,
                chatContext = content,
            };

            // for debug
            Console.WriteLine("recieve chat msg from :{0}", player.user);

            if (toWho == "WorldChat")
            {
                chatMessage.fromName = toWho;
                player.Broadcast(chatMessage, true);
            }


            else
            {
                Player toPlayer = OnlinePlayers[toWho];
                toPlayer.connection.Send(chatMessage);
            }

            ChatHistory.Add(string.Format("('{0}','{1}','{2}','{3}')", player.user, toWho, content, System.DateTime.Now));
        }
예제 #16
0
        void ReleaseDesignerOutlets()
        {
            if (ChatHistory != null)
            {
                ChatHistory.Dispose();
                ChatHistory = null;
            }

            if (ChatInput != null)
            {
                ChatInput.Dispose();
                ChatInput = null;
            }

            if (ContainerTopConstraint != null)
            {
                ContainerTopConstraint.Dispose();
                ContainerTopConstraint = null;
            }

            if (InterfaceContainer != null)
            {
                InterfaceContainer.Dispose();
                InterfaceContainer = null;
            }

            if (ContainerBottomConstraint != null)
            {
                ContainerBottomConstraint.Dispose();
                ContainerBottomConstraint = null;
            }
        }
예제 #17
0
        private void Instance_MessageRecieved(ChatMsg msg, ref bool sendToOthers)
        {
            var message = ChatMessage.FromChatMsg(msg);

            ChatHistory.Add(message);
            MessageReceived?.Invoke(message, ref sendToOthers);
        }
예제 #18
0
        public HttpResponseMessage createMeeting(int chatRoomId)
        {
            VolunteerMatchDbContext db = new VolunteerMatchDbContext();

            try
            {
                var         chatMassages = db.ChatHistories.Where(x => x.chatRoomId == chatRoomId).ToList();
                ChatHistory meetingMsg   = chatMassages.Where(x => x.meetingMsg == true).FirstOrDefault();
                Meeting     meeting      = new Meeting()
                {
                    firstMemberId        = (int)meetingMsg.fromMemberId,
                    secondMemberId       = (int)meetingMsg.toMemberId,
                    meetingEventTitle    = meetingMsg.meetingEventTitle,
                    meetingUnixDate      = meetingMsg.meetingUnixDate,
                    didHappen            = false,
                    meetingDateLabel     = meetingMsg.meetingDateLabel,
                    meetingTimeLabel     = meetingMsg.meetingTimeLabel,
                    meetingLocationLabel = meetingMsg.meetingLocationLabel,
                    didPushSent          = false,
                };
                db.Meetings.Add(meeting);
                db.ChatHistories.Remove(meetingMsg);
                db.SaveChanges();



                return(Request.CreateResponse(HttpStatusCode.OK, "Meeting saved in DB!"));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
            }
        }
예제 #19
0
        public void TestAddDelete()
        {
            // 数据存储在文件中,每次运行只测试新加消息。
            using ChatHistory ch = new ChatHistory(".", 0, -1, -1);
            List <long> addedIds = new List <long>();

            for (int i = 0; i < 10; ++i)
            {
                addedIds.Add(ch.AddMessage("" + i, "" + i));
            }
            List <long> deletedIds = new List <long>();

            foreach (long id in addedIds)
            {
                if (id % 2 == 0)
                {
                    continue;
                }
                ch.DeleteMessage(id);
                deletedIds.Add(id);
            }

            for (int i = 0; i < addedIds.Count; ++i)
            {
                long id = addedIds[i];
                List <ChatHistoryMessage> msgs = ch.ReadMessage(id, 1);
                Assert.IsTrue(msgs.Count == 1);
                ChatHistoryMessage msg = msgs[^ 1];
예제 #20
0
파일: Startup.cs 프로젝트: dev-2-geek/Chat
        public async Task <object> Any(PostChatToChannel request)
        {
            // Ensure the subscription sending this notification is still active
            var sub = ServerEvents.GetSubscriptionInfo(request.From);

            if (sub == null)
            {
                throw HttpError.NotFound("Subscription {0} does not exist".Fmt(request.From));
            }

            var channel = request.Channel;

            var chatMessage = request.Message.IndexOf("{{", StringComparison.Ordinal) >= 0
                ? await HostContext.AppHost.ScriptContext.RenderScriptAsync(request.Message, new Dictionary <string, object> {
                [nameof(Request)] = Request
            })
                : request.Message;

            // Create a DTO ChatMessage to hold all required info about this message
            var msg = new ChatMessage
            {
                Id         = ChatHistory.GetNextMessageId(channel),
                Channel    = request.Channel,
                FromUserId = sub.UserId,
                FromName   = sub.DisplayName,
                Message    = chatMessage.HtmlEncode(),
            };

            // Check to see if this is a private message to a specific user
            if (request.ToUserId != null)
            {
                // Mark the message as private so it can be displayed differently in Chat
                msg.Private = true;
                // Send the message to the specific user Id
                await ServerEvents.NotifyUserIdAsync(request.ToUserId, request.Selector, msg);

                // Also provide UI feedback to the user sending the private message so they
                // can see what was sent. Relay it to all senders active subscriptions
                var toSubs = ServerEvents.GetSubscriptionInfosByUserId(request.ToUserId);
                foreach (var toSub in toSubs)
                {
                    // Change the message format to contain who the private message was sent to
                    msg.Message = $"@{toSub.DisplayName}: {msg.Message}";
                    await ServerEvents.NotifySubscriptionAsync(request.From, request.Selector, msg);
                }
            }
            else
            {
                // Notify everyone in the channel for public messages
                await ServerEvents.NotifyChannelAsync(request.Channel, request.Selector, msg);
            }

            if (!msg.Private)
            {
                ChatHistory.Log(channel, msg);
            }

            return(msg);
        }
예제 #21
0
        // Constructor to make the adminform connect to the server
        // Sees if the server sends "updated", if so: updates
        public AdminForm(ServerConnection server, int houseNumber, UserInfo user)
        {
            InitializeComponent();

            Task.Run(() =>
            {
                udpClient.Client.Bind(new IPEndPoint(0, server.GetAvailableUdpPort()));

                int attempts   = 0;
                string message = "";
                while (true)
                {
                    Thread.Sleep(200);

                    int count  = udpClient.Client.Available;
                    byte[] msg = new byte[count];

                    if (msg.Length == 0 && attempts < 100)
                    {
                        continue;
                    }
                    else if (attempts >= 100)
                    {
                    }
                    else if (msg.Length == 0)
                    {
                        continue;
                    }

                    if (attempts < 100)
                    {
                        udpClient.Client.Receive(msg);
                        message = Encoding.Default.GetString(msg, 0, msg.Length);
                    }

                    if (message.Contains("Updated") || attempts >= 100)
                    {
                        _user.StudentsInfo = server.GetUsersInfo(_user.HouseNumber);
                        _mandatoryRules    = server.GetMandatoryRules(_user.HouseNumber);
                        _houseRules        = server.GetHouseRules(_user.HouseNumber);
                        _complaints        = server.GetComplaints(_user.HouseNumber);
                        _messages          = server.GetMessages(_user.HouseNumber);
                    }
                    ;

                    attempts = 0;
                }
            });

            _houseNumber    = houseNumber;
            _server         = server;
            _mandatoryRules = server.GetMandatoryRules(houseNumber);
            _houseRules     = server.GetHouseRules(houseNumber);
            _complaints     = server.GetComplaints(houseNumber);
            _messages       = server.GetMessages(houseNumber);
            _user           = user;

            UpdateTick(false);
        }
예제 #22
0
        public ActionResult DeleteConfirmed(int id)
        {
            ChatHistory chatHistory = db.ChatHistory.Find(id);

            db.ChatHistory.Remove(chatHistory);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
예제 #23
0
        public void TestDeleteFile()
        {
            using ChatHistory ch = new ChatHistory(".", 0, -1, -1);
            long now = DateTime.Now.Ticks;

            ch.DeleteFileBefore(now);
            ch.DeleteContentFileBefore(now);
        }
예제 #24
0
        private void ClearScrollbackFor(Connection connection)
        {
            var chatHistory = new ChatHistory {
                ShortName = RoomInfo.ShortName, Requested = false, Lines = new List <HistoryLine>()
            };

            connection.Send(chatHistory);
        }
예제 #25
0
        public async Task <IResult> SaveMessageAsync(ChatHistory chatHistory)
        {
            var response = await _httpClient.PostAsJsonAsync(Routes.ChatEndpoint.SaveMessage, chatHistory);

            var data = await response.ToResult();

            return(data);
        }
예제 #26
0
        public void MostRecentZeroShouldReturnEmptyList()
        {
            ChatHistory history = new ChatHistory();

            history.AddMessage(message);

            Assert.That(history.MostRecent(0).Count == 0);
        }
        private void StartReadingChatServer()
        {
            var cts = new CancellationTokenSource();

            _ = m_chatService.ChatLogs()
                .ForEachAsync((x) => ChatHistory.Add($"{x.At.ToDateTime().ToString("HH:mm:ss")} {x.Name}: {x.Content}"), cts.Token);

            App.Current.Exit += (_, __) => cts.Cancel();
        }
예제 #28
0
 private void ChatHistoryTextChanged(object sender, TextChangedEventArgs e)
 {
     // If the chat box is already scrolled to the bottom, keep it at the bottom.
     // Otherwise, the user has scrolled up and we don't want to disturb them.
     if (ChatHistory.VerticalOffset + ChatHistory.ExtentHeight == ChatHistory.ViewportHeight)
     {
         ChatHistory.ScrollToEnd();
     }
 }
예제 #29
0
        public async Task <IResult> SaveMessageAsync(ChatHistory message)
        {
            message.ToUser = await _context.Users.Where(user => user.Id == message.ToUserId).FirstOrDefaultAsync();

            await _context.ChatHistories.AddAsync(message);

            await _context.SaveChangesAsync();

            return(Result.Success());
        }
예제 #30
0
        public ChatViewModel([NotNull] GablarskiSocialClient client, ChatHistory history)
        {
            if (client == null)
                throw new ArgumentNullException ("client");

            this.client = client;
            this.closeGroupCommand = new RelayCommand<Group> (CloseGroupCore);
            this.groups = new SelectedObservableCollection<Group, GroupViewModel> (client.Groups,
                g => new GroupViewModel (client, g, history.GetMessages (g)));
        }
예제 #31
0
        public async Task <IResult> SaveMessageAsync(ChatHistory <IChatUser> message)
        {
            message.ToUser = await _context.Users.Where(user => user.Id == message.ToUserId).FirstOrDefaultAsync();

            await _context.ChatHistories.AddAsync(_mapper.Map <ChatHistory <BlazorHeroUser> >(message));

            await _context.SaveChangesAsync();

            return(await Result.SuccessAsync());
        }
예제 #32
0
 public Channel( IrcChannelID id, Font.Library Library, Size ClientSize )
 {
     ID = id;
     History = new ChatHistory()
         { Bounds = new Rectangle( Margin, Margin, ClientSize.Width-2*Margin, ClientSize.Height-2*Margin )
         };
     Input = new TextBox()
         { MaxBounds = new Rectangle( 1*Margin, ClientSize.Height-100-Margin, ClientSize.Width-2*Margin, 100 )
         , Font = new Font( Library, "Uber Console", 5 ) { Color = Color.Black }
         , Text = ""
         , VerticalAlignment = VerticalAlignment.Bottom
         };
 }
예제 #33
0
    /// <summary>
    /// Reads the specified XML.
    /// </summary>
    /// works with url's and local paths(local paths dont work in webplayer).
    /// 
	/// @code
    /// public class Example : MonoBehaviour
    /// {
    /// 
    /// string buildingId = "0080200000490694";
    /// 
	/// ReadXML("www.domainname.com/table_export_adressen_Leeuwarden.xml",typeof(Records));//placed in Database.buildingInfoDict
    /// ReadXML("www.domainname.com/ChatHistory.xml", typeof(ChatHistory));//placed in Database.chatHistory
    /// ReadXML("ChatHistory.xml",typeof(ChatHistory));// points to projectPath\ChatHistory.xml next to projectPath\Assets
    /// 
    /// Info dictionaryElement = Database.FindBuilding(buildingId);
    /// Info dictionaryElementAlternate = Database.buildingInfoDict[buildingId];
    /// 
    /// }
	/// @endcode
	/// <param name="xmlName">Name of the XML to load.</param>
	/// <param name="type">The type of the info in the XML.</param>
    public static IEnumerator ReadXML(string url, System.Type type)
    {
        if (url.StartsWith("http"))
        {
            WWW w = new WWW(url);
            yield return w;

            if (w.isDone)
            {
                if (type == typeof(ChatHistory))
                {
                    Debug.Log("Loading history");
                    XmlSerializer serial = new XmlSerializer(typeof(ChatHistory));
                    StringReader reader = new StringReader(w.text);
                    chatHistory = (ChatHistory)serial.Deserialize(reader);
                }

                if (type == typeof(Records))
                {
                    Debug.Log("Loading Records");
                    XmlSerializer serial = new XmlSerializer(typeof(Records));
                    StringReader reader = new StringReader(w.text);
                    records = (Records)serial.Deserialize(reader);
                    loaded = true;
                    AddToDictionary();
                }
            }
        }
        else
        {
            FileStream file = new FileStream(Application.dataPath+"/"+url, FileMode.Open);
			if (type == typeof(Records))
            {
                XmlSerializer serial = new XmlSerializer(typeof(Records));
                records = (Records)serial.Deserialize(file);
                AddToDictionary();
                loaded = true;
            }
            if (type == typeof(ChatHistory))
            {
                XmlSerializer serial = new XmlSerializer(typeof(ChatHistory));
                chatHistory = (ChatHistory)serial.Deserialize(file);
            }
            Debug.Log("Loading Done!");
        
        }

       
    }
예제 #34
0
    /// <summary>
    /// Save an object like ChatHistory or Records to the xmlDoc.
    /// </summary>
    /// Only works local.
	/// 
	/// Example:
	/// @code
    /// public class Example : MonoBehaviour
    /// {
    /// 
    /// Bericht testBericht = new Bericht();
	/// testBericht.berichten = "Bericht";
	/// testBericht.datum = System.DataTime.now;
    /// 
	/// ChatHistory test = new ChatHistory();
    /// test.chatHistory = new List<Bericht>();
    /// test.chatHistory.Add(testBericht);
    /// 
    /// SaveXML("ChatHistory.xml",test,typeof(ChatHistory));
    /// 
    /// }
	/// @endcode
    /// 
    /// <param name="xmlDoc">Name of the XML document to save, if not existing creates new XML.</param>
    /// <param name="chatBericht">Chat bericht to save. (if has less than 1 element will create a empty XML)</param>
    /// <param name="type">type of the data to save(W.I.P), use typeof(ChatHistory).</param>
    public void SaveXML(string xmlDoc,ChatHistory chatBericht,System.Type type)
    {   
        FileStream file;
        XmlSerializer serial;

        if (File.Exists(xmlDoc)&& chatBericht.berichten.Count()>0)
        {
            file = new FileStream(xmlDoc, FileMode.Open);
            serial = new XmlSerializer(type);
            ChatHistory tempSave = (ChatHistory)serial.Deserialize(file);

            for (int i = 0; i < chatBericht.berichten.Count(); i++)
            {
                tempSave.berichten.Add(chatBericht.berichten[i]);
            }

            file.Dispose();
            file = new FileStream(xmlDoc, FileMode.Create);

            serial.Serialize(file,tempSave);
        }
        else
        {
            file = new FileStream(xmlDoc, FileMode.CreateNew);
            serial = new XmlSerializer(type);
            serial.Serialize(file, chatBericht);
        }
    }