public bool IsConnectionStop(string ConnectionId)
        {
            bool result = false;

            try
            {
                if (!string.IsNullOrEmpty(ConnectionId))
                {
                    Guid connection = Guid.Parse(ConnectionId);

                    using (var db = new LicensingEntities())
                    {
                        var Connections = db.Connection.Where(con => con.ConnectionID == connection);

                        if (Connections.Count() > 0)
                        {
                            var connectionItem = Connections.First();

                            if (connectionItem.StopCalled.HasValue)
                            {
                                if (!connectionItem.StopCalled.Value && !connectionItem.ReStarted)
                                {
                                    result = true;
                                    connectionItem.ReStarted = true;
                                    db.SaveChanges();
                                }
                                else
                                {
                                    result = false;
                                }

                            }
                            else
                            {
                                result = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                System.Diagnostics.Debug.WriteLine(ex);
            }finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return result;

        }
        public void OnConnected(ConnectionInfo connectionInfo)
        {
            connectionInfo.CurrentDateTime = DateTime.Now;

            lock (_entryObject)
            {
                logWrite(connectionInfo.ConnectionId, "OnConnected Start");

                connectionInfo.CurrentDateTime = DateTime.UtcNow;

                if (connectionInfo.Role == ((int)Role.user).ToString())
                {
                    using (var db = new LicensingEntities())
                    {
                        DateTime DateTimeNow = DateTime.UtcNow;

                        var myLicenses = db.LicenseUser.Where(
                            li => li.StartDateTime <= DateTimeNow &&
                            li.EndDateTime >= DateTimeNow &&
                            li.Company.ToLower() == connectionInfo.Company.ToLower() &&
                            li.ProjectType.ToLower() == connectionInfo.ProjectType.ToLower() &&
                            li.UserName.ToLower() == connectionInfo.UserName.ToLower()).ToList();

                        if (myLicenses.Count() == 1)
                        {
                            var myLicense = myLicenses.First();

                            joinLicense(connectionInfo.ConnectionId);

                            //라이센스 보유 중인 것.
                            SetConnection(connectionInfo, myLicense);
                        }
                        else if (myLicenses.Count() > 1)
                        {
                            logWrite(connectionInfo.ConnectionId, "라이센스가 중복되었습니다 Error");
                        }
                        else
                        {
                            GetLicenseProcess(connectionInfo);
                        }

                        Clients.Group(((int)Role.manager).ToString()).NewConnection(connectionInfo);
                    }
                }

                logWrite(connectionInfo.ConnectionId, "OnConnected End");
            }
        }
        public bool ErrorLog(string ConnectionId, string ErrorMsg)
        {
            bool resultLog = false;

            try
            {
                if (!string.IsNullOrEmpty(ConnectionId) && !string.IsNullOrEmpty(ErrorMsg))
                {
                    using (var db = new LicensingEntities())
                    {
                        Guid convert = Guid.Parse(ConnectionId);

                        var connectionItems = db.Connection.Where(id => id.ConnectionID == convert);

                        if (connectionItems.Count() > 0)
                        {
                            var connectionItem = connectionItems.First();

                            connectionItem.ErrorLog = ErrorMsg;

                            db.SaveChanges();

                            resultLog = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                resultLog = false;
                System.Diagnostics.Debug.WriteLine(ex);
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return resultLog;
        }
        public void IsLicense(string Company, string ProjectType, string UserName, string ConnectionId)
        {
            using (var db = new LicensingEntities())
            {
                DateTime DateTimeNow = DateTime.UtcNow;

                var myLicenses = db.LicenseUser.Where(
                              li => li.StartDateTime <= DateTimeNow &&
                              li.EndDateTime >= DateTimeNow &&
                              li.Company.ToLower() == Company.ToLower() &&
                              li.ProjectType.ToLower() == ProjectType.ToLower() &&
                              li.UserName.ToLower() == UserName.ToLower()).ToList();

                if(myLicenses.Count == 0)
                {
                    Guid id = Guid.Parse(ConnectionId);

                    int RoleNum = (int)Role.user;

                    var userInfos = db.User.Where(f => f.UserName.ToLower() == UserName.ToLower());

                    if(userInfos.Count() > 0)
                    {
                        RoleNum = userInfos.First().Role;
                    }

                    var connectionItems = db.Connection.Where(con => con.ConnectionID == id);

                    if(connectionItems.Count() > 0)
                    {
                        var connectionItem = connectionItems.First();

                       ConnectionInfo connectionInfo = new ConnectionInfo()
                       {
                           Company = Company,
                           UserName = UserName,
                           ConnectionId = ConnectionId,
                           ExtensionV1 = connectionItem.ExtensionV1,
                           ExtensionV2 = connectionItem.ExtensionV2,
                           ProjectType = ProjectType,
                           CurrentDateTime = DateTime.UtcNow,
                           Status = (int)ConnectionStatus.OnReConnected,
                           Transport = connectionItem.Transport,
                           UserAgent = connectionItem.UserAgent,
                           Role = RoleNum.ToString()
                       };
                        
                        hubConnection.connectionContext.tryConnection(connectionInfo);
                    }
                    
                }
            }
        }
        //현재 라이센스가 자기가 포함되어 있는지, 확인하고 Company에서 License Maxium확인소
        public void LicenseUpdate(ConnectionInfo connectionInfo)
        {
            lock(_entryObject)
            {
                connectionInfo.CurrentDateTime = DateTime.UtcNow;

                logWrite(connectionInfo.ConnectionId, connectionInfo.CurrentDateTime.ToString() + 
                        "," + "라이센스 업데이트!!!!");

                using (var db = new LicensingEntities())
                {
                    var licenses = db.LicenseUser.Where(license =>
                                license.UserName.ToLower() == connectionInfo.UserName.ToLower() &&
                                license.EndDateTime >= connectionInfo.CurrentDateTime).ToList();

                    System.Diagnostics.Debug.WriteLine("현재 라이센스 카운트 : "+licenses.Count);

                    if (licenses.Count < LicenseUpdateMaxium)
                    {
                        if (licenses.Count == 0)
                        {
                            logWrite(connectionInfo.ConnectionId, "라이센스가 없으면 라이센스 업데이트을 진행할 수 없다.");

                            var licenseUsers = db.LicenseUser.Where(license =>
                                       license.Company.ToLower() == connectionInfo.Company.ToLower() &&
                                       license.ProjectType.ToLower() == connectionInfo.ProjectType.ToLower() &&
                                       license.StartDateTime <= connectionInfo.CurrentDateTime &&
                                       license.EndDateTime >= connectionInfo.CurrentDateTime);

                            var lastLicense = licenseUsers.OrderBy(f => f.EndDateTime).First();

                            var nextLicenseTime = (lastLicense.EndDateTime - DateTime.UtcNow);
                            //라이센스가 초기화되기 전까지의 시간.
                            fullLicense(connectionInfo.ConnectionId, nextLicenseTime.ToString());
                           
                            return;
                        }

                        var LicenseInfos = db.LicenseCompany.Where(f => f.Company.ToLower() == connectionInfo.Company.ToLower() &&
                            f.ProjectType.ToLower() == connectionInfo.ProjectType.ToLower());

                        if (LicenseInfos.Count() > 0)
                        {
                            var licenseMaxium = LicenseInfos.First().LicenseMaxium;

                            if(licenseMaxium <  licenses.Count)
                            {
                                logWrite(connectionInfo.ConnectionId, "해당 프로젝트에는 라이센스 개수가 없습니다.");
                                fullLicense(connectionInfo.ConnectionId, "라이센스 개수 없음");
                                return;
                            }
                        }
                        else
                        {
                            logWrite(connectionInfo.ConnectionId, "회사 정보를 찾을 수 없습니다.");
                            fullLicense(connectionInfo.ConnectionId, "회사 정보를 찾을 수 없습니다.");
                            return;
                        }

                        var licenseOrderby = licenses.OrderBy(date => date.StartDateTime);

                        var recentlyLicense = licenseOrderby.First();

                        var licenseType = GetLicenseInfo(connectionInfo.Company, connectionInfo.ProjectType);

                        if(licenseType != int.MinValue)
                        {
                            connectionInfo.CurrentDateTime = recentlyLicense.EndDateTime;

                            var licenseuser = CreateLicense(connectionInfo, licenseType);

                            if (licenseuser != null)
                            {
                                joinLicense(connectionInfo.ConnectionId);

                                //라이센스 생성한 것.
                                SetConnection(connectionInfo, licenseuser);
                            }
                        }
                    }
                    else
                    {
                        joinLicense(connectionInfo.ConnectionId);
                    }
                }
            }
        }
        public void tryConnection(ConnectionInfo connectionInfo)
        {
           
            lock (_entryObject)
            {
                connectionInfo.CurrentDateTime = DateTime.UtcNow;

                logWrite(connectionInfo.ConnectionId, "tryConnection 잠금 구문에 진입했습니다!!!!! Start");

                using (var db = new LicensingEntities())
                {

                    var myLicenses = db.LicenseUser.Where(li => li.StartDateTime <= connectionInfo.CurrentDateTime &&
                                                         li.EndDateTime >= connectionInfo.CurrentDateTime &&
                                                        li.Company.ToLower() == connectionInfo.Company.ToLower() &&
                                                        li.ProjectType.ToLower() == connectionInfo.ProjectType.ToLower() &&
                                                        li.UserName.ToLower() == connectionInfo.UserName.ToLower());

                    if (myLicenses.Count() == 1)
                    {
                        var myLicense = myLicenses.First();
                        //라이센스 보유중인 것 
                        SetConnection(connectionInfo, myLicense);
                    }
                    else if (myLicenses.Count() > 1)
                    {
                        logWrite(connectionInfo.ConnectionId, "라이센스가 중복되었습니다 Error");
                    }
                    else
                    {
                        GetLicenseProcess(connectionInfo);
                    }

                    Clients.Group(((int)Role.manager).ToString()).NewConnection(connectionInfo);
                }

                logWrite(connectionInfo.ConnectionId, "tryConnection 잠금 구문에 진입했습니다!!!!! End");
            }
        }
        public void licenseCheck(object sender)
        {
            lock (_updateObject)
            {
                if (_updatingSwitch)
                {
                    _updatingSwitch = false;
                  
                    DateTime DateTimeNow = DateTime.UtcNow;

                    string datetimeNow = DateTimeNow.ToString("yyyy-MM-dd HH:mm:ss"); 

                    logWrite("Timer Call", "License Update " + datetimeNow);

                    using (var db = new LicensingEntities())
                    {
                        //Linq에서 날짜간의 Subtract는 어렵기 때문에 StoreProcedure로 변경.
                        var licenseUpdate = db.updateLicense(datetimeNow).ToList();
                        
                        licenseUpdate.ForEach(f =>
                        {
                            logWrite(f.ConnectionID.ToString(), "라이센스 업데이트 클라이언트에게 요청");

                            LicenseUpdateNotice(f.ConnectionID.ToString());
                        });
                    }

                    _updatingSwitch = true;
                }
            }
        }
        private void SetReConnection(ConnectionInfo reConnectionInfo)
        {
            Guid ConnectionID = Guid.Parse(reConnectionInfo.ConnectionId);

            using (var db = new LicensingEntities())
            {
                var users = db.User.Where(f => f.UserName == reConnectionInfo.UserName);

                if (users.Count() > 0)
                {
                    var user = users.First();
                    user.LastActivity = reConnectionInfo.CurrentDateTime;
                }
                else
                {
                    var user = new User
                    {
                        ID = Guid.NewGuid(),
                        UserName = reConnectionInfo.UserName,
                        Company = reConnectionInfo.Company,
                        ProjectType = reConnectionInfo.ProjectType,
                        Role = 1,
                        LastActivity = reConnectionInfo.CurrentDateTime
                    };

                    db.User.Add(user);
                }

                var _connections = db.Connection.Where(con => con.ConnectionID == ConnectionID);

                if (_connections.Count() > 0)
                {
                    var _connection = _connections.First();
                    _connection.ReConnectedDateTime = reConnectionInfo.CurrentDateTime;
                    _connection.LastActivity = reConnectionInfo.CurrentDateTime;
                    _connection.Status = (int)ConnectionStatus.OnReConnected;
                }
                else
                {
                    CreateConnection(reConnectionInfo);
                }

                db.SaveChanges();

            }
        }
        public void OnDisConnection(string ConnectionId, string UserName, DateTime currentDateTime, bool stopCall)
        {
            logWrite( ConnectionId,"DisConnection Start");

            var connectionId = Guid.Parse(ConnectionId);

             using (var db = new LicensingEntities())
            {
                var users = db.User.Where(f => f.UserName == UserName);

                if (users.Count() > 0)
                {
                    var user = users.First();
                    user.LastActivity = currentDateTime;
                }

                var _connections = db.Connection.Where(con => con.ConnectionID == connectionId);

                if (_connections.Count() > 0)
                {
                    var _connection = _connections.First();
                    _connection.Status = (int)ConnectionStatus.OnDisConnected;
                    _connection.LastActivity = currentDateTime;
                    _connection.StopCalled = stopCall;
                    _connection.DisConnectedDateTime = currentDateTime;
                }

                db.SaveChanges();
            }

            Clients.Group(((int)Role.manager).ToString()).DisConnection(ConnectionId);

            logWrite(ConnectionId, "DisConnection End");
        }
        private int GetLicenseInfo(string Company, string ProjectType)
        {
            int licenseType = int.MinValue;

            using (var db = new LicensingEntities())
            {
                var licenseCompany = db.LicenseCompany.Where(f => f.Company.ToLower() == Company.ToLower() &&
                                                             f.ProjectType.ToLower() ==ProjectType.ToLower());

                if(licenseCompany.Count() > 0)
                {

                    var licenseInfo = licenseCompany.First();
                    licenseType = licenseInfo.LicenseType;
                }
            }

            return licenseType;
        }
        private void GetLicenseProcess(ConnectionInfo connectionInfo)
        {
            if (_processSwitch)
            {
                _processSwitch = false;

                using (var db = new LicensingEntities())
                {
                    var licenseCompanys = db.LicenseCompany.Where(LC =>
                                                LC.Company.ToLower() == connectionInfo.Company.ToLower() &&
                                                LC.ProjectType.ToLower() == connectionInfo.ProjectType.ToLower());

                    if (licenseCompanys.Count() > 0)
                    {
                        var Companys = licenseCompanys.First();

                        var licenseUsers = db.LicenseUser.Where(license =>
                                                license.Company.ToLower() == connectionInfo.Company.ToLower() &&
                                                license.ProjectType.ToLower() == connectionInfo.ProjectType.ToLower() &&
                                                license.StartDateTime <= connectionInfo.CurrentDateTime &&
                                                license.EndDateTime >= connectionInfo.CurrentDateTime);

                        int currentLicense = licenseUsers.Count();


                        if (Companys.LicenseMaxium > currentLicense)
                        {
                            logWrite(connectionInfo.ConnectionId, "현재 라이센스 개수" + currentLicense.ToString());

                            var licenseItem = CreateLicense(connectionInfo, Companys.LicenseType);

                            if (licenseItem != null)
                            {
                                //라이센스 생성한 것을 마지막.
                                SetConnection(connectionInfo, licenseItem);

                                joinLicense(connectionInfo.ConnectionId);
                            }
                            else
                                logWrite(connectionInfo.ConnectionId, "라이센스 생성 실패");
                        }
                        else
                        {
                            if (licenseUsers.Count() > 0)
                            {
                                var lastLicense = licenseUsers.OrderBy(f => f.EndDateTime).First();

                                var nextLicenseTime = (lastLicense.EndDateTime - DateTime.UtcNow);
                                //라이센스가 초기화되기 전까지의 시간.
                                fullLicense(connectionInfo.ConnectionId, nextLicenseTime.ToString());
                            }
                            else
                            {
                                fullLicense(connectionInfo.ConnectionId, "License 적용되지않았습니다.");
                            }
                        }
                    }
                    else
                    {
                        logWrite(connectionInfo.ConnectionId, "라이센스 정보가 잘 못되었습니다.");
                    }
                }

                _processSwitch = true;
            }

        }
        private void CreateConnection(ConnectionInfo connectionInfo)
        {
            logWrite(connectionInfo.ConnectionId, "Connection 생성 중입니다.");

            using (var db = new LicensingEntities())
            {
                var _connection = new Connection
                {
                    ConnectionID = Guid.Parse(connectionInfo.ConnectionId),
                    UserAgent = (connectionInfo.UserAgent != null ? connectionInfo.UserAgent : string.Empty),
                    Company = connectionInfo.Company,
                    ProjectType = connectionInfo.ProjectType,
                    ConnectedDateTime = connectionInfo.CurrentDateTime,
                    Transport = connectionInfo.Transport,
                    LastActivity = connectionInfo.CurrentDateTime,
                    UserName = connectionInfo.UserName,
                    ExtensionV1 = connectionInfo.ExtensionV1,
                    ExtensionV2 = connectionInfo.ExtensionV2,
                    Status = connectionInfo.Status
                };

                db.Connection.Add(_connection);
                db.SaveChanges();

            }
        } 
        private LicenseUser CreateLicense(ConnectionInfo connectionInfo, int LicenseType)
        {
            LicenseUser newLicense = new LicenseUser();

            logWrite(connectionInfo.ConnectionId,"라이센스 타입 : " + LicenseType + "라이센스 생성 중..");

            try
            {
                using (var db = new LicensingEntities())
                {
                    newLicense = new LicenseUser()
                    {
                        ID = Guid.NewGuid(),
                        Company = connectionInfo.Company,
                        ProjectType = connectionInfo.ProjectType,
                        UserName = connectionInfo.UserName,
                        LicenseType = LicenseType,
                        StartDateTime = connectionInfo.CurrentDateTime,
                        EndDateTime = connectionInfo.CurrentDateTime.AddMinutes(LicenseType)
                    };

                    db.LicenseUser.Add(newLicense);
                    db.SaveChanges();
                   
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                newLicense = null;
            }

            return newLicense;
        }
        private void SetConnection(ConnectionInfo connectionInfo, LicenseUser licenseUser)
        {
            using (var db = new LicensingEntities())
            {
                Guid ConnectionID = Guid.Parse(connectionInfo.ConnectionId);

                var users = db.User.Where(f => f.UserName == connectionInfo.UserName);

                if (users.Count() == 0)
                {
                    int Isrole;

                    if(!int.TryParse(connectionInfo.Role, out Isrole))
                    {
                        Isrole = 1;
                    }

                    var user = new User
                    {
                        ID = Guid.NewGuid(),
                        UserName = connectionInfo.UserName,
                        Company = connectionInfo.Company,
                        ProjectType = connectionInfo.ProjectType,
                        Role = Isrole,
                        LastActivity = connectionInfo.CurrentDateTime
                    };

                    db.User.Add(user);
                }
                else
                {
                    var user = users.First();
                    user.LastActivity = DateTime.UtcNow;
                }

                db.SaveChanges();

                var _connections = db.Connection.Where(con => con.ConnectionID == ConnectionID);

                if (_connections.Count() == 0)
                {
                    CreateConnection(connectionInfo);
                }

                Clients.Client(connectionInfo.ConnectionId).licenseExpired(licenseUser.EndDateTime);
            }
        }