public static IFrameStream OpenFile(string fileName, out AdvFileMetadataInfo fileMetadataInfo, out GeoLocationInfo geoLocation)
        {
            fileMetadataInfo = new AdvFileMetadataInfo();
            geoLocation      = new GeoLocationInfo();
            try
            {
                IFrameStream rv = new AstroDigitalVideoStreamV2(fileName, ref fileMetadataInfo, ref geoLocation);

                TangraContext.Current.RenderingEngine = fileMetadataInfo.Engine == "AAV" ? "AstroAnalogueVideo" : "AstroDigitalVideo";

                if (fileMetadataInfo.Engine == "AAV")
                {
                    UsageStats.Instance.ProcessedAavFiles++;
                }
                else
                {
                    UsageStats.Instance.ProcessedAdvFiles++;
                }
                UsageStats.Instance.Save();

                return(rv);
            }
            catch (ADVFormatException ex)
            {
                MessageBox.Show(ex.Message, "Error opening ADV/AAV file", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(null);
        }
Пример #2
0
 public LocationDescriptionViewModel(GeoCoordinate geoCoordinate)
 {
     Location = new GeoLocationInfo
     {
         Latitude  = geoCoordinate.Latitude,
         Longitude = geoCoordinate.Longitude,
     };
 }
        private void CheckAdvFileFormat(string fileName, ref AdvFileMetadataInfo fileMetadataInfo, ref GeoLocationInfo geoLocation)
        {
            AdvFile advFile = AdvFile.OpenFile(fileName);

            CheckAdvFileFormatInternal(advFile);

            fileMetadataInfo.Recorder = advFile.AdvFileTags["RECORDER"];
            fileMetadataInfo.Camera   = advFile.AdvFileTags["CAMERA-MODEL"];
            fileMetadataInfo.Engine   = advFile.AdvFileTags["FSTF-TYPE"];

            engine = fileMetadataInfo.Engine;

            if (engine == "ADV")
            {
                advFile.AdvFileTags.TryGetValue("ADVR-SOFTWARE-VERSION", out fileMetadataInfo.AdvrVersion);
                if (string.IsNullOrWhiteSpace(fileMetadataInfo.AdvrVersion))
                {
                    advFile.AdvFileTags.TryGetValue("RECORDER-SOFTWARE-VERSION", out fileMetadataInfo.AdvrVersion);
                }

                advFile.AdvFileTags.TryGetValue("HTCC-FIRMWARE-VERSION", out fileMetadataInfo.HtccFirmareVersion);
                fileMetadataInfo.SensorInfo = advFile.AdvFileTags["CAMERA-SENSOR-INFO"];

                advFile.AdvFileTags.TryGetValue("OBJNAME", out fileMetadataInfo.ObjectName);

                advFile.AdvFileTags.TryGetValue("LONGITUDE-WGS84", out geoLocation.Longitude);
                advFile.AdvFileTags.TryGetValue("LATITUDE-WGS84", out geoLocation.Latitude);
                advFile.AdvFileTags.TryGetValue("ALTITUDE-MSL", out geoLocation.Altitude);
                advFile.AdvFileTags.TryGetValue("MSL-WGS84-OFFSET", out geoLocation.MslWgs84Offset);

                if (!string.IsNullOrEmpty(geoLocation.MslWgs84Offset) &&
                    !geoLocation.MslWgs84Offset.StartsWith("-"))
                {
                    geoLocation.MslWgs84Offset = "+" + geoLocation.MslWgs84Offset;
                }

                advFile.AdvFileTags.TryGetValue("GPS-HDOP", out geoLocation.GpsHdop);
            }
            else if (engine == "AAV")
            {
                advFile.AdvFileTags.TryGetValue("OCR-ENGINE", out OcrEngine);
                string sCorr;
                int    iCorr;
                if (advFile.AdvFileTags.TryGetValue("CAPHNTP-TIMING-CORRECTION", out sCorr) &&
                    int.TryParse(sCorr, out iCorr))
                {
                    fileMetadataInfo.HasNTPTimeStamps = true;
                }
                advFile.AdvFileTags.TryGetValue("OBJECT", out fileMetadataInfo.ObjectName);
            }

            this.geoLocation = new GeoLocationInfo(geoLocation);
        }
Пример #4
0
        public GeoLocationInfo GetGeolocationInfo()
        {
            WebClient webClient  = new WebClient();
            string    externalIp = webClient
                                   .DownloadString("http://icanhazip.com");

            string ipStackAccessKey = "1919678931125515ad3f7b04e39ce87e";
            string ipStackUrl       = $"api.ipstack.com/{externalIp}?access_key={ipStackAccessKey}";

            ipStackUrl = "http://" + ipStackUrl;

            string          ipInfoAsJson    = webClient.DownloadString(ipStackUrl);
            GeoLocationInfo geolocationInfo = JsonConvert.DeserializeObject <GeoLocationInfo>(ipInfoAsJson);

            return(geolocationInfo);
        }
Пример #5
0
        private bool IsValidUser(UserLogOnViewModel model)
        {
            model.GeoLocation = GeoLocationInfo.GetGeolocationInfo();

            //проверяем, есть ли емейл в базе
            var user = _identityDbContext.ApplicationUsers.Include("ApplicationUserPasswordHistories")
                       .SingleOrDefault(p => p.Email == model.Email);

            if (user == null)
            {
                throw new Exception($"Пользователя с email {model.Email} нет в базе");
            }

            //проверяем, подходит ли пароль емейлу
            var userPassword = user.ApplicationUserPasswordHistories.SingleOrDefault(p => p.Password == model.Password);

            if (userPassword == null)
            {
                user.FailedSignInCount += 1;
                _identityDbContext.SaveChanges();
                throw new Exception("Неверный пароль");
            }
            if (userPassword != null && userPassword.InvalidatedDate != null)
            {
                user.FailedSignInCount += 1;
                _identityDbContext.SaveChanges();
                throw new Exception("Аккаунт пользователя заблокирован");
            }

            //добавляем строку нового входа в таблице ApplicationUserSignInHistories в БД
            ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
            {
                Id = Guid.NewGuid(),
                ApplicationUserId = user.Id,
                SignInTime        = DateTime.Now,
                MachineIp         = model.GeoLocation.ip,
                IpToGeoCountry    = model.GeoLocation.country_name,
                IpToGeoCity       = model.GeoLocation.city,
                IpToGeoLatitude   = model.GeoLocation.latitude,
                IpToGeoLongitude  = model.GeoLocation.longitude
            };

            _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
            _identityDbContext.SaveChanges();

            return(true);
        }
Пример #6
0
        public GeoLocationInfo GetGeolocationInfo()
        {
            WebClient webClient  = new WebClient();
            string    externalIp = webClient
                                   .DownloadString("http://icanhazip.com");

            string ipStackAccessKey = "cb6a8892805bdd4727b7669b1f584318";
            string ipStackUrl       = $"api.ipstack.com/{externalIp}?access_key={ipStackAccessKey}";

            ipStackUrl = "http://" + ipStackUrl;

            string ipInfoAsJson = webClient.DownloadString(ipStackUrl);

            GeoLocationInfo geoLocationInfo = JsonConvert.DeserializeObject <GeoLocationInfo>(ipInfoAsJson);

            return(geoLocationInfo);
        }
Пример #7
0
        public static IFrameStream OpenFile(string fileName, out AdvFileMetadataInfo fileMetadataInfo, out GeoLocationInfo geoLocation)
        {
            fileMetadataInfo = new AdvFileMetadataInfo();
            geoLocation      = new GeoLocationInfo();
            try
            {
                int version = TangraCore.ADV2GetFormatVersion(fileName);

                IFrameStream rv;
                if (version == 1)
                {
                    var adv1 = new AstroDigitalVideoStream(fileName, ref fileMetadataInfo, ref geoLocation);
                    if (adv1.IsStatusChannelOnly)
                    {
                        TangraContext.Current.CustomRenderer = new AavStatusChannelOnlyRenderer(adv1);
                        return(null);
                    }
                    rv = adv1;
                }
                else
                {
                    rv = AstroDigitalVideoStreamV2.OpenFile(fileName, out fileMetadataInfo, out geoLocation);
                }

                TangraContext.Current.RenderingEngine = fileMetadataInfo.Engine == "AAV" ? "AstroAnalogueVideo" : "AstroDigitalVideo";

                if (fileMetadataInfo.Engine == "AAV")
                {
                    UsageStats.Instance.ProcessedAavFiles++;
                }
                else
                {
                    UsageStats.Instance.ProcessedAdvFiles++;
                }
                UsageStats.Instance.Save();

                return(rv);
            }
            catch (ADVFormatException ex)
            {
                MessageBox.Show(ex.Message, "Error opening ADV/AAV file", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(null);
        }
Пример #8
0
 public LocationDescriptionViewModel(GeoLocationInfo locInfo)
 {
     Location = locInfo;
 }
        public void OpenOrganization(OpenOrganizationRequestVm model)
        {
            if (model == null)
            {
                throw new ArgumentNullException($"{typeof(OpenOrganizationRequestVm).Name} is null");
            }

            var checkOrganization = /*(from o in _aplicationDbContext.Organizations
                                     * where o.IdentificationNumber == model.IdentificationNumber ||
                                     * o.FullName == model.FullName
                                     * select o).ToList(); */
                                    _aplicationDbContext.Organizations
                                    .SingleOrDefault(p => p.IdentificationNumber == model.IdentificationNumber ||
                                                     p.FullName == model.FullName);

            if (checkOrganization != null)
            {
                throw new Exception("Такая организация уже существует в базе");
            }

            var checkOrganizationType = _aplicationDbContext.OrganizationTypes
                                        .SingleOrDefault(p => p.Name == model.OrganizationType);

            if (checkOrganizationType == null)
            {
                throw new Exception("Организационно-правовая форма организации не корректна");
            }


            var Position = _aplicationDbContext.EmployeePositions.SingleOrDefault(p => p.PositionName == "Director");

            if (Position == null)
            {
                throw new Exception("Данной должности не имеется в списке должностей");
            }

            var UserExists = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.DirectorEmail);

            if (UserExists != null)
            {
                throw new Exception("Пользователь с данным мэйлом уже существует");
            }

            Organization organization = new Organization()
            {
                FullName             = model.FullName,
                IdentificationNumber = model.IdentificationNumber,
                RegistrationDate     = DateTime.Now,
                OrganizationTypeId   = checkOrganizationType.Id,
                OrganizationEmail    = model.OrganizationEmail,
                PhoneNumber          = model.PhoneNumber,
                LinkToWebsite        = model.LinkToWebsite,
                Address = model.Address,
            };

            _aplicationDbContext.Organizations.Add(organization);
            _aplicationDbContext.SaveChanges();

            Employee employee = new Employee()
            {
                FirstName          = model.DirectorFirstName,
                LastName           = model.DirectorLastName,
                DoB                = model.DirectorDoB,
                Email              = model.DirectorEmail,
                EmployeePositionId = Position.Id,
                OrganizationId     = organization.Id
            };

            _aplicationDbContext.Employees.Add(employee);
            _aplicationDbContext.SaveChanges();

            ApplicationUser user = new ApplicationUser()
            {
                Email                = model.DirectorEmail,
                IsActive             = true,
                FailedSignInCount    = 0,
                CreatedDate          = DateTime.Now,
                AssosiatedEmployeeId = employee.Id
            };

            _identityDbContext.ApplicationUsers.Add(user);
            _identityDbContext.SaveChanges();

            ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory()
            {
                SetupDate         = DateTime.Now,
                InvalidatedDate   = DateTime.Now.AddMonths(3),
                Password          = model.Password,
                ApplicationUserId = user.Id
            };

            _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory);
            _identityDbContext.SaveChanges();

            var geoLocationInfo = GeoLocationInfo.GetGeolocationInfo();

            ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
            {
                SignInTime        = DateTime.Now,
                MachineIp         = geoLocationInfo.ip,
                IpToGeoCountry    = geoLocationInfo.country_name,
                IpToGeoCity       = geoLocationInfo.city,
                IpToGeoLatitude   = geoLocationInfo.latitude,
                IpToGeoLongitude  = geoLocationInfo.longitude,
                ApplicationUserId = user.Id
            };

            _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
            _identityDbContext.SaveChanges();
        }
Пример #10
0
 public LocationDescriptionViewModel(GeoLocationInfo locInfo)
 {
     Location = locInfo;
 }
Пример #11
0
 public LocationDescriptionViewModel(GeoCoordinate geoCoordinate)
 {
     Location = new GeoLocationInfo
     {
         Latitude = geoCoordinate.Latitude,
         Longitude = geoCoordinate.Longitude,
     };
 }
Пример #12
0
        public void OpenOrganization(OpenOrganizationViewModel viewModel)
        {
            DataSet applicationDataSet = new DataSet();
            DataSet identityDataSet    = new DataSet();

            string organizationsTable = "[dbo].[Organizations]";
            string employeeTable      = "[dbo].[Employees]";

            string userTable         = "[dbo].[ApplicationUsers]";
            string userSignInTable   = "[dbo].[ApplicationUserSignInHistories]";
            string userPasswordTable = "[dbo].[ApplicationUserPasswordHistories]";
            string associatedEmpId   = string.Empty;

            string          applicationConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Auction.ApplicationDb;Data Source=DM-ПК\SQLEXPRESS";
            string          identityConnectionString    = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Auction.IdentityDb;Data Source=DM-ПК\SQLEXPRESS";
            GeoLocationInfo geoLocationInfo             = GetGeolocationInfo();

            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    using (SqlConnection applicationConnection = new SqlConnection(applicationConnectionString))
                    {
                        applicationConnection.Open();
                        string selectOrganizationByIdentificatorsSql = $"select * from {organizationsTable} " +
                                                                       $"where [IdentificationNumber] = {viewModel.OrganizationIdentificationNumber}";

                        //формируем адаптер для выгрузки данных в датасет
                        using (SqlDataAdapter applicationAdapter = new SqlDataAdapter(selectOrganizationByIdentificatorsSql, applicationConnection))
                        {
                            //заполняем в датасет таблицу organizationsTable и формируем для него SqlCommandBuilder для последующего добавления данных
                            applicationAdapter.Fill(applicationDataSet, organizationsTable);
                            SqlCommandBuilder applicationCommandBuilder = new SqlCommandBuilder(applicationAdapter);

                            //проводим проверку, есть ли уже такая организация в БД
                            bool isOrganizationAlreadyExist = applicationDataSet
                                                              .Tables[organizationsTable].Rows.Count != 0;
                            if (isOrganizationAlreadyExist)
                            {
                                throw new ApplicationException($"Already has an organization with IdentificationNumber = {viewModel.OrganizationIdentificationNumber}");
                            }

                            //очищаем датасет для дальнейших манипуляций с БД
                            applicationDataSet.Clear();
                            Organization organization = new Organization()
                            {
                                Id                   = Guid.NewGuid().ToString(),
                                FullName             = viewModel.OrganizationFullName,
                                IdentificationNumber = viewModel.OrganizationIdentificationNumber,
                                OrganizationTypeId   = viewModel.OrganizationTypeId,
                                RegistrationDate     = DateTime.Now.ToString("yyyy-MM-dd")
                            };

                            //делаем новую команду для SqlCommandBuilder - выбрать все из таблицы organizationsTable
                            string selectOrganizationsSql = $"select * from {organizationsTable}";
                            applicationAdapter.SelectCommand = new SqlCommand(selectOrganizationsSql, applicationConnection);
                            applicationCommandBuilder        = new SqlCommandBuilder(applicationAdapter);

                            applicationAdapter.Fill(applicationDataSet, organizationsTable);                          //заполняем датасет новыми данными
                            var dataRow = applicationDataSet.Tables[organizationsTable].NewRowWithData(organization); //формируем новую строку для таблицы organizationsTable, запихиваем в нее данные объекта organization
                            applicationDataSet.Tables[organizationsTable].Rows.Add(dataRow);                          //добавляем строку в organizationsTable
                            applicationAdapter.Update(applicationDataSet, organizationsTable);                        //обновляем таблицу Organizations в БД

                            //добавляем новые данные в таблицу Employees в БД
                            applicationDataSet.Clear();
                            Employee employee = new Employee()
                            {
                                Id             = Guid.NewGuid().ToString(),
                                FirstName      = viewModel.CeoFirstName,
                                LastName       = viewModel.CeoLastName,
                                MiddleName     = viewModel.CeoMiddleName,
                                Email          = viewModel.Email,
                                DoB            = viewModel.DoB.ToString("yyyy-MM-dd"),
                                OrganizationId = Guid.NewGuid().ToString()
                            };
                            associatedEmpId = employee.Id;

                            string selectEmployeeSql = $"select * from {employeeTable}";
                            applicationAdapter.SelectCommand = new SqlCommand(selectEmployeeSql, applicationConnection);
                            applicationCommandBuilder        = new SqlCommandBuilder(applicationAdapter);

                            applicationAdapter.Fill(applicationDataSet, employeeTable);
                            dataRow = applicationDataSet.Tables[employeeTable].NewRowWithData(employee);
                            applicationDataSet.Tables[employeeTable].Rows.Add(dataRow);
                            applicationAdapter.Update(applicationDataSet, employeeTable);

                            //transactionScope.Complete();
                        }
                    }

                    using (SqlConnection identityConnection = new SqlConnection(identityConnectionString))
                    {
                        identityConnection.Open();
                        string selectUserByEmailSql = $"select * from {userTable} " +
                                                      $"where [Email] = '{viewModel.Email}'";

                        //формируем адаптер и вытаскиваем данные о юзерах с таким емейлом
                        using (SqlDataAdapter identityAdapter = new SqlDataAdapter(selectUserByEmailSql, identityConnection))
                        {
                            identityAdapter.Fill(identityDataSet, userTable);
                            SqlCommandBuilder identityCommandBuilder = new SqlCommandBuilder(identityAdapter);

                            //проверяем есть ли юзеры с таким мейлом
                            bool isUserAlreadyExist = identityDataSet
                                                      .Tables[userTable].Rows.Count != 0;
                            if (isUserAlreadyExist)
                            {
                                throw new ApplicationException($"Already has a user with Email = {viewModel.Email}");
                            }

                            //добавляем юзера в ApplicationUser в БД
                            identityDataSet.Clear();
                            ApplicationUser user = new ApplicationUser()
                            {
                                Id    = Guid.NewGuid().ToString(),
                                Email = viewModel.Email,
                                IsActivatedAccount   = true,
                                FailedSigninCount    = 0,
                                IsBlockedBySystem    = false,
                                AssociatedEmployeeId = associatedEmpId,
                                CreationDate         = DateTime.Now.ToString("yyyy-MM-dd")
                            };

                            string selectUserSql = $"select * from {userTable}";
                            identityAdapter.SelectCommand = new SqlCommand(selectUserSql, identityConnection);
                            identityCommandBuilder        = new SqlCommandBuilder(identityAdapter);

                            identityAdapter.Fill(identityDataSet, userTable);
                            var dataRow = identityDataSet.Tables[userTable].NewRowWithData(user);
                            identityDataSet.Tables[userTable].Rows.Add(dataRow);
                            identityAdapter.Update(identityDataSet, userTable);

                            //добавляем строку в ApplicationUserPasswordHistories в БД
                            identityDataSet.Clear();
                            ApplicationUserPasswordHistories userPassword = new ApplicationUserPasswordHistories()
                            {
                                Id = Guid.NewGuid().ToString(),
                                ApplicationUserId = user.Id,
                                SetupDate         = DateTime.Now.ToString("yyyy-MM-dd"),
                                PasswordHash      = viewModel.Password
                            };

                            string userPasswordSql = $"select * from {userPasswordTable}";
                            identityAdapter.SelectCommand = new SqlCommand(userPasswordSql, identityConnection);
                            identityCommandBuilder        = new SqlCommandBuilder(identityAdapter);

                            identityAdapter.Fill(identityDataSet, userPasswordTable);
                            dataRow = identityDataSet.Tables[userPasswordTable].NewRowWithData(userPassword);
                            identityDataSet.Tables[userPasswordTable].Rows.Add(dataRow);
                            identityAdapter.Update(identityDataSet, userPasswordTable);

                            //добавляем строку в ApplicationUserSignInHistories в БД
                            identityDataSet.Clear();
                            //GeoLocationInfo geoLocationInfo = GetGeolocationInfo();
                            ApplicationUserSignInHistories userSignIn = new ApplicationUserSignInHistories()
                            {
                                Id = Guid.NewGuid().ToString(),
                                ApplicationUserId  = user.Id,
                                SignInTime         = DateTime.Now.ToString("yyyy-MM-dd"),
                                MachineIp          = geoLocationInfo.ip,
                                IpToGeoCountryCode = geoLocationInfo.country_name,
                                IpToGeoCityName    = geoLocationInfo.city,
                                IpToGeoLatitude    = geoLocationInfo.latitude,
                                IpToGeoLongitude   = geoLocationInfo.longitude
                            };

                            string userSignInSql = $"select * from {userSignInTable}";
                            identityAdapter.SelectCommand = new SqlCommand(userSignInSql, identityConnection);
                            identityCommandBuilder        = new SqlCommandBuilder(identityAdapter);

                            identityAdapter.Fill(identityDataSet, userSignInTable);
                            dataRow = identityDataSet.Tables[userSignInTable].NewRowWithData(userSignIn);
                            identityDataSet.Tables[userSignInTable].Rows.Add(dataRow);
                            identityAdapter.Update(identityDataSet, userSignInTable);
                        }
                    }

                    transactionScope.Complete();
                }
                catch (Exception)
                {
                    throw new ApplicationException("No connection");
                }
            }
        }
Пример #13
0
        private AstroDigitalVideoStream(string fileName, ref AdvFileMetadataInfo fileMetadataInfo, ref GeoLocationInfo geoLocation)
        {
            CheckAdvFileFormat(fileName, ref fileMetadataInfo, ref geoLocation);

            m_FileName = fileName;
            var fileInfo = new AdvFileInfo();

            TangraCore.ADVOpenFile(fileName, ref fileInfo);

            m_FirstFrame  = 0;
            m_CountFrames = fileInfo.CountFrames;

            m_BitPix       = fileInfo.Bpp;
            m_Width        = fileInfo.Width;
            m_Height       = fileInfo.Height;
            m_Aav16NormVal = fileInfo.Aav16NormVal;

            m_FrameRate = fileInfo.FrameRate;


            // Get the last frame in the video and read the Almanac Offset and Almanac Status so they are applied
            // to the frames that didn't have Almanac Status = Updated
            if (m_CountFrames > 0)
            {
                GetPixelmap(m_FirstFrame + m_CountFrames - 1);

                m_AlamanacOffsetLastFrameIsGood = m_CurrentFrameInfo.AlmanacStatusIsGood;
                m_AlmanacOffsetLastFrame        = m_CurrentFrameInfo.GetSignedAlamancOffset();
            }
            else
            {
                m_AlamanacOffsetLastFrameIsGood = false;
                m_AlmanacOffsetLastFrame        = 0;
            }

            m_Engine            = fileMetadataInfo.Engine;
            m_CameraModel       = fileMetadataInfo.Camera;
            m_UsesNtpTimestamps = fileMetadataInfo.HasNTPTimeStamps;

            if (m_Engine == "AAV")
            {
                m_VideoStandard = GetFileTag("NATIVE-VIDEO-STANDARD");
                double.TryParse(GetFileTag("NATIVE-FRAME-RATE"), out m_NativeFrameRate);

                int.TryParse(GetFileTag("OSD-FIRST-LINE"), out m_OsdFirstLine);
                int.TryParse(GetFileTag("OSD-LAST-LINE"), out m_OsdLastLine);

                if (m_OsdLastLine > m_Height)
                {
                    m_OsdLastLine = m_Height;
                }
                if (m_OsdFirstLine < 0)
                {
                    m_OsdFirstLine = 0;
                }

                m_IntegratedAAVFrames = -1;

                if (double.TryParse(GetFileTag("EFFECTIVE-FRAME-RATE"), out m_EffectiveFrameRate) && m_NativeFrameRate != 0)
                {
                    m_IntegratedAAVFrames = (int)Math.Round(m_NativeFrameRate / m_EffectiveFrameRate);
                }

                int.TryParse(GetFileTag("FRAME-STACKING-RATE"), out m_StackingRate);
                if (m_StackingRate == 1)
                {
                    m_StackingRate = 0;                                  // Video stacked at x1 is a non-stacked video
                }
            }
            else
            {
                m_OsdFirstLine = 0;
                m_OsdLastLine  = 0;
            }

            m_OcrDataAvailable = null;
        }
        private AstroDigitalVideoStreamV2(string fileName, ref AdvFileMetadataInfo fileMetadataInfo, ref GeoLocationInfo geoLocation)
        {
            //CheckAdvFileFormat(fileName, ref fileMetadataInfo, ref geoLocation);

            m_FileName = fileName;

            m_AdvFile = new AdvFile2(fileName);

            m_FirstFrame  = 0;
            m_CountFrames = m_AdvFile.MainSteamInfo.FrameCount;

            m_BitPix        = m_AdvFile.DataBpp;
            m_Width         = m_AdvFile.Width;
            m_Height        = m_AdvFile.Height;
            m_MaxPixelValue = (uint)m_AdvFile.MaxPixelValue;

            m_FrameRate = 0;

            m_Engine = "ADV2";

            fileMetadataInfo.Recorder = GetFileTag("RECORDER-SOFTWARE");
            CameraModel             = fileMetadataInfo.Camera = GetFileTag("CAMERA-MODEL");
            fileMetadataInfo.Engine = GetFileTag("FSTF-TYPE");

            fileMetadataInfo.AdvrVersion = GetFileTag("RECORDER-SOFTWARE-VERSION");
            fileMetadataInfo.SensorInfo  = GetFileTag("CAMERA-SENSOR-INFO");

            fileMetadataInfo.ObjectName = GetFileTag("OBJNAME");

            int aavVersion;

            if (int.TryParse(GetFileTag("AAV-VERSION"), out aavVersion))
            {
                m_AAVVersion    = aavVersion;
                m_VideoStandard = GetFileTag("NATIVE-VIDEO-STANDARD");
                double.TryParse(GetFileTag("NATIVE-FRAME-RATE"), NumberStyles.Float, CultureInfo.InvariantCulture, out m_NativeFrameRate);

                int.TryParse(GetFileTag("OSD-FIRST-LINE"), out m_OsdFirstLine);
                int.TryParse(GetFileTag("OSD-LAST-LINE"), out m_OsdLastLine);

                if (m_OsdLastLine > m_Height)
                {
                    m_OsdLastLine = m_Height;
                }
                if (m_OsdFirstLine < 0)
                {
                    m_OsdFirstLine = 0;
                }

                m_IntegratedAAVFrames = -1;

                if (double.TryParse(GetFileTag("EFFECTIVE-FRAME-RATE"), NumberStyles.Float, CultureInfo.InvariantCulture, out m_EffectiveFrameRate) && m_NativeFrameRate != 0)
                {
                    m_IntegratedAAVFrames = (int)Math.Round(m_NativeFrameRate / m_EffectiveFrameRate);
                    m_FrameRate           = m_EffectiveFrameRate; // This is important for OCR-ing as the frame rate is used to derive the frame exposure
                }

                int.TryParse(GetFileTag("FRAME-STACKING-RATE"), out m_StackingRate);
                if (m_StackingRate == 1)
                {
                    m_StackingRate = 0;                      // Video stacked at x1 is a non-stacked video
                }
                m_Engine = string.Format("AAV{0}", aavVersion);
            }

            this.geoLocation = new GeoLocationInfo()
            {
                //TODO
            };

            geoLocation = this.geoLocation;
        }
Пример #15
0
        public async Task <IHttpActionResult> LocationByIp(string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                return(this.BadRequest("IP is empty"));
            }
            using (var connection = new OracleConnection(ConfigurationManager.ConnectionStrings["GEOIP"].ToString()))
            {
                IPAddress addr;
                if (!IPAddress.TryParse(ip, out addr))
                {
                    return(this.BadRequest("Invalid IP address"));
                }
                LogManager.GetLogger("Geo").Trace("Get ip for " + ip);
                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "GEOIP.GEOIP_PKG.GET_LOCATION";
                    cmd.BindByName  = true;
                    var returnValParam = new OracleParameter(
                        "Return_Value",
                        OracleDbType.Int16,
                        ParameterDirection.ReturnValue);
                    var contryParam = new OracleParameter("O_COUNTRY", OracleDbType.Varchar2, ParameterDirection.Output)
                    {
                        Size = 255
                    };
                    var stateParam = new OracleParameter(
                        "O_STATE",
                        OracleDbType.Varchar2,
                        ParameterDirection.Output)
                    {
                        Size = 255
                    };
                    var cityParam = new OracleParameter(
                        "O_CITY",
                        OracleDbType.Varchar2,
                        ParameterDirection.Output)
                    {
                        Size = 255
                    };
                    cmd.Parameters.Add(returnValParam);
                    cmd.Parameters.Add("IP_ADDR", OracleDbType.Varchar2, 255, ip, ParameterDirection.Input);
                    cmd.Parameters.Add(contryParam);
                    cmd.Parameters.Add(stateParam);
                    cmd.Parameters.Add(cityParam);
                    connection.Open();
                    try
                    {
                        await cmd.ExecuteNonQueryAsync();

                        var resultVal = int.Parse(returnValParam.Value.ToString());
                        if (resultVal == 1)
                        {
                            var locationinfo = new GeoLocationInfo
                            {
                                Ip      = ip,
                                Country = contryParam.Value.ToString(),
                                City    = cityParam.Value.ToString(),
                                State   = stateParam.Value.ToString()
                            };

                            return(this.Ok(locationinfo));
                        }
                        else
                        {
                            return(this.NotFound());
                        }
                    }
                    catch (Exception ex)
                    {
                        var logger = LogManager.GetLogger("GeoIP");
                        logger.Error(ex);
                        return(this.InternalServerError(ex));
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }
        }
Пример #16
0
        public void OpenOrganization(OpenOrganizationViewModel viewModel)
        {
            DataSet applicationDataSet = new DataSet();
            DataSet identityDataSet    = new DataSet();

            string organizationsTable = "[dbo].[Organizations]";
            string employeeTable      = "[dbo].[Employees]";

            Employee employee = new Employee();

            using (TransactionScope transactionScope = new TransactionScope())
            {
                try
                {
                    using (SqlConnection applicationConnection = new SqlConnection(
                               ApplicationSettings.APPLICATION_CONNECTION_STRING))
                    {
                        applicationConnection.Open();

                        string selectOrganizationByIdentificatorsSql = $"select * from {organizationsTable} " +
                                                                       $"where [IdentificationNumber] = {viewModel.OrganizationIdentificationNumber}";

                        string selectOrganizationsSql = $"select * from {organizationsTable}";

                        using (SqlDataAdapter applicationAdapter = new SqlDataAdapter(selectOrganizationByIdentificatorsSql,
                                                                                      applicationConnection))
                        {
                            applicationAdapter.Fill(applicationDataSet, organizationsTable);
                            SqlCommandBuilder applicationCommandBuilder = new SqlCommandBuilder(applicationAdapter);
                            bool isOrganizationAlreadyExist             = applicationDataSet.Tables[organizationsTable].Rows.Count != 0;

                            if (isOrganizationAlreadyExist)
                            {
                                throw new ApplicationException($"Already has an organization with IdentificationNumber = {viewModel.OrganizationIdentificationNumber}");
                            }

                            applicationDataSet.Clear();

                            Organization organization = new Organization()
                            {
                                Id                   = Guid.NewGuid().ToString(),
                                FullName             = viewModel.OrganizationFullName,
                                IdentificationNumber = viewModel.OrganizationIdentificationNumber,
                                OrganizationTypeId   = viewModel.OrganizationTypeId,
                                RegistrationDate     = DateTime.Now.ToString("yyyy-MM-dd")
                            };

                            applicationAdapter.SelectCommand = new SqlCommand(selectOrganizationsSql, applicationConnection);
                            applicationCommandBuilder        = new SqlCommandBuilder(applicationAdapter);

                            applicationAdapter.Fill(applicationDataSet, organizationsTable);
                            var dataRow = applicationDataSet.Tables[organizationsTable].NewRowWithData(organization);
                            applicationDataSet.Tables[organizationsTable].Rows.Add(dataRow);
                            applicationAdapter.Update(applicationDataSet, organizationsTable);

                            employee.Id             = Guid.NewGuid().ToString();
                            employee.FirstName      = viewModel.CeoFirstName;
                            employee.LastName       = viewModel.CeoLastName;
                            employee.MiddleName     = viewModel.CeoMiddleName;
                            employee.Email          = viewModel.Email;
                            employee.DoB            = viewModel.DoB;
                            employee.OrganizationId = Guid.NewGuid().ToString();


                            string selectEmployeeSql = $"select * from {employeeTable}";

                            applicationAdapter.SelectCommand = new SqlCommand(selectEmployeeSql, applicationConnection);
                            applicationCommandBuilder        = new SqlCommandBuilder(applicationAdapter);
                            applicationAdapter.Fill(applicationDataSet, employeeTable);

                            dataRow = applicationDataSet.Tables[employeeTable].NewRowWithData(employee);
                            applicationDataSet.Tables[employeeTable].Rows.Add(dataRow);
                            applicationAdapter.Update(applicationDataSet, employeeTable);
                        }
                    }
                    using (SqlConnection identityConnection = new SqlConnection(
                               ApplicationSettings.IDENTITY_CONNECTION_STRING))
                    {
                        identityConnection.Open();

                        string usersTable        = "[dbo].[ApplicationUsers]";
                        string selectUserByEmail = $"select * from {usersTable} where [Email]='{viewModel.Email}'";

                        using (SqlDataAdapter identityUserAdapter = new SqlDataAdapter(selectUserByEmail, identityConnection))
                        {
                            identityUserAdapter.Fill(identityDataSet, usersTable);
                            SqlCommandBuilder identityCommandBuilder = new SqlCommandBuilder(identityUserAdapter);

                            bool isUserAlreadyExist = identityDataSet.Tables[usersTable].Rows.Count != 0;

                            if (isUserAlreadyExist)
                            {
                                throw new ApplicationException($"Already has user with email = {viewModel.Email}");
                            }

                            identityDataSet.Clear();

                            ApplicationUser user = new ApplicationUser()
                            {
                                Id    = Guid.NewGuid().ToString(),
                                Email = viewModel.Email,
                                IsActivatedAccount   = true,
                                FailedSigninCount    = 0,
                                IsBlockedBySystem    = false,
                                AssociatedEmployeeId = employee.Id,
                                CreationDate         = DateTime.Now.ToString("yyyy-MM-dd")
                            };
                            string selectUsersSql = $"select * from {usersTable}";
                            identityUserAdapter.SelectCommand = new SqlCommand(selectUsersSql, identityConnection);
                            identityCommandBuilder            = new SqlCommandBuilder(identityUserAdapter);
                            identityUserAdapter.Fill(identityDataSet, usersTable);
                            var dataRow = identityDataSet.Tables[usersTable].NewRowWithData(user);
                            identityDataSet.Tables[usersTable].Rows.Add(dataRow);
                            identityUserAdapter.Update(identityDataSet, usersTable);

                            identityDataSet.Clear();

                            ApplicationUserPasswordHistories userPassword = new ApplicationUserPasswordHistories()
                            {
                                Id = Guid.NewGuid().ToString(),
                                ApplicationUserId = user.Id,
                                SetupDate         = DateTime.Now.ToString("yyyy-MM-dd"),
                                InvalidatedDate   = DateTime.Now.AddMonths(3).ToString("yyyy-MM-dd"),
                                PasswordHash      = viewModel.Password
                            };

                            string usersPasswordsTable   = "[dbo].[ApplicationUserPasswordHistories]";
                            string SelectUserPasswordSql = $"select * from {usersPasswordsTable}";
                            identityUserAdapter.SelectCommand = new SqlCommand(SelectUserPasswordSql, identityConnection);
                            identityCommandBuilder            = new SqlCommandBuilder(identityUserAdapter);

                            identityUserAdapter.Fill(identityDataSet, usersPasswordsTable);
                            dataRow = identityDataSet.Tables[usersPasswordsTable].NewRowWithData(userPassword);
                            identityDataSet.Tables[usersPasswordsTable].Rows.Add(dataRow);
                            identityUserAdapter.Update(identityDataSet, usersPasswordsTable);

                            identityDataSet.Clear();

                            GeoLocationInfo geoLocationInfo = GetGeolocationInfo();

                            ApplicationUserSignInHistories userSignIn = new ApplicationUserSignInHistories()
                            {
                                Id = Guid.NewGuid().ToString(),
                                ApplicationUserId  = user.Id,
                                SignInTime         = DateTime.Now.ToString("yyyy-MM-dd"),
                                MachineIp          = geoLocationInfo.ip,
                                IpToGeoCountryCode = geoLocationInfo.country_name,
                                IpToGeoCityName    = geoLocationInfo.city,
                                IpToGeoLatitude    = geoLocationInfo.latitude,
                                IpToGeoLongitude   = geoLocationInfo.longitude
                            };

                            string userSignInTable = "[dbo].[ApplicationUserSignInHistories]";
                            string userSignInSql   = $"select * from {userSignInTable}";
                            identityUserAdapter.SelectCommand = new SqlCommand(userSignInSql, identityConnection);
                            identityCommandBuilder            = new SqlCommandBuilder(identityUserAdapter);

                            identityUserAdapter.Fill(identityDataSet, userSignInTable);
                            dataRow = identityDataSet.Tables[userSignInTable].NewRowWithData(userSignIn);
                            identityDataSet.Tables[userSignInTable].Rows.Add(dataRow);
                            identityUserAdapter.Update(identityDataSet, userSignInTable);
                        }
                    }

                    transactionScope.Complete();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public void ValidateUserInLogIn(UserLogOnVm model)
        {
            var userExists = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.Email);

            if (userExists == null)
            {
                throw new Exception("Пользователь с таким мэйлом отсутствует в системе");
            }

            var passwordCheck = _identityDbContext.ApplicationUserPasswordHistories
                                .Where(p => p.Password == model.Password && p.ApplicationUserId == userExists.Id)
                                .OrderByDescending(p => p.SetupDate).Take(1);

            if (passwordCheck == null)
            {
                userExists.FailedSignInCount++;
                _identityDbContext.SaveChanges();
                throw new Exception("У данного пользователя другой пароль");
            }

            var FailedSignInCount = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.Email).FailedSignInCount;

            if (FailedSignInCount > 5)
            {
                userExists.IsActive = false;
                throw new Exception("Вы ввели неправильный пароль более 5 раз");
            }
            var invalidatedDateCheck = _identityDbContext.ApplicationUserPasswordHistories
                                       .Where(p => p.ApplicationUser.Email == model.Email && p.Password == model.Password)
                                       .OrderByDescending(p => p.SetupDate).Take(1);

            if (invalidatedDateCheck.FirstOrDefault().InvalidatedDate <= DateTime.Now)
            {
                userExists.IsActive = false;
                _identityDbContext.SaveChanges();
                throw new Exception("Истекла валидная дата для данного пароля");
            }


            var validUser = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Id == userExists.Id && (p.IsActive == true));

            if (validUser == null)
            {
                throw new Exception("Данный пользователь заблокирован");
            }

            validUser.FailedSignInCount = 0;
            _identityDbContext.SaveChanges();

            GeoLocationInfo geoInfo = GeoLocationInfo.GetGeolocationInfo();

            ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
            {
                ApplicationUserId = validUser.Id,
                IpToGeoCity       = geoInfo.city,
                IpToGeoLatitude   = geoInfo.latitude,
                IpToGeoCountry    = geoInfo.country_name,
                IpToGeoLongitude  = geoInfo.longitude,
                MachineIp         = geoInfo.ip,
                SignInTime        = DateTime.Now
            };

            _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
            _identityDbContext.SaveChanges();
        }
        public void OpenOrganization(RegisterOrganizationViewModel model)
        {
            var geoLocationInfo = GeoLocationInfo.GetGeolocationInfo();

            if (model == null)
            {
                throw new Exception($"{typeof(RegisterOrganizationViewModel).Name} is null");
            }

            var checkOrganization = _applicationDbContext.Organizations
                                    .SingleOrDefault(p => p.IdentificationNumber == model.IdentificationNumber || p.FullName == model.FullName);

            if (checkOrganization != null)
            {
                throw new Exception("Такая организация уже сущуствует в базе");
            }

            var checkOrganizationType = _applicationDbContext.OrganizationTypes
                                        .SingleOrDefault(p => p.Name == model.OrganizationType);

            if (checkOrganizationType == null)
            {
                OrganizationType orgType = new OrganizationType()
                {
                    Id   = Guid.NewGuid(),
                    Name = model.OrganizationType
                };
                _applicationDbContext.OrganizationTypes.Add(orgType);
                _applicationDbContext.SaveChanges();
                checkOrganizationType = orgType;
            }


            Organization organization = new Organization()
            {
                Id                   = Guid.NewGuid(),
                FullName             = model.FullName,
                IdentificationNumber = model.IdentificationNumber,
                RegistrationDate     = DateTime.Now,
                OrganizationTypeId   = checkOrganizationType.Id
            };

            _applicationDbContext.Organizations.Add(organization);
            _applicationDbContext.SaveChanges();

            var checkEmployeeEmail = _applicationDbContext.Employees.Any(p => p.Email == model.CeoEmail);

            if (!checkEmployeeEmail)
            {
                var ceoPosition = _applicationDbContext.EmployeePositions.SingleOrDefault(p => p.Name == "CEO");
                if (ceoPosition == null)
                {
                    EmployeePosition pos = new EmployeePosition()
                    {
                        Id   = Guid.NewGuid(),
                        Name = "CEO"
                    };
                    _applicationDbContext.EmployeePositions.Add(pos);
                    _applicationDbContext.SaveChanges();
                    ceoPosition = pos;
                }

                Employee employee = new Employee()
                {
                    Id                 = Guid.NewGuid(),
                    FirstName          = model.CeoFirstName,
                    LastName           = model.CeoLastName,
                    DoB                = model.CeoDoB,
                    Email              = model.CeoEmail,
                    EmployeePositionId = new Guid(ceoPosition.Id.ToString()),
                    OrganizationId     = organization.Id
                };
                _applicationDbContext.Employees.Add(employee);
                _applicationDbContext.SaveChanges();

                ApplicationUser user = new ApplicationUser()
                {
                    Id                   = Guid.NewGuid(),
                    Email                = model.CeoEmail,
                    IsActive             = true,
                    FailedSignInCount    = 0,
                    CreatedDate          = DateTime.Now,
                    AssosiatedEmployeeId = employee.Id
                };
                _identityDbContext.ApplicationUsers.Add(user);
                _identityDbContext.SaveChanges();

                ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory()
                {
                    Id                = Guid.NewGuid(),
                    SetupDate         = DateTime.Now,
                    Password          = model.Password,
                    ApplicationUserId = user.Id
                };
                _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory);
                _identityDbContext.SaveChanges();

                ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory()
                {
                    Id                = Guid.NewGuid(),
                    SignInTime        = DateTime.Now,
                    MachineIp         = geoLocationInfo.ip,
                    IpToGeoCountry    = geoLocationInfo.country_name,
                    IpToGeoCity       = geoLocationInfo.city,
                    IpToGeoLatitude   = geoLocationInfo.latitude,
                    IpToGeoLongitude  = geoLocationInfo.longitude,
                    ApplicationUserId = user.Id
                };
                _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory);
                _identityDbContext.SaveChanges();
            }
        }
Пример #19
0
 public void InitAdvFile(AdvFileMetadataInfo fileMetadataInfo, GeoLocationInfo geoLocation, int firstFrameNo)
 {
     m_AdvFileMetadataInfo = fileMetadataInfo;
     m_GeoLocation         = geoLocation;
     m_FirstFrameNo        = firstFrameNo;
 }