예제 #1
0
        public static void ChangeGroupMessage(SocketAsyncEventArgs e)
        {
            MClient        mClient = MClient.CreateInstance();
            AsyncUserToken token   = (AsyncUserToken)e.UserToken;
            //得到一个完整的包的数据,放入新list,第二个参数是数据长度,所以要减去8
            List <byte> onePackage = token.receiveBuffer.GetRange(8, token.packageLen - 8);

            //将复制出来的数据从receiveBuffer旧list中删除
            token.receiveBuffer.RemoveRange(0, token.packageLen);
            //list要先转换成数组,再转换成字符串
            String jsonStr = Encoding.Default.GetString(onePackage.ToArray());
            //得到用户名和密码
            JArray jArray = JArray.Parse(jsonStr);

            //先保存好友信息
            if (jArray[0]["isOk"].ToString().Equals("True"))
            {
                Console.WriteLine("保存好友信息");

                foreach (var obj in jArray)
                {
                    SqliteConnect.SaveFriendInfo(obj["id"].ToString(), obj["Group"].ToString(), obj["UserName"].ToString(), obj["RealName"].ToString(), obj["Sex"].ToString(),
                                                 obj["BirthDay"].ToString(), obj["Address"].ToString(), obj["Email"].ToString(), obj["PhoneNumber"].ToString(),
                                                 obj["Remarks"].ToString());
                }
            }
            //然后删除原分组List中的好友
            Application.Current.Dispatcher.Invoke(
                new Action(() =>
            {
                FriendListViewModel friendListViewModel = FriendListViewModel.CreateInstance();
                FriendEntity.InGroupListDelete(friendListViewModel.friendGroups, jArray[0]["id"].ToString());
            })
                );
        }
예제 #2
0
        public static void UserMessageDeal(SocketAsyncEventArgs e)
        {
            MClient        mClient = MClient.CreateInstance();
            AsyncUserToken token   = (AsyncUserToken)e.UserToken;
            //得到一个完整的包的数据,放入新list,第二个参数是数据长度,所以要减去8
            List <byte> onePackage = token.receiveBuffer.GetRange(8, token.packageLen - 8);

            //将复制出来的数据从receiveBuffer旧list中删除
            token.receiveBuffer.RemoveRange(0, token.packageLen);
            //list要先转换成数组,再转换成字符串
            String jsonStr = Encoding.Default.GetString(onePackage.ToArray());

            //得到用户名和密码
            Console.WriteLine("jsonStr = " + jsonStr);
            JArray jArray = JArray.Parse(jsonStr);

            if (jArray[0]["isOk"].ToString().Equals("True"))
            {
                Console.WriteLine("保存用户消息");

                foreach (var obj in jArray)
                {
                    SqliteConnect.SaveMessage(obj["FriendId"].ToString(), obj["Message"].ToString(), obj["MessageDate"].ToString());
                }
            }
        }
예제 #3
0
        //处理好友请求消息
        public static void FriendRequestMessageDeal(SocketAsyncEventArgs e)
        {
            MClient        mClient = MClient.CreateInstance();
            AsyncUserToken token   = (AsyncUserToken)e.UserToken;
            //得到一个完整的包的数据,放入新list,第二个参数是数据长度,所以要减去8
            List <byte> onePackage = token.receiveBuffer.GetRange(8, token.packageLen - 8);

            //将复制出来的数据从receiveBuffer旧list中删除
            token.receiveBuffer.RemoveRange(0, token.packageLen);
            //list要先转换成数组,再转换成字符串
            String jsonStr = Encoding.Default.GetString(onePackage.ToArray());
            //得到用户名和密码
            JArray jArray = JArray.Parse(jsonStr);

            if (jArray[0]["isOk"].ToString().Equals("True"))
            {
                Console.WriteLine("保存好友信息");

                foreach (var obj in jArray)
                {
                    SqliteConnect.SaveFriendRequestInfo(obj["id"].ToString(), obj["UserName"].ToString(), obj["RealName"].ToString(), obj["Sex"].ToString(),
                                                        obj["BirthDay"].ToString(), obj["Address"].ToString(), obj["Email"].ToString(), obj["PhoneNumber"].ToString(),
                                                        obj["Remarks"].ToString());
                }
            }
        }
예제 #4
0
        //删除好友
        public void DeleteFriend(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("删除该好友?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);

            if (MessageBoxResult.OK == result)
            {
                //进行删除好友的操作
                //将删除好友的信息发送给服务端,由服务端同时删除用户和好友的好友表中的对应ID
                JObject obj = new JObject();
                obj["Id"] = this.Id;
                String  str     = obj.ToString();
                MClient mClient = MClient.CreateInstance();
                mClient.SendDeleteFriend(str);
                //同时客户端本地将该好友从队列中删除
                SqliteConnect.DeleteFriendById(this.Id);
                //然后从好友队列中删除
                Application.Current.Dispatcher.Invoke(
                    new Action(() =>
                {
                    FriendListViewModel friendListViewModel = FriendListViewModel.CreateInstance();
                    FriendEntity.InGroupListDelete(friendListViewModel.friendGroups, this.Id);
                })
                    );
            }
        }
예제 #5
0
        /*
         * UpdateMap() is straight forward to understand.
         */
        internal static void UpdateMap(DateTimeOffset time)
        {
            PrimeDns.Log._LogInformation("Map Updater Started at Time : " + time.ToString(), Logger.ConstStartUp, null);
            Telemetry.Telemetry.PushStatusOfThread("MapUpdater", "Started");
            if (!SqliteConnect.CheckPrimeDnsState(AppConfig.ConstPrimeDnsMapCreated))
            {
                CreatePrimeDnsMap().Wait();
            }

            var t = new Task[2]
            {
                UpdatePrimeDnsMap(),
                Task.Delay(new TimeSpan(0, 0, 300))
            };

            var index = Task.WaitAny(t);

            if (index == 1)
            {
                var source = new CancellationTokenSource();
                PrimeDns.DnsResolverCancellationToken = source.Token;
                source.Cancel();
                t[0].Wait();
            }
            Telemetry.Telemetry.PushStatusOfThread("MapUpdater", "Ended");
            PrimeDns.Log._LogInformation("Map Updater Exited at Time : " + time.ToString(), Logger.ConstStartUp, null);
        }
예제 #6
0
        public static void DeleteFriendMessage(SocketAsyncEventArgs e)
        {
            MClient        mClient = MClient.CreateInstance();
            AsyncUserToken token   = (AsyncUserToken)e.UserToken;
            //得到一个完整的包的数据,放入新list,第二个参数是数据长度,所以要减去8
            List <byte> onePackage = token.receiveBuffer.GetRange(8, token.packageLen - 8);

            //将复制出来的数据从receiveBuffer旧list中删除
            token.receiveBuffer.RemoveRange(0, token.packageLen);
            //list要先转换成数组,再转换成字符串
            String jsonStr = Encoding.Default.GetString(onePackage.ToArray());

            //得到用户名和密码
            Console.WriteLine("jsonStr = " + jsonStr);
            JObject obj = JObject.Parse(jsonStr);

            //先从数据库中删除
            SqliteConnect.DeleteFriendById(obj["Id"].ToString());
            //然后从好友队列中删除
            Application.Current.Dispatcher.Invoke(
                new Action(() =>
            {
                FriendListViewModel friendListViewModel = FriendListViewModel.CreateInstance();
                FriendEntity.InGroupListDelete(friendListViewModel.friendGroups, obj["Id"].ToString());
            })
                );
        }
예제 #7
0
 public FriendListViewModel()
 {
     //查询数据库,拿到当前用户的所有信息,并保存在这个类里面
     SqliteConnect.QueryUserInfo(out FriendListViewModel.id, out FriendListViewModel.username, out FriendListViewModel.realname, out FriendListViewModel.sex, out FriendListViewModel.birthday, out FriendListViewModel.address, out FriendListViewModel.email, out FriendListViewModel.phonenumber, out FriendListViewModel.remark);
     //分组列表
     friendGroups      = new ObservableCollection <FriendGroup>();
     friendRequestList = new ObservableCollection <FriendEntity>();
     //启动一个线程,这个函数负责对好友列表界面进行维护
     scanThread = new Thread(FriendListUpdata);
     scanThread.Start();
 }
예제 #8
0
        /*
         * UpdateHostfile() - calls various other functions that have comments on them, so should be understandable.
         */
        internal void UpdateHostfile(DateTimeOffset time)
        {
            PrimeDns.Log._LogInformation("Host File Updater Started at Time : " + time.ToString(), Logger.ConstStartUp, null);
            Telemetry.Telemetry.PushStatusOfThread("HostFileUpdater", "Started");
            if (!SqliteConnect.CheckPrimeDnsState(AppConfig.ConstPrimeDnsSectionCreated))
            {
                CreatePrimeDnsSection();
                Telemetry.Telemetry.PushHostfileWrites();
                MapUpdater.UpdatePrimeDnsState(AppConfig.ConstPrimeDnsSectionCreated, 1);
            }
            var isPrimeDnsSectionOkay        = IntegrityChecker.CheckPrimeDnsSectionIntegrity(PrimeDns.Config.HostFilePath);
            var isMapUpdated                 = SqliteConnect.CheckPrimeDnsState(AppConfig.ConstPrimeDnsMapUpdated);
            var isHostFileUpdatedFromOutside = SqliteConnect.CheckPrimeDnsState(AppConfig.ConstPrimeDnsHostFileUpdatedFromOutside);

            if (isPrimeDnsSectionOkay && (isMapUpdated || isHostFileUpdatedFromOutside))
            {
                try
                {
                    var newPrimeDnsSectionEntries = GetPrimeDnsSectionEntries();
                    var hostfilePath = PrimeDns.Config.HostFilePath;
                    RemoveOldPrimeDnsSectionEntries(hostfilePath);
                    FindPrimeDnsSectionBegin(hostfilePath);
                    if (PrimeDnsBeginLine >= 0)
                    {
                        FileHelper.InsertIntoFile(hostfilePath, newPrimeDnsSectionEntries, PrimeDnsBeginLine + 1);
                    }
                    MapUpdater.UpdatePrimeDnsState(AppConfig.ConstPrimeDnsMapUpdated, 0);
                    MapUpdater.UpdatePrimeDnsState(AppConfig.ConstPrimeDnsHostFileUpdatedFromOutside, 0);
                    Telemetry.Telemetry.PushHostfileWrites();
                }
                catch (IOException ioe)
                {
                    PrimeDns.Log._LogError("Aggregate Exception occured while updating Hostfile - ", Logger.ConstHostFileIntegrity, ioe);
                    Telemetry.Telemetry.PushStatusOfThread("HostFileUpdater", "Failed");
                }
            }
            else if (!isPrimeDnsSectionOkay)
            {
                FileHelper.RemoveLineFromFile(PrimeDns.Config.HostFilePath, PrimeDns.Config.PrimeDnsSectionBeginString);
                FileHelper.RemoveLineFromFile(PrimeDns.Config.HostFilePath, PrimeDns.Config.PrimeDnsSectionEndString);
                CreatePrimeDnsSection();
                Telemetry.Telemetry.PushHostfileWrites();
                MapUpdater.UpdatePrimeDnsState(AppConfig.ConstPrimeDnsHostFileUpdatedFromOutside, 1);
                PrimeDns.Log._LogWarning("CheckPrimeDnsSectionIntegrity FAILED!!, Continuing..", Logger.ConstHostFileIntegrity, null);
            }
            Telemetry.Telemetry.PushStatusOfThread("HostFileUpdater", "Ended");
            PrimeDns.Log._LogInformation("Host File Updater Ended at Time : " + time.ToString(), Logger.ConstStartUp, null);

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
예제 #9
0
        /*
         * CreateTable_PrimeDNSMap() creates the table PrimeDNSMap.
         */
        private static void CreateTable_PrimeDNSMap()
        {
            var createCommand = "Create table " + AppConfig.ConstTableNamePrimeDnsMap +
                                " ( HostName varchar(100), IPAddressList varchar(200), LastUpdatedTime datetime, LastCheckedTime datetime, TimeToLiveInSeconds int )";

            try
            {
                var query = SqliteConnect.ExecuteNonQuery(createCommand, _mapConnectionString);
                PrimeDns.Log._LogInformation("Table PrimeDnsMap created successfully", Logger.ConstSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while creating table PrimeDNSMap.", Logger.ConstSqliteExecuteNonQuery, error);
            }
        }
예제 #10
0
        /*
         * CreateTable_PrimeDNSState() creates the table PrimeDNSState.
         */
        private static void CreateTable_PrimeDNSState()
        {
            var createCommand = "Create table " + AppConfig.ConstTableNamePrimeDnsState +
                                " ( FlagName varchar(100), FlagValue boolean )";

            try
            {
                var query = SqliteConnect.ExecuteNonQuery(createCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("Table PrimeDNSState created successfully", Logger.ConstSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while creating table PrimeDNSState.", Logger.ConstSqliteExecuteNonQuery, error);
            }
        }
예제 #11
0
        public void MessageUpdata()
        {
            while (true)
            {
                Application.Current.Dispatcher.Invoke(
                    new Action(() =>
                {
                    //从数据库中更新聊天消息
                    SqliteConnect.QueryMessage(this.NowName, this.UserName, this.FriendId, ref _messageMixGroup);
                })
                    );

                Thread.Sleep(2000);
            }
        }
예제 #12
0
        private static void UpdatePrimeDnsMapRow(string pDomain, int pUpdatedTtl)
        {
            var updateCommand = "UPDATE " + AppConfig.ConstTableNamePrimeDnsMap +
                                $" SET TimeToLiveInSeconds={pUpdatedTtl}" + $" WHERE HostName={pDomain}";

            try
            {
                SqliteConnect.ExecuteNonQuery(updateCommand, _mapConnectionString);
                //PrimeDns.logger._LogInformation("Updated PrimeDNSMap table successfully", Logger.Logger.CSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while updating PrimeDNSMap table for TTL Updater", Logger.Logger.ConstSqliteExecuteNonQuery, error);
            }
        }
예제 #13
0
        /*
         * UpdatePrimeDnsState() updates any given flag in the PrimeDns State table
         */

        public static void UpdatePrimeDnsState(string pFlagName, int pFlagValue)
        {
            var updateCommand = "UPDATE " + AppConfig.ConstTableNamePrimeDnsState + " " +
                                $"SET FlagValue={pFlagValue} WHERE FlagName=\"{pFlagName}\"";

            try
            {
                var numberOfRowsUpdated = SqliteConnect.ExecuteNonQuery(updateCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("PrimeDNSState table updated - # of rows updated - " + numberOfRowsUpdated, Logger.ConstSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while updating PrimeDNSState table on Database", Logger.ConstSqliteExecuteNonQuery, error);
            }
        }
예제 #14
0
        /*
         * DeletePrimeDnsMapRow() deletes row with pHostName from PrimeDNSMap Table.
         */
        private static void DeletePrimeDnsMapRow(string pHostName)
        {
            PrimeDns.Semaphore.Wait();
            var deleteCommand =
                "DELETE FROM " + AppConfig.ConstTableNamePrimeDnsMap + $" WHERE HostName=\"{pHostName}\"";

            try
            {
                var query = SqliteConnect.ExecuteNonQuery(deleteCommand, _mapConnectionString);
                //PrimeDns.logger._LogInformation("Deleted Row from PrimeDNSMap successfully", Logger.CSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while deleting row from PrimeDNSMap table", Logger.ConstSqliteExecuteNonQuery, error);
            }
            PrimeDns.Semaphore.Release();
        }
예제 #15
0
        /*
         * WriteToPrimeDnsMap() inserts a given row data into PrimeDNSMap Table.
         */
        public static void WriteToPrimeDnsMap(PrimeDnsMapRow pMapRowToBeInserted)
        {
            PrimeDns.Semaphore.Wait();
            var insertSql = "Insert into " + AppConfig.ConstTableNamePrimeDnsMap +
                            $" ( HostName, IPAddressList, LastUpdatedTime, LastCheckedTime, TimeToLiveInSeconds) values (\"{pMapRowToBeInserted.HostName}\", \"{pMapRowToBeInserted.GetStringOfIpAddressList()}\", \"{pMapRowToBeInserted.LastUpdatedTime}\", \"{pMapRowToBeInserted.LastCheckedTime}\", {pMapRowToBeInserted.TimeToLiveInSeconds})";

            try
            {
                var query = SqliteConnect.ExecuteNonQuery(insertSql, _mapConnectionString);
                //PrimeDns.logger._LogInformation("Data inserted into PrimeDNSMap table successfully", Logger.CSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while inserting data into PrimeDNSMap table", Logger.ConstSqliteExecuteNonQuery, error);
            }
            PrimeDns.Semaphore.Release();
        }
예제 #16
0
        /*
         * UpdatePrimeDnsMapRow() updates the row containing the mentioned hostName to newly passed values in PrimeDNSMap Table.
         */
        private static void UpdateLastCheckedTime(PrimeDnsMapRow pUpdatedMapRow)
        {
            PrimeDns.Semaphore.Wait();
            var updateCommand = "UPDATE " + AppConfig.ConstTableNamePrimeDnsMap +
                                $" SET LastCheckedTime=\"{pUpdatedMapRow.LastCheckedTime}\" " +
                                $" WHERE HostName=\"{pUpdatedMapRow.HostName}\"";

            try
            {
                var query = SqliteConnect.ExecuteNonQuery(updateCommand, _mapConnectionString);
                //PrimeDns.logger._LogInformation("Updated PrimeDNSMap table successfully", Logger.CSqliteExecuteNonQuery, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while updating PrimeDNSMap table for Last Checked Time", Logger.ConstSqliteExecuteNonQuery, error);
            }
            PrimeDns.Semaphore.Release();
        }
예제 #17
0
        public static void UserInfoDeal(SocketAsyncEventArgs e)
        {
            MClient        mClient = MClient.CreateInstance();
            AsyncUserToken token   = (AsyncUserToken)e.UserToken;
            //得到一个完整的包的数据,放入新list,第二个参数是数据长度,所以要减去8
            List <byte> onePackage = token.receiveBuffer.GetRange(8, token.packageLen - 8);

            //将复制出来的数据从receiveBuffer旧list中删除
            token.receiveBuffer.RemoveRange(0, token.packageLen);
            Console.WriteLine("清除receiveBuffer中的数据 , token.packageLen = " + token.packageLen);
            //list要先转换成数组,再转换成字符串
            String jsonStr = Encoding.Default.GetString(onePackage.ToArray());
            //得到用户名和密码
            JObject obj = JObject.Parse(jsonStr);

            //如果传回来的用户信息是正确的
            if (obj["isOk"].ToString().Equals("True"))
            {
                Console.WriteLine("保存自己的信息");
                //先初始化数据库的静态变量(这里是用id合成数据库名)
                SqliteConnect.SqliteInit(obj["id"].ToString());
                //然后创建好友表和信息表(如果有,不会重复创建)
                SqliteConnect.CreateTable();
                //保存自己的最新信息到数据库
                SqliteConnect.SaveUserInfo(obj["id"].ToString(), obj["UserName"].ToString(), obj["RealName"].ToString(), obj["Sex"].ToString(),
                                           obj["BirthDay"].ToString(), obj["Address"].ToString(), obj["Email"].ToString(), obj["PhoneNumber"].ToString(),
                                           obj["Remark"].ToString());

                //主窗口隐藏
                Application.Current.Dispatcher.Invoke(new Action(() => { Application.Current.MainWindow.Hide(); }));
                //打开好友界面
                Application.Current.Dispatcher.Invoke(new Action(() => {
                    FriendListWindow friedListWindow = new FriendListWindow();
                    friedListWindow.Show();
                }));
            }
            else
            {
                MessageBox.Show("用户信息返回失败");
            }
        }
예제 #18
0
        public static void FriendInfoDeal(SocketAsyncEventArgs e)
        {
            MClient        mClient = MClient.CreateInstance();
            AsyncUserToken token   = (AsyncUserToken)e.UserToken;
            //得到一个完整的包的数据,放入新list,第二个参数是数据长度,所以要减去8
            List <byte> onePackage = token.receiveBuffer.GetRange(8, token.packageLen - 8);

            //将复制出来的数据从receiveBuffer旧list中删除
            token.receiveBuffer.RemoveRange(0, token.packageLen);
            //list要先转换成数组,再转换成字符串
            String jsonStr = Encoding.Default.GetString(onePackage.ToArray());
            //得到用户名和密码
            JArray jArray = JArray.Parse(jsonStr);


            if (jArray[0]["isOk"].ToString().Equals("True"))
            {
                Console.WriteLine("保存好友信息");

                //保存还没有更新前的时间,如果时间比这个时间还晚,说明是已经被删除的好友
                String updatetime = DateTime.Now.ToString();

                foreach (var obj in jArray)
                {
                    SqliteConnect.SaveFriendInfo(obj["id"].ToString(), obj["Group"].ToString(), obj["UserName"].ToString(), obj["RealName"].ToString(), obj["Sex"].ToString(),
                                                 obj["BirthDay"].ToString(), obj["Address"].ToString(), obj["Email"].ToString(), obj["PhoneNumber"].ToString(),
                                                 obj["Remarks"].ToString());
                }

                //在保存完好友信息后,就要根据更新时间对数据库表中的数据进行排查,删除掉这一次还没有更新的数据
                SqliteConnect.DeleteFriendByTime(updatetime);
            }
            else
            {
                //如果不进行这个补充,那么在只有一个好友,且服务端已经删除这个好友的情况下,客户端本地的该好友不会被删除
                String updatetime = DateTime.Now.ToString();
                SqliteConnect.DeleteFriendByTime(updatetime);
            }
        }
예제 #19
0
        public void FriendListUpdata()
        {
            //进行数据库查询,从好友信息表中获得好友的信息
            //这个查询函数最好可以直接对好友分组列表进行操作
            //即可以传入好友分组列表对象
            //将while写进invoke里面会造成界面卡死,推测Application.Current.Dispatcher.Invoke这个方法会占用界面线程
            //所以要把while写在外面,并设置阻塞,每5秒访问一次Application.Current.Dispatcher.Invoke方法更新好友列表
            //TODO  其实还是可以先用数据库读取完,得到结果再使用Application.Current.Dispatcher.Invoke方法,因为数据库操作还是很占时间的
            while (true)
            {
                // MessageBox.Show("这里就查询了一次");
                Application.Current.Dispatcher.Invoke(
                    new Action(() =>
                {
                    //更新好友列表信息
                    SqliteConnect.QueryFriendInfo(ref _friends);
                    //更新好友请求信息
                    SqliteConnect.QueryFriendRequestInfo(ref friendRequestList);
                })
                    );

                Thread.Sleep(5000);
            }
        }
예제 #20
0
        /*
         * CreatePrimeDnsMap() creates the table PrimeDNSMap,
         * And also inserts the resolved DNS Data for all the valid domain names from Domains.json into this table.
         */
        internal static async Task CreatePrimeDnsMap()
        {
            var isPrimeDnsMapPresent = SqliteConnect.IsTablePresent(AppConfig.ConstTableNamePrimeDnsMap, _mapConnectionString);

            if (isPrimeDnsMapPresent)
            {
                PrimeDns.Log._LogWarning("PrimeDNSMap Table present in DB, dropping it and creating again.", Logger.ConstPrimeDnsStateIntegrity, null);
                SqliteConnect.DropTable(AppConfig.ConstTableNamePrimeDnsMap, _mapConnectionString);
            }
            CreateTable_PrimeDNSMap();
            UpdatePrimeDnsState(AppConfig.ConstPrimeDnsMapCreated, 1);
            UpdatePrimeDnsState(AppConfig.ConstPrimeDnsMapUpdated, 1);

            var criticalDomains = PrimeDns.DomainsConfig.GetCriticalDomains();

            if (criticalDomains == null)
            {
                return;
            }

            var source = new CancellationTokenSource();

            PrimeDns.DnsResolverCancellationToken = source.Token;

            var tasks = new List <Task <Tuple <PrimeDnsMapRow, bool> > >();

            foreach (string domain in criticalDomains)
            {
                if (DomainsConfig.IsDomainNameValid(domain))
                {
                    var mapRow = new PrimeDnsMapRow(domain);
                    tasks.Add(DoWorkAsync(mapRow, PrimeDns.DnsResolverCancellationToken));
                }
                else
                {
                    PrimeDns.Log._LogWarning("Invalid Domain Name - " + domain + " Found in File!", Logger.ConstDomainsWatcher, null);
                    Telemetry.Telemetry.PushDnsCallsData(domain, "Failure", "InvalidDomain", 0, 0, "INVALID-DOMAIN");
                }

                if (tasks.Count < PrimeDns.Config.ParallelDnsCallsLimit)
                {
                    continue;
                }
                foreach (var(item1, item2) in await Task.WhenAll(tasks))
                {
                    if (item2)
                    {
                        WriteToPrimeDnsMap(item1);
                        //Console.WriteLine("Ending Dns Resolver {0}", task.Item1.HostName);
                    }
                    else
                    {
                        PrimeDns.Log._LogInformation("Failure in adding New Domain to PrimeDNSMap " + item1.HostName, Logger.ConstDomainsWatcher, null);
                        try
                        {
                            if (!PrimeDns.DomainsConfig.DomainYetToBeAddedToMap[item1.HostName])
                            {
                                PrimeDns.DomainsConfig.DomainYetToBeAddedToMap[item1.HostName] = true;
                            }
                        }
                        catch (KeyNotFoundException)
                        {
                            PrimeDns.DomainsConfig.DomainYetToBeAddedToMap.Add(item1.HostName, true);
                        }
                    }
                }
                tasks.Clear();
            }

            if (tasks.Count > 0)
            {
                foreach (var(item1, item2) in await Task.WhenAll(tasks))
                {
                    if (item2)
                    {
                        WriteToPrimeDnsMap(item1);
                        //Console.WriteLine("Ending Dns Resolver {0}", task.Item1.HostName);
                    }
                    else
                    {
                        PrimeDns.Log._LogInformation("Failure in adding New Domain to PrimeDNSMap " + item1.HostName, Logger.ConstDomainsWatcher, null);
                        try
                        {
                            if (!PrimeDns.DomainsConfig.DomainYetToBeAddedToMap[item1.HostName])
                            {
                                PrimeDns.DomainsConfig.DomainYetToBeAddedToMap[item1.HostName] = true;
                            }
                        }
                        catch (KeyNotFoundException)
                        {
                            PrimeDns.DomainsConfig.DomainYetToBeAddedToMap.Add(item1.HostName, true);
                        }
                    }
                }
                tasks.Clear();
            }

            PrimeDns.Log._LogInformation("WriteToPrimeDNSMap Successful", Logger.ConstSqliteExecuteNonQuery, null);
        }
예제 #21
0
        /*
         * CreateAndInitializePrimeDnsState() does exactly what it says. Initializes all flags in PrimeDNSState.
         */
        internal static void CreateAndInitializePrimeDnsState(int pSectionCreatedFlag, int pMapCreatedFlag, int pCriticalDomainsUpdatedFlag, int pMapUpdatedFlag, int pHostFileUpdatedFromOutsideFlag)
        {
            CreateTable_PrimeDNSState();
            var insertCommand = "Insert into " + AppConfig.ConstTableNamePrimeDnsState +
                                $" values (\"{AppConfig.ConstPrimeDnsSectionCreated}\", {pSectionCreatedFlag})";

            try
            {
                SqliteConnect.ExecuteNonQuery(insertCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("Successfully Initialized PrimeDNSSectionCreated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while Initializing PrimeDNSSectionCreated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, error);
            }

            insertCommand = "Insert into " + AppConfig.ConstTableNamePrimeDnsState +
                            $" values (\"{AppConfig.ConstPrimeDnsMapCreated}\", {pMapCreatedFlag})";
            try
            {
                SqliteConnect.ExecuteNonQuery(insertCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("Successfully Initialized PrimeDNSMapCreated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while Initializing PrimeDNSMapCreated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, error);
            }

            insertCommand = "Insert into " + AppConfig.ConstTableNamePrimeDnsState +
                            $" values (\"{AppConfig.ConstPrimeDnsCriticalDomainsUpdated}\", {pCriticalDomainsUpdatedFlag})";
            try
            {
                SqliteConnect.ExecuteNonQuery(insertCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("Successfully Initialized PrimeDNSCriticalDomainsUpdated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while Initializing PrimeDNSCriticalDomainsUpdated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, error);
            }

            insertCommand = "Insert into " + AppConfig.ConstTableNamePrimeDnsState +
                            $" values (\"{AppConfig.ConstPrimeDnsMapUpdated}\", {pMapUpdatedFlag})";
            try
            {
                SqliteConnect.ExecuteNonQuery(insertCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("Successfully Initialized PrimeDNSMapUpdated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while Initializing PrimeDNSMapUpdated in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, error);
            }

            insertCommand = "Insert into " + AppConfig.ConstTableNamePrimeDnsState +
                            $" values (\"{AppConfig.ConstPrimeDnsHostFileUpdatedFromOutside}\", {pHostFileUpdatedFromOutsideFlag})";
            try
            {
                SqliteConnect.ExecuteNonQuery(insertCommand, _stateConnectionString);
                PrimeDns.Log._LogInformation("Successfully Initialized PrimeDnsHostFileUpdatedFromOutside in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, null);
            }
            catch (Exception error)
            {
                PrimeDns.Log._LogError("Error occured while Initializing PrimeDnsHostFileUpdatedFromOutside in the PrimeDNSState", Logger.ConstPrimeDnsStateIntegrity, error);
            }
        }