private void DoWork(object sender, DoWorkEventArgs e)
        {
            _sent = "";
            try
            {
                var agencyName = "NoAgencyName";
                var biosSn     = "00000";
                try
                {
                    agencyName = Singleton.Agency.AgencyName;
                    biosSn     = Singleton.ProductActivation.BiosSn;
                    agencyName = agencyName.Substring(0, agencyName.IndexOf(' '));
                }
                catch
                {
                }

                var destination = PathUtil.GetServerLogPath();

                var destFiName = agencyName + "_" + biosSn + "_" + DateTime.Now.Date.ToString("dd-MM-yy") + "_Log.txt";

                var destpa = Path.Combine(destination, destFiName);

                using (var client = new WebClient())
                {
                    client.Credentials = DbCommandUtil.GetNetworkCredential();

                    client.UploadFile(destpa, _sourceLogFile);
                }
            }
            catch (Exception exception)
            {
                _sent = exception.Message;
            }
        }
Example #2
0
        private void ConfigureContainer()
        {
            switch (Singleton.Edition)
            {
            case PinnaFaceEdition.CompactEdition:
                Singleton.SqlceFileName = PathUtil.GetDatabasePath();
                Singleton.PhotoStorage  = PhotoStorage.FileSystem;
                break;

            case PinnaFaceEdition.ServerEdition:
                Singleton.SqlceFileName = "PinnaFaceDbProd";    //"PinnaFaceDb25";//munahan_pfdbtest1";//"PinnaFaceDb25";//PinnaFaceDbProd
                Singleton.PhotoStorage  = PhotoStorage.Database;
                break;
            }

            Singleton.UseServerDateTime = false;    //TO Handle Datetime.Now from serverornot
            Singleton.BuildType         = BuildType.Production;
            Singleton.SeedDefaults      = true;
            Singleton.SystemVersionDate = DbCommandUtil.GetCurrentDatabaseVersion(); //Whenever System is updated change the number to higher value

            Container.RegisterType <IDbContext, PinnaFaceDbContext>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IUnitOfWork, UnitOfWork>();

            Container.RegisterType <MainViewModel>();
        }
Example #3
0
 private void ExecuteDeleteVisaViewCommand()
 {
     try
     {
         if (MessageBox.Show("Are you Sure You want to Delete this Visa?", "Delete Visa",
                             MessageBoxButton.YesNoCancel, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes)
         {
             return;
         }
         //Check Constraints Before Deleting
         var ids = DbCommandUtil.QueryCommand("Select VisaId as Id from Employees " +
                                              " where Id='" + SelectedVisa.Id + "' and enabled='1'").ToList();
         if (ids.Count == 0)
         {
             SelectedVisa.Enabled = false;
             _visaService.InsertOrUpdate(SelectedVisa);
         }
         else
         {
             MessageBox.Show("Problem deleting Visa, There may exist Employees Assigned to this Visa," +
                             " you have to first update or delete those Employees related with " +
                             SelectedVisa.VisaNumber,
                             "Can't Delete Visa", MessageBoxButton.OK, MessageBoxImage.Error);
         }
         //Visas.Remove(SelectedVisa);
     }
     catch
     {
         MessageBox.Show(
             "Problem deleting Visa, There may exist Employees Assigned to this Visa, you have to first update or delete those Employees related with " +
             SelectedVisa.VisaNumber, "Can't Delete Visa", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
        private void ExecuteDeleteForeignAgentViewCommand()
        {
            try
            {
                if (SelectedAgent.Id == 1)
                {
                    return;//can delete the last agent
                }
                if (MessageBox.Show("Are you Sure You want to Delete this Foreign Agent?", "Delete Foreign Agent",
                                    MessageBoxButton.YesNoCancel, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes)
                {
                    return;
                }

                var ids = DbCommandUtil.QueryCommand("Select ForeignAgentId as Id from Visas " +
                                                     " where Id='" + SelectedAgent.Id + "' and enabled='1'").ToList();
                if (ids.Count == 0)
                {
                    SelectedAgent.Enabled = false;
                    _foreignAgentService.InsertOrUpdate(SelectedAgent);
                }
                else
                {
                    MessageBox.Show("There may exist Visas Assigned to this agent, you have to update or delete " +
                                    "those Visas related with " + SelectedAgent.AgentName,
                                    "Can't Delete Agent", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch
            {
                MessageBox.Show("There may exist Visas Assigned to this agent, you have to update or delete those Visas related with " + SelectedAgent.AgentName, "Can't Delete Agent", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            GetLiveForeignAgents();
        }
Example #5
0
        public List <string> GetServerFileNames()
        {
            var listRequest = WebRequest.Create(PathUtil.GetDestinationPhotoPath());

            listRequest.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
            listRequest.Credentials = DbCommandUtil.GetNetworkCredential();
            var lines  = new List <string>();
            var lines2 = new List <string>();

            using (var listResponse = listRequest.GetResponse())
                using (var listStream = listResponse.GetResponseStream())
                    using (var listReader = new StreamReader(listStream))
                    {
                        while (!listReader.EndOfStream)
                        {
                            var line = listReader.ReadLine();
                            lines.Add(line);
                        }
                    }

            foreach (var line in lines)
            {
                var tokens =
                    line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);

                var name = tokens[3];
                lines2.Add(name);
            }


            return(lines2);
        }
Example #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            Singleton.Edition           = PinnaFaceEdition.WebEdition;
            Singleton.BuildType         = BuildType.Production;
            Singleton.SeedDefaults      = true;
            Singleton.UseServerDateTime = true;//TO Handle Datetime.Now from serverornot

            /**************/
            Singleton.SystemVersionDate = DbCommandUtil.GetCurrentDatabaseVersion();

            if (!ValidateProduct())
            {
                LogUtil.LogError(ErrorSeverity.Critical, "ValidateProduct",
                                 "Higher Database Version", "", "");
                return;
            }
            /*****************/

            IEnumerable <ListDTO> aa = new ListService().GetAll();

            new InitializeObjects().InitializeWebSecurity();

            Container = new UnityContainer();
            Container.RegisterType <IDbContext, PinnaFaceServerDBContext>(new ContainerControlledLifetimeManager());
            Container.RegisterType <IUnitOfWork, UnitOfWork>();
        }
Example #7
0
        public DbCommandUtilTest()
        {
            var comm = new DbCommandUtil("IF NOT EXISTS(SELECT * FROM SYS.OBJECTS WHERE Name = 'Test') CREATE TABLE TEST (ID INT, VALUE NUMERIC(4,2))");

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            comm.ExecuteNonQuery();
            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
        }
        public ActivationModel ValidateProduct()
        {
            //var dt = DbCommandUtil.GetCurrentSqlDate(true);
            //var loc = dt.ToLocalTime();

            return(Singleton.Edition == PinnaFaceEdition.CompactEdition
                ? DbCommandUtil.ValidateProductSqlCe()
                : DbCommandUtil.ValidateProductSql());
        }
Example #9
0
        public void ParameterPrecisionTest()
        {
            Insert();
            var comm = new DbCommandUtil("SELECT ID FROM TEST WHERE Value = @Value");

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            comm.AddParameter("@Value", DbType.Double, 4, 2, 35.4);
            var idValue = comm.ExecuteScalar <int?>();

            Assert.Equal(3, idValue);
        }
Example #10
0
        public void NullParameterTest()
        {
            Insert();
            var comm = new DbCommandUtil("SELECT * FROM TEST WHERE ID = @ID");

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            comm.AddParameter("@ID", DbType.Int32, null);
            Assert.Equal(0, comm.GetDataTable().Rows.Count);
            comm.SetParameterValue("@ID", 0);
            Assert.Equal(0, comm.GetDataTable().Rows.Count);
        }
Example #11
0
        public void BasicDbCommandUtilTest()
        {
            // Select
            var comm = new DbCommandUtil("SELECT * FROM TEST");

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            var dataTable = comm.GetDataTable();

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            Assert.Equal(2, dataTable.Columns.Count);
            Assert.Equal("ID", dataTable.Columns[0].ColumnName);
        }
Example #12
0
        private static void Insert()
        {
            // INSERT 1
            var insert1Comm = new DbCommandUtil("INSERT INTO TEST(ID,VALUE) VALUES(2, 1.2)");

            Assert.Equal(ConnectionState.Closed, insert1Comm.DaScopeContext.Connection.State);
            insert1Comm.ExecuteNonQuery();
            Assert.Equal(ConnectionState.Closed, insert1Comm.DaScopeContext.Connection.State);
            // INSERT 2
            var insert2Comm = new DbCommandUtil("INSERT INTO TEST(ID,VALUE) VALUES(3, 35.4)");

            Assert.Equal(ConnectionState.Closed, insert2Comm.DaScopeContext.Connection.State);
            insert2Comm.ExecuteNonQuery();
            Assert.Equal(ConnectionState.Closed, insert2Comm.DaScopeContext.Connection.State);
        }
Example #13
0
        public bool ValidateProduct()
        {
            var activationModel = DbCommandUtil.ValidateProductSql();

            if (activationModel != null &&
                activationModel.DatabaseVersionDate != 0 &&
                activationModel.MaximumSystemVersion != 0)
            {
                if (Singleton.SystemVersionDate < activationModel.DatabaseVersionDate)
                {
                    return(false);
                }
            }
            return(true);
        }
Example #14
0
        public ActivationViewModel()
        {
            CleanUp();
            string connectionStringName = DbCommandUtil.GetActivationConnectionString();

            _dbContext  = new EntitiesModel(connectionStringName);
            _unitOfWork = new UnitOfWork(DbContextUtil.GetDbContextInstance());

            ProductActivation = _unitOfWork.Repository <ProductActivationDTO>()
                                .Query().Get()
                                .FirstOrDefault() ?? new ProductActivationDTO();

            ProgressBarVisibility = "Collapsed";
            CommandsEnability     = true;
            BiosNo = "Bios No:" + new ProductActivationDTO().BiosSn;
        }
        private ActivationKey CheckProductRenewalOnActivationServer(string productKey)
        {
            try
            {
                string connectionStringName = DbCommandUtil.GetActivationConnectionString();

                var           dbContext = new EntitiesModel(connectionStringName);
                ActivationKey key       = dbContext.ActivationKeys
                                          .FirstOrDefault(a => a.ProductKey == productKey &&
                                                          a.KeyStatus == 0 && a.ProductType == 0);
                return(key);
            }
            catch
            {
                return(null);
            }
        }
Example #16
0
        private void BuildIndexes()
        {
            const string sql = @"SELECT DISTINCT
	   index_name		= [index].name,
	   column_name		= [columns].name,
	   index_column_id  = [index_columns].index_column_id
from sys.indexes [index]
          LEFT JOIN sys.objects [objects] ON ( [objects].object_id = [index].object_id )
          LEFT JOIN sys.index_columns [index_columns] ON ( [index_columns].index_id = [index].index_id )
		                                                 AND ( [index_columns].object_id  = [index].object_id )
          LEFT JOIN sys.columns [columns] ON ( [index_columns].OBJECT_id = [columns].object_id )
                                             AND ( [index_columns].Column_id = [columns].column_id )
WHERE ( [objects].schema_id = SCHEMA_ID(@schema_name) )
	  AND ( [objects].name = @object_name )
	  AND ( [index].type = 2 )
ORDER BY [index].name, [index_columns].index_column_id";

            using (var comm = new DbCommandUtil(sql))
            {
                comm.AddParameter("@schema_name", DbType.AnsiString, Schema);
                comm.AddParameter("@object_name", DbType.AnsiString, Name);
                var reader            = comm.ExecuteReader(CommandBehavior.CloseConnection);
                var previousIndexName = "";
                var indexColumns      = new List <Column>();
                while (reader.Read())
                {
                    var indexName = reader.GetString(0);
                    if (previousIndexName == "")
                    {
                        previousIndexName = indexName;
                    }

                    if (previousIndexName != indexName)
                    {
                        _Indexes.Add(new Index(previousIndexName, indexColumns));
                        indexColumns = new List <Column>();
                    }
                    indexColumns.Add(Columns[reader.GetString(1)]);
                    previousIndexName = indexName;
                }
                _Indexes.Add(new Index(previousIndexName, indexColumns));

                reader.Close();
            }
        }
Example #17
0
        public void DataTableTest()
        {
            // DataTable
            Insert();
            var comm = new DbCommandUtil("SELECT * FROM TEST");

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            var dataTable = comm.GetDataTable();

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            Assert.Equal(2, dataTable.Columns.Count);
            Assert.Equal(2, dataTable.Rows.Count);
            Assert.Equal(2, dataTable.Rows[0][0]);
            Assert.Equal(1.2, dataTable.Rows[0][1]);
            Assert.Equal(3, dataTable.Rows[1][0]);
            Assert.Equal(35.4, dataTable.Rows[1][1]);
            Assert.Equal("ID", dataTable.Columns[0].ColumnName);
        }
Example #18
0
        public static Server GetServer()
        {
            try
            {
                var serveruspas = DbCommandUtil.GetBackUpUserNameAndPassword().Split('_');

                var serverConnection = new ServerConnection(serveruspas[0])
                {
                    LoginSecure = false,
                    Login       = serveruspas[1],
                    Password    = serveruspas[2]
                };
                return(new Server(serverConnection));
            }
            catch
            {
                return(null);
            }
        }
Example #19
0
        public void DbCommandUtilExecuteScalarTest()
        {
            // Null
            var comm = new DbCommandUtil("SELECT ID FROM TEST");

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            var testNullValue = comm.ExecuteScalar <int?>();

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            Assert.Null(testNullValue);
            // Insert
            Insert();
            // NotNull
            var testNotNullValue = comm.ExecuteScalar <int?>();

            Assert.Equal(ConnectionState.Closed, comm.DaScopeContext.Connection.State);
            Assert.NotNull(testNotNullValue);
            Assert.Equal(2, testNotNullValue);
        }
Example #20
0
        public static Table[] GetAll()
        {
            var          tables = new List <Table>();
            const string sql    =
                @"SELECT Schema_Name(Schema_Id) AS Schema_Name, Name, Type
  FROM sys.objects
 WHERE type = 'U'";
            var comm = new DbCommandUtil(sql);

            using (var reader = comm.ExecuteReader())
            {
                while (reader.Read())
                {
                    string schema = reader.GetString(0);
                    string name   = reader.GetString(1);
                    tables.Add(new Table(schema, name));
                }
            }
            return(tables.ToArray());
        }
Example #21
0
 private void ExecuteDeleteVisaViewCommand()
 {
     try
     {
         if (MessageBox.Show("Are you sure you want to delete this Visa?", "Delete Visa",
                             MessageBoxButton.YesNoCancel, MessageBoxImage.Warning, MessageBoxResult.No) != MessageBoxResult.Yes)
         {
             return;
         }
         //Check Constraints Before Deleting
         List <CommandModel> ids = DbCommandUtil.QueryCommand("Select VisaId as Id from Employees " +
                                                              " where Id='" + SelectedVisa.Id +
                                                              "' and enabled='1'").ToList();
         if (ids.Count == 0)
         {
             SelectedVisa.Enabled = false;
             /**********/
             SelectedVisa.Condition.Enabled       = false;
             SelectedVisa.Sponsor.Enabled         = false;
             SelectedVisa.Sponsor.Address.Enabled = false;
             /**********/
             _visaService.InsertOrUpdate(SelectedVisa);
             Load();
         }
         else
         {
             MessageBox.Show("Problem deleting Visa, There may exist Employees Assigned to this Visa," +
                             " you have to first update or delete those Employees related with visa: " +
                             SelectedVisa.VisaNumber,
                             "Can't Delete Visa", MessageBoxButton.OK, MessageBoxImage.Error);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Problem deleting Visa, There may exist Employees Assigned to this Visa," +
                         " you have to first update or delete those Employees related with " +
                         SelectedVisa.VisaNumber + Environment.NewLine + ex.Message + Environment.NewLine +
                         ex.InnerException,
                         "Can't Delete Visa", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Example #22
0
        public bool ValidateProduct()
        {
            //var dt = DbCommandUtil.GetCurrentSqlDate(true);
            //var loc = dt.ToLocalTime();

            var activationModel = Singleton.Edition == PinnaFaceEdition.CompactEdition
                ? DbCommandUtil.ValidateProductSqlCe()
                : DbCommandUtil.ValidateProductSql();

            if (activationModel != null &&
                activationModel.DatabaseVersionDate != 0 &&
                activationModel.MaximumSystemVersion != 0)
            {
                if (Singleton.SystemVersionDate < activationModel.DatabaseVersionDate)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #23
0
        public PinnaFaceServerDBContext Create()
        {
            #region For Debug
            string sQlServConString = DbCommandUtil.GetWebConnectionString();
            Singleton.ConnectionStringName = sQlServConString;
            Singleton.ProviderName         = "System.Data.SqlClient";
            var sql = new SqlConnectionFactory(sQlServConString);
            return(new PinnaFaceServerDBContext(sql.CreateConnection(sQlServConString), true));

            #endregion

            #region For Release
            //const string serverIp = "198.38.83.33";
            //const string serverInitialCatalog = "ibrahim11_amstock1";
            //var sQlServerConString = "Data Source=" + serverIp + ";Initial Catalog=" + serverInitialCatalog + ";"+
            //                          "User ID=ibrahim11_armsdev;Password=@rmsd3v;"+
            //                          "encrypt=true;trustServerCertificate=true";

            //var sql = new SqlConnectionFactory(sQlServerConString);
            //return new PinnaFaceServerDBContext(sql.CreateConnection(sQlServerConString), true);
            #endregion
        }
Example #24
0
        private void UploadFiles(IEnumerable <string> fileNames)
        {
            using (var client = new WebClient())
            {
                client.Credentials = DbCommandUtil.GetNetworkCredential();

                foreach (var fileName in fileNames)
                {
                    var destpa        = new Uri(Path.Combine(_destination, fileName));
                    var sourceLogFile = Path.Combine(_sourceFile, fileName);
                    try
                    {
                        client.UploadFile(destpa, WebRequestMethods.Ftp.UploadFile, sourceLogFile);
                    }
                    catch (Exception ex)
                    {
                        LogUtil.LogError(ErrorSeverity.Critical, "FileUploader.UploadFile problem",
                                         ex.Message + Environment.NewLine + ex.InnerException, "", "");
                    }
                }
            }
        }
Example #25
0
        private static void UpdateDataAdapter()
        {
            Insert();

            #region Config DataAdapater

            var comm = new DbCommandUtil("SELECT * FROM TEST");

            const string insertSql = "INSERT INTO TEST(ID,VALUE) VALUES(@ID, @VALUES)";
            comm.ChangeDataAdaterCommand(DataAdapterCommand.Insert, insertSql);
            comm.CreateParameter("@ID", DbType.Int32, "ID");
            comm.CreateParameter("@VALUE", DbType.Decimal, 4, 2, "VALUE");

            const string updateSql = "UPDATE TEST SET VALUE = @VALUE) WHERE ID=@ID";
            comm.ChangeDataAdaterCommand(DataAdapterCommand.Update, updateSql);
            comm.CreateParameter("@ID", DbType.Int32, "ID");
            comm.CreateParameter("@VALUE", DbType.Decimal, 4, 2, "VALUE");

            const string deleteSql = "DELETE TEST WHERE ID=@ID";
            comm.ChangeDataAdaterCommand(DataAdapterCommand.Delete, deleteSql);
            comm.CreateParameter("@ID", DbType.Int32, "ID");

            #endregion Config DataAdapater

            var dt = comm.GetDataTable();
            dt.Rows.Add(3, 100.1);
            dt.Rows[0].Delete();
            dt.Rows[1]["VALUE"] = 100.2;
            comm.Update(dt);

            dt = comm.GetDataTable();
            Assert.Equal(2, dt.Rows.Count);
            Assert.Equal(2, dt.Rows[0][0]);
            Assert.Equal(100.2, dt.Rows[0][1]);
            Assert.Equal(3, dt.Rows[1][0]);
            Assert.Equal(100.1, dt.Rows[1][1]);
        }
Example #26
0
        public PinnaFaceDbContext Create()
        {
            switch (Singleton.Edition)
            {
            case PinnaFaceEdition.CompactEdition:

                var sqlCeConString = DbCommandUtil.GetConnectionString();

                Singleton.ConnectionStringName = sqlCeConString;
                Singleton.ProviderName         = "System.Data.SqlServerCe.4.0";
                var sqlce = new SqlCeConnectionFactory(Singleton.ProviderName);
                return(new PinnaFaceDbContext(sqlce.CreateConnection(sqlCeConString), true));

            case PinnaFaceEdition.ServerEdition:

                var sQlServConString = DbCommandUtil.GetConnectionString();

                Singleton.ConnectionStringName = sQlServConString;
                Singleton.ProviderName         = "System.Data.SqlClient";
                var sql = new SqlConnectionFactory(sQlServConString);
                return(new PinnaFaceDbContext(sql.CreateConnection(sQlServConString), true));
            }
            return(null);
        }
Example #27
0
        private void BuildTable()
        {
            string sql = String.Format("SELECT TOP 0 * FROM {0}", FullName);

            using (var comm = new DbCommandUtil(sql))
            {
                _TableSchema           = comm.GetDataTable();
                _TableSchema.TableName = Name;
            }
            // Build columns
            foreach (DataColumn column in _TableSchema.Columns)
            {
                var tableColumn = new Column
                {
                    Name      = column.ColumnName,
                    AllowNull = column.AllowDBNull,
                    ReadOnly  = column.ReadOnly,
                    DataType  = column.DataType,
                    MaxLength = column.MaxLength
                };
                Columns.Add(tableColumn.Name, tableColumn);
            }
            BuildIndexes();
        }
Example #28
0
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            ProductActivation.ProductKey = ProductKey;
            var key = _dbContext.ActivationKeys
                      .FirstOrDefault(a => a.ProductKey == ProductActivation.ProductKey &&
                                      a.KeyStatus == 0 && a.ProductType == 0);

            //O represents Active and O represents PinnaFace

            if (key != null)
            {
                try
                {
                    if (string.IsNullOrEmpty(key.BIOS_SN))
                    {
                        key.BIOS_SN = ProductActivation.BiosSn;
                        //key.FirstActivatedDate = DateTime.Now;
                        //    //GETUTCDATETIME StoredPr. //the time will be better if it is the server timer
                        //key.ExpirationDate = key.FirstActivatedDate.Value.AddDays(key.ExpiryDuration);
                    }
                    else
                    {
                        if (!key.BIOS_SN.Contains(ProductActivation.BiosSn))
                        {
                            if (key.NoOfAllowedPcs == 1)
                            {
                                MessageBox.Show(
                                    "Can't Activate the product, " +
                                    "Check your product key and try again, " +
                                    "or contact pinnaface office!", "More than Allowed Pcs");
                                ProductKey        = "";
                                CommandsEnability = true;

                                return;
                            }

                            key.BIOS_SN = key.BIOS_SN + "," + ProductActivation.BiosSn;
                            if (key.BIOS_SN.Split(',').Count() > key.NoOfAllowedPcs)
                            {
                                MessageBox.Show(
                                    "Can't Activate the product, " +
                                    "Check your product key and try again, " +
                                    "or contact pinnaface office!", "More than Allowed Pcs");
                                ProductKey        = "";
                                CommandsEnability = true;
                                return;
                            }
                        }
                    }

                    key.NoOfActivations = key.NoOfActivations + 1;
                    if (key.NoOfActivations > key.NoOfAllowedActivations)
                    {
                        MessageBox.Show(
                            "Can't Activate the product, " +
                            "Check your product key and try again, " +
                            "or contact pinnaface office!", "More than Allowed Activations");
                        ProductKey        = "";
                        CommandsEnability = true;
                        return;
                    }

                    _dbContext.Add(key);
                    _dbContext.SaveChanges();

                    ProductActivation.RegisteredBiosSn = key.BIOS_SN;
                    ProductActivation.DateLastModified = DbCommandUtil.GetCurrentSqlDate(true);//  DateTime.Now; //GETUTCDATETIME StoredPr
                    ProductActivation.Synced           = false;

                    if (ProductActivation.Id == 0)
                    {
                        ProductActivation.LicensedTo           = key.CustomerName;
                        ProductActivation.DatabaseVersionDate  = Singleton.SystemVersionDate;
                        ProductActivation.MaximumSystemVersion = key.MaximumAllowedSystemVersion;


                        ProductActivation.ModifiedByUserId  = 1;
                        ProductActivation.CreatedByUserId   = 1;
                        ProductActivation.DateRecordCreated = DbCommandUtil.GetCurrentSqlDate(true);//DateTime.Now; //GETUTCDATETIME StoredPr

                        #region Set UserAccounts

                        ProductActivation.SuperName = key.SuperName; //.Email;
                        ProductActivation.SuperPass = key.SuperPass;
                        ProductActivation.AdminName = key.AdminName;
                        ProductActivation.AdminPass = key.AdminPass;
                        ProductActivation.User1Name = key.User1Name;
                        ProductActivation.User1Pass = key.User1Pass;

                        #endregion

                        #region Agency

                        var localAgency = new AgencyDTO
                        {
                            AgencyName         = key.CustomerName ?? (key.CustomerName = ""),
                            AgencyNameAmharic  = "-",
                            ManagerName        = "-",
                            ManagerNameAmharic = "-",
                            Address            = new AddressDTO
                            {
                                AddressType  = AddressTypes.Local,
                                Country      = CountryList.Ethiopia,
                                City         = EnumUtil.GetEnumDesc(CityList.AddisAbeba),
                                Region       = "14",
                                Telephone    = key.Telephone ?? (key.Telephone = ""),
                                PrimaryEmail = key.Email ?? (key.Email = "")
                            },
                            Header           = new AttachmentDTO(),
                            Footer           = new AttachmentDTO(),
                            LicenceNumber    = "-",
                            SaudiOperation   = key.SaudiOperation,
                            DubaiOperation   = key.DubaiOperation,
                            KuwaitOperation  = key.KuwaitOperation,
                            QatarOperation   = key.QatarOperation,
                            JordanOperation  = key.JordanOperation,
                            LebanonOperation = key.LebanonOperation,
                            BahrainOperation = key.BahrainOperation,
                            DepositAmount    = "100,000 USD",
                            Managertype      = "ዋና ስራ አስኪያጅ"
                        };

                        #endregion

                        #region Foreign Agents

                        var foreignAgent = new AgentDTO
                        {
                            AgentName        = "-",
                            AgentNameAmharic = "-",
                            Address          = new AddressDTO
                            {
                                AddressType = AddressTypes.Foreign,
                                Country     = CountryList.SaudiArabia,
                                City        = EnumUtil.GetEnumDesc(CityList.Riyadh)
                            },
                            LicenseNumber = "-",
                            Header        = new AttachmentDTO(),
                            Footer        = new AttachmentDTO(),
                        };

                        #endregion

                        #region Setting

                        var setting = new SettingDTO
                        {
                            AwajNumber             = "923/2008",
                            EmbassyApplicationType = EmbassyApplicationTypes.SponsorNameOnTop,
                            SyncDuration           = 1,
                            StartSync = true,
                        };

                        #endregion

                        ProductActivation.FirstActivatedDate = key.FirstActivatedDate; // DateTime.Now; //GETUTCDATETIME StoredPr
                        ProductActivation.ExpiryDate         = key.ExpiryDate;         // DateTime.Now.AddDays(key.ExpiryDuration);

                        ProductActivation.Agency = localAgency;
                        setting.Agency           = localAgency;

                        ////Since we don't update Header and Footer from Server we didnt need the following 6 lines
                        //localAgency.Address.Agency = localAgency;
                        //localAgency.Header.Agency = localAgency;
                        //localAgency.Footer.Agency = localAgency;

                        //foreignAgent.Address.Agency = localAgency;
                        //foreignAgent.Header.Agency = localAgency;
                        //foreignAgent.Footer.Agency = localAgency;

                        _unitOfWork.Repository <AgencyDTO>().Insert(localAgency);
                        _unitOfWork.Repository <AgentDTO>().Insert(foreignAgent);

                        _unitOfWork.Repository <SettingDTO>().Insert(setting);
                        _unitOfWork.Repository <ProductActivationDTO>().Insert(ProductActivation);
                    }
                    else
                    {
                        //localAgency.Synced = false;
                        //foreignAgent.Synced = false;

                        //_unitOfWork.Repository<AgencyDTO>().Update(localAgency);
                        //_unitOfWork.Repository<AgentDTO>().Update(foreignAgent);

                        _unitOfWork.Repository <ProductActivationDTO>().Update(ProductActivation);
                    }

                    int changes = _unitOfWork.Commit();
                    if (changes > 0)
                    {
                        Singleton.ProductActivation = ProductActivation;
                        _login = true;
                    }
                    else
                    {
                        MessageBox.Show(
                            "Can't Activate the product, check your product key and try again, or contact pinnasofts!");
                        ProductKey        = "";
                        CommandsEnability = true;
                    }
                }
                catch
                {
                    MessageBox.Show("Error:" + Environment.NewLine + " There may be no Internet connection." +
                                    Environment.NewLine + "Check your connection and try again.");
                    CommandsEnability = true;
                }
            }
            else
            {
                MessageBox.Show(
                    "Can't Activate the product, check your product key and try again, or contact pinnasofts!");
                ProductKey        = "";
                CommandsEnability = true;
            }
        }
Example #29
0
        public void Sync() //(object sender, DoWorkEventArgs e)
        {
            Singleton.SystemVersionDate = DbCommandUtil.GetCurrentDatabaseVersion();

            var productionDbVersion = Convert.ToInt32(DbCommandUtil.GetCurrentDbVersion());
            var systemVersionDate   = Convert.ToInt32(Singleton.SystemVersionDate);

            if (systemVersionDate < productionDbVersion)
            {
                LogUtil.LogError(ErrorSeverity.Critical, "ValidateProduct",
                                 "Higher Database Version", UserName, Agency);
                return;
            }

            LogUtil.LogError(ErrorSeverity.Critical, "Sync", "Started", UserName, Agency);

            AgencyWithAgentsUtility.InsertAgencyNamesonAddressesandAttachments();
            if (!AgencyWithAgentsUtility.InsertAgencyWithAgents(UserName, Agency))
            {
                return;
            }
            if (!AgencyWithAgentsUtility.InsertUserWithAgencyWithAgents(UserName, Agency))
            {
                return;
            }


            IUnitOfWork sourceUnitOfWork = new UnitOfWork(
                new DbContextFactory().Create());
            IUnitOfWork destinationUnitOfWork = new UnitOfWorkServer(
                new ServerDbContextFactory().Create());

            var agency = sourceUnitOfWork.Repository <AgencyDTO>()
                         .Query()
                         .Get()
                         .FirstOrDefault();

            //Setting = sourceUnitOfWork.Repository<SettingDTO>()
            //    .Query()
            //    .Get(1)
            //    .FirstOrDefault();

            try
            {
                //if (Setting != null)
                //{
                //    LastFromServerSyncDate = Setting.LastFromServerSyncDate != null
                //        ? (DateTime) Setting.LastFromServerSyncDate
                //        : DbCommandUtil.GetCurrentSqlDate(false).AddYears(-1);//If it is for first time collect all last one year data
                //    LastToServerSyncDate = Setting.LastToServerSyncDate != null
                //        ? (DateTime) Setting.LastToServerSyncDate
                //        : DbCommandUtil.GetCurrentSqlDate(false).AddYears(-1);
                //}
                //else
                //{
                LastFromServerSyncDate = DbCommandUtil.GetCurrentSqlDate(false).AddYears(-10);
                LastToServerSyncDate   = DbCommandUtil.GetCurrentSqlDate(false).AddYears(-10);
                //}
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ErrorSeverity.Critical, "Sync DbCommandUtil.GetCurrentSqlDate(true)",
                                 ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
            }

            LogUtil.LogError(ErrorSeverity.Info, "Sync To Server",
                             "Started", UserName, Agency);

            #region Sync To Server

            ToServerSyncing    = true;
            LastServerSyncDate = LastToServerSyncDate; //.AddMinutes(-10);//-10 Minutes should be syncronized with MonitorTimerElapsed

            try
            {
                if (!SyncUsers2(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncAgencies2(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                Singleton.Agency = destinationUnitOfWork.Repository <AgencyDTO>()
                                   .Query().Filter(a => a.RowGuid == agency.RowGuid)
                                   .Get()
                                   .FirstOrDefault();

                if (!SyncAddresses(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncAttachments(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncRequiredDocuments(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncVisaSponsors(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncVisaConditions(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncEducation(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncExperiences(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncHawala(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncInsurance(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncLabour(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncEmbassy(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncFlight(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncAgencies(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncForeignAgents(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncAgencyWithAgents(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncSettings(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncProductActivations(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncVisas(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncEmployees(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncRelatives(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncComplains(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncComplainRemarks(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncEmployees2(sourceUnitOfWork, destinationUnitOfWork, false))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                if (!SyncUsers(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncMemberships(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncRoles(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncUsersInRoles(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow(destinationUnitOfWork);
                if (!SyncUserWithAgencyWithAgentDTO(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }

                //Sync Setting
                try
                {
                    if (!_errorsFound && _updatesFound)
                    {
                        var        setUnitOfWork = new UnitOfWork(new DbContextFactory().Create());
                        SettingDTO set           = setUnitOfWork.Repository <SettingDTO>().Query().Get(1).FirstOrDefault();

                        if (set != null)
                        {
                            set.LastToServerSyncDate = DbCommandUtil.GetCurrentSqlDate(false); //.AddHours(-1);
                        }
                        setUnitOfWork.Repository <SettingDTO>().SimpleUpdate(set);
                        setUnitOfWork.Commit();
                        setUnitOfWork.Dispose();
                    }
                    else
                    {
                        LogUtil.LogError(ErrorSeverity.Critical, "Sync To Server",
                                         "No Updates Found", UserName, Agency);
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.LogError(ErrorSeverity.Critical, "Update Setting.LastToServerSyncDate",
                                     ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
                }
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ErrorSeverity.Critical, "Sync General Method",
                                 ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
            }
            finally
            {
                try
                {
                    sourceUnitOfWork.Dispose();
                }
                catch (Exception ex)
                {
                    LogUtil.LogError(ErrorSeverity.Critical, "Sync General sourceUnitOfWork.Dispose",
                                     ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
                }
            }

            #endregion

            LogUtil.LogError(ErrorSeverity.Info, "Sync To Server", "Completed", UserName, Agency);

            #region Dispose UoW

            try
            {
                sourceUnitOfWork.Dispose();
                destinationUnitOfWork.Dispose();
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ErrorSeverity.Critical, "Dispose Unit of Work Method",
                                 ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
            }

            #endregion

            LogUtil.LogError(ErrorSeverity.Info, "Sync From Server", "Started", UserName, Agency);

            #region Sync From Server

            ToServerSyncing  = false;
            Singleton.Agency = agency;
            try
            {
                LastServerSyncDate = LastFromServerSyncDate; //.AddMinutes(-10);
                //-10 Minutes should be syncronized with MonitorTimerElapsed


                sourceUnitOfWork      = new UnitOfWorkServer(new ServerDbContextFactory().Create());
                destinationUnitOfWork = new UnitOfWork(new DbContextFactory().Create());

                if (!SyncSettings(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);
                if (!SyncProductActivations(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);

                if (!SyncAddresses(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);

                if (!SyncVisaSponsors(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);
                if (!SyncVisaConditions(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);

                if (!SyncVisas(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);

                if (!SyncEmployees(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);

                if (!SyncComplains(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);
                if (!SyncComplainRemarks(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);
                if (!SyncEmployees2(sourceUnitOfWork, destinationUnitOfWork, true))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);

                if (!SyncRoles(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                destinationUnitOfWork = GetNewUow2(destinationUnitOfWork);
                if (!SyncUsersInRoles(sourceUnitOfWork, destinationUnitOfWork))
                {
                    return;
                }
                ////destinationUnitOfWork = GetNewUow(destinationUnitOfWork);

                //Sync Setting
                try
                {
                    if (!_errorsFound && _updatesFound)
                    {
                        var        setUnitOfWork = new UnitOfWork(new DbContextFactory().Create());
                        SettingDTO set           = setUnitOfWork.Repository <SettingDTO>().Query().Get(1).FirstOrDefault();

                        if (set != null)
                        {
                            set.LastFromServerSyncDate = DbCommandUtil.GetCurrentSqlDate(false); //.AddHours(-1);
                        }
                        setUnitOfWork.Repository <SettingDTO>().SimpleUpdate(set);
                        setUnitOfWork.Commit();
                        setUnitOfWork.Dispose();
                    }
                    else
                    {
                        LogUtil.LogError(ErrorSeverity.Critical, "Sync From Server",
                                         "No Updates Found", UserName, Agency);
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.LogError(ErrorSeverity.Critical, "Update Setting.LastFromServerSyncDate",
                                     ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
                }
            }
            catch (Exception ex)
            {
                LogUtil.LogError(ErrorSeverity.Critical, "Sync From Server General Method",
                                 ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
            }
            finally
            {
                try
                {
                    sourceUnitOfWork.Dispose();
                }
                catch (Exception ex)
                {
                    LogUtil.LogError(ErrorSeverity.Critical, "Sync From Server General sourceUnitOfWork.Dispose()",
                                     ex.Message + Environment.NewLine + ex.InnerException, UserName, Agency);
                }
            }

            #endregion

            LogUtil.LogError(ErrorSeverity.Info, "Sync From Server",
                             "Completed", UserName, Agency);
        }