public static bool SaveOutcome(CreateOutcomeVModel Outcome)
        {
            try
            {
                using (var model = new fmDbDataModel())
                {
                    fm_Outcomes newOutcome = new fm_Outcomes()
                    {
                        UserId = UserSingleton.Instance.Id,
                        Name   = Outcome.Name,
                        Type   = (int)Enum.Parse(typeof(OutcomeType), Outcome.OutcomeType.ToString()),
                        Amount = Outcome.Amount,
                        //Currency = (int)Enum.Parse(typeof(CurrencyType), Outcome.Currency.ToString()),
                        InsertTime = DateTime.Now
                    };

                    model.fm_Outcomes.Add(newOutcome);
                    model.SaveChanges();
                }

                return(true);
            }
            catch (Exception e)
            {
                DataOperationManager.VerifyResult(new Func <CreateOutcomeVModel, bool>(SaveOutcome), new object[] { Outcome }, MethodReturnStatus.Error);

                _log.ErrorFormat("There was an error with saving the outcome. Message: {0}, Stacktrace: {1}", e.Message, e.StackTrace);
                return(false);
            }
        }
        public static bool InsertUser(RegisterVModel userRegister)
        {
            using (var model = new fmDbDataModel())
            {
                try
                {
                    string hashedPassword = SecurityManager.CalculateHash(userRegister.Password);

                    fm_Users newUser = new fm_Users()
                    {
                        Name     = userRegister.Name,
                        Email    = userRegister.Email,
                        Password = hashedPassword,
                        Salt     = SecurityManager.GetSalt(), // later will be taken from database and fetched with new password to compare with the old one

                        InsertTime    = DateTime.Now,
                        AccountStatus = (int)AccountStatus.Active
                    };
                    // Adding the user to the currently connected database and now performing the same operation on the mirror ones.
                    model.fm_Users.Add(newUser);
                    model.SaveChanges();
                    DataOperationManager.Synch(new Func <RegisterVModel, bool>(InsertUser), new object[] { userRegister });

                    return(true);
                }
                catch (Exception e)
                {
                    DataOperationManager.VerifyResult(new Func <RegisterVModel, bool>(InsertUser), new object[] { userRegister }, MethodReturnStatus.Error);
                    _log.ErrorFormat("There was an error with inserting user to db. Message: {0}, Stacktrace: {1}", e.Message, e.StackTrace);
                    return(false);
                }
            }
        }
        public static void SwitchCurrency(CurrencyType?currency)
        {
            if (currency == null)
            {
                return;
            }

            using (var model = new fmDbDataModel())
            {
                try
                {
                    if (HttpContext.Current.Session["USER_ID"] != null)
                    {
                        long userId = Convert.ToInt64(HttpContext.Current.Session["USER_ID"].ToString());
                        var  user   = model.fm_Users.FirstOrDefault(u => u.Id == userId);
                        if (user != null)
                        {
                            UserSingleton.Instance.DefaultCurrency = (int)currency;
                            user.DefaultCurrency = (int)currency;
                            model.SaveChanges();
                            DataOperationManager.Synch(new Action <CurrencyType?>(SwitchCurrency), new object[] { currency });
                        }
                        else
                        {
                            DataOperationManager.VerifyResult(new Action <CurrencyType?>(SwitchCurrency), new object[] { currency }, MethodReturnStatus.Null);
                        }
                    }
                }
                catch (Exception e)
                {
                    DataOperationManager.VerifyResult(new Action <CurrencyType?>(SwitchCurrency), new object[] { currency }, MethodReturnStatus.Error);
                    _log.ErrorFormat("There was an error with inserting user to db. Message: {0}, Stacktrace: {1}", e.Message, e.StackTrace);
                }
            }
        }
        public static double SumOutcomes()
        {
            try
            {
                using (var model = new fmDbDataModel())
                {
                    var sum = model.fm_Outcomes
                              .Where(o => o.UserId == UserSingleton.Instance.Id)
                              .Select(o => o.Amount ?? 0)
                              .DefaultIfEmpty()
                              .Sum();

                    return(sum);
                }
            }
            catch (Exception)
            {
                DataOperationManager.VerifyResult(new Func <double>(SumOutcomes), null, MethodReturnStatus.Error);
                throw;
            }
        }
Exemplo n.º 5
0
        public static LoginVModel UserSignIn(LoginVModel UserLogin)
        {
            fm_Users userExists = null;

            try
            {
                using (var model = new fmDbDataModel())
                {
                    userExists =
                        model.fm_Users.FirstOrDefault(user => user.Email.Equals(UserLogin.Email));

                    if (userExists == null)
                    {
                        return((LoginVModel)DataOperationManager.VerifyResult(new Func <LoginVModel, LoginVModel>(UserSignIn), new object[] { UserLogin }, HostCommunication.HostModels.MethodReturnStatus.Null));
                    }

                    string hashedPassword = SecurityManager.CalculateHash(UserLogin.Password, userExists.Salt);

                    if (SecurityManager.ComparePasswords(userExists.Password, hashedPassword))
                    {
                        bool isInitialized = UserManager.InitializeUserLogin(userExists);
                        if (isInitialized)
                        {
                            return(new LoginVModel()
                            {
                                Email = UserLogin.Email,
                                Password = hashedPassword
                            });
                        }
                    }
                    _log.InfoFormat("User with {0} email could not login.", UserLogin.Email);
                    return(null);
                }
            }
            catch (Exception e)
            {
                return((LoginVModel)DataOperationManager.VerifyResult(new Func <LoginVModel, LoginVModel>(UserSignIn), new object[] { UserLogin }, HostCommunication.HostModels.MethodReturnStatus.Error));
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Adds the AuditableProduct object specified by the product input parameter to the data source and updates its Id property asynchronously.
 /// </summary>
 /// <param name="product">The AuditableProduct object to add to the data source.</param>
 public Task <SetDataOperationResult> AddProductAsync(AuditableProduct product)
 {
     return(DataOperationManager.TrySetAsync(() => DataProvider.AddProduct(InitializeDataModel(product)), $"{product.Name} was added to the data source successfully", $"A problem occurred and {product.Name} was not added to the data source."));
 }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new DataController with the values from the input parameters.
 /// </summary>
 /// <param name="dataProvider">The IDataProvider object that provides access to the application data source.</param>
 /// <param name="dataOperationManager">The DataOperationManager object used to perform asynchronous and retryable data operations with.</param>
 /// <param name="currentUser">The User that is currently logged in to the application.</param>
 public DataController(IDataProvider dataProvider, DataOperationManager dataOperationManager, User currentUser)
 {
     DataProvider         = dataProvider;
     DataOperationManager = dataOperationManager;
     CurrentUser          = currentUser?.Clone();
 }
Exemplo n.º 8
0
 /// <summary>
 /// Updates the AuditableProduct object specified by the product input parameter in the data source.
 /// </summary>
 /// <param name="product">The AuditableProduct object to update in the data source.</param>
 /// <returns>A SetDataOperationResult object containing details relating to whether the operation was successful or not.</returns>
 public SetDataOperationResult UpdateProduct(AuditableProduct product)
 {
     return(DataOperationManager.TrySet(() => DataProvider.UpdateProduct(UpdateDataModel(product)), $"{product.Name} was saved in the data source successfully.", $"A problem occurred and {product.Name} was not updated in the data source.", false, false));
 }
Exemplo n.º 9
0
 /// <summary>
 /// Gets all of the AuditableProduct objects in the application in an AuditableProducts collection asynchronously.
 /// </summary>
 /// <returns>An AuditableProducts collection that contains all of the AuditableProduct objects in the application.</returns>
 public Task <GetDataOperationResult <AuditableProducts> > GetProductsAsync()
 {
     return(DataOperationManager.TryGetAsync(() => DataProvider.GetProducts(), string.Empty, "A problem occurred when trying to retrieve the products.", true));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Deletes the AuditableProduct object specified by the product input parameter from the data source asynchronously.
 /// </summary>
 /// <param name="product">The AuditableProduct object to remove from the data source.</param>
 /// <returns>A SetDataOperationResult object containing details relating to whether the operation was successful or not.</returns>
 public Task <SetDataOperationResult> DeleteProductAsync(AuditableProduct product)
 {
     return(DataOperationManager.TrySetAsync(() => DataProvider.DeleteProduct(DeleteDataModel(product)), $"{product.Name} has been deleted from the data source successfully.", $"A problem occurred and {product.Name} was not deleted from the data source.", true, false));
 }
        public PartialViewResult TakeArticleBody(int?datpagnum = 0, int datcatnum = 0, bool likecntrl = false)
        {
            DataOperationManager dat = new DataOperationManager();
            int skp = datpagnum.Value;

            if (datpagnum.Value != 0)
            {
                skp = (datpagnum.Value - 1) * 9;
            }


            if (datcatnum == 0 && datpagnum != 0 && likecntrl == false)
            {
                List <Article> articles = article_mngr.ListQueryable().Where(x => x.IsDraft == false).OrderByDescending(x => x.ModifiedOn).Skip(skp).Take(9).ToList();

                dat.data_article_list  = articles;
                dat.number_of_elements = DataOperationManager.TakePageNumber(article_mngr.ListQueryable().Where(x => x.IsDraft == false).Count());
                dat.categoryid         = 0;
                dat.likecntrl          = false;

                return(PartialView("_PartialIndexBody", dat));
            }
            else if (datcatnum != 0 && datpagnum == 0 && likecntrl == false)
            {
                List <Article> categorizedarticles = article_mngr.ListQueryable().Where(x => x.IsDraft == false && x.CategoryId == datcatnum).OrderByDescending(x => x.ModifiedOn).Take(9).ToList();
                dat.data_article_list  = categorizedarticles;
                dat.number_of_elements = DataOperationManager.TakePageNumber(article_mngr.ListQueryable().Where(x => x.IsDraft == false && x.CategoryId == datcatnum).Count());
                dat.categoryid         = datcatnum;
                dat.likecntrl          = false;

                return(PartialView("_PartialIndexBody", dat));
            }
            else if (datcatnum != 0 && datpagnum != 0 && likecntrl == false)
            {
                List <Article> categorizedarticles = article_mngr.ListQueryable().Where(x => x.IsDraft == false && x.CategoryId == datcatnum).OrderByDescending(x => x.ModifiedOn).Skip(skp).Take(9).ToList();
                dat.data_article_list  = categorizedarticles;
                dat.number_of_elements = DataOperationManager.TakePageNumber(article_mngr.ListQueryable().Where(x => x.IsDraft == false && x.CategoryId == datcatnum).Count());
                dat.categoryid         = datcatnum;
                dat.likecntrl          = false;
                return(PartialView("_PartialIndexBody", dat));
            }
            else if (datcatnum == 0 && datpagnum == 0 && likecntrl == true)
            {
                List <Article> likestatusarticle = article_mngr.ListQueryable().Where(x => x.IsDraft == false).OrderByDescending(x => x.LikeCount).Take(9).ToList();
                dat.data_article_list  = likestatusarticle;
                dat.number_of_elements = DataOperationManager.TakePageNumber(article_mngr.ListQueryable().Where(x => x.IsDraft == false).OrderByDescending(x => x.LikeCount).Count()); // TODO : zaten yine üsteki ile aynı sayısı döner işi otomatikleştir.
                dat.categoryid         = 0;
                dat.likecntrl          = true;
                return(PartialView("_PartialIndexBody", dat));
            }
            else if (datcatnum == 0 && datpagnum != 0 && likecntrl == true)
            {
                List <Article> likestatusarticle = article_mngr.ListQueryable().Where(x => x.IsDraft == false).OrderByDescending(x => x.LikeCount).Skip(skp).Take(9).ToList();
                dat.data_article_list  = likestatusarticle;
                dat.number_of_elements = DataOperationManager.TakePageNumber(article_mngr.ListQueryable().Where(x => x.IsDraft == false).OrderByDescending(x => x.LikeCount).Count()); // TODO : zaten yine üsteki ile aynı sayısı döner işi otomatikleştir.
                dat.categoryid         = 0;
                dat.likecntrl          = true;
                return(PartialView("_PartialIndexBody", dat));
            }
            //Aslinda asagidaki durum catid==0 && id==0 durumunu ifade etmekdir. fakat .Net bize en az bir return ifadesini if-else statement dişinda yazmaya zorladiğindan bunu yukaridaki şartlar sağlanmadiği takdirde garanti girilecek durum olarak aşagi yazdik!

            List <Article> get_articles = article_mngr.ListQueryable().Where(x => x.IsDraft == false).OrderByDescending(x => x.ModifiedOn).Take(9).ToList();


            dat.data_article_list  = get_articles;
            dat.number_of_elements = DataOperationManager.TakePageNumber(article_mngr.ListQueryable().Where(x => x.IsDraft == false).Count());
            dat.categoryid         = 0;
            dat.likecntrl          = false;
            return(PartialView("_PartialIndexBody", dat));
        }
Exemplo n.º 12
0
        public static void PrepareRAID()
        {
            _listOfDbDescriptions = CheckDatabasesExistence();

            for (int i = 0; i < _listOfDbDescriptions.Count; i++) // informing each database about its mirrors
            {
                var mirrorDbs = _listOfDbDescriptions.FindAll(db => ((db.Server != _listOfDbDescriptions[i].Server) && (db.MirrorSide == _listOfDbDescriptions[i].MirrorSide)));
                foreach (var mirror in mirrorDbs)
                {
                    _listOfDbDescriptions[i].DbMirrors.Add(mirror);
                }
            }

            foreach (var dbDescription in _listOfDbDescriptions)
            {
                foreach (var dbMirror in dbDescription.DbMirrors)
                {
                    if (!dbMirror.Exists && !dbDescription.Exists)
                    {
                        dbDescription.ShouldBeRecreated = dbMirror.ShouldBeRecreated = CreationType.FromScratch;
                    }
                    else if (!dbMirror.Exists && dbDescription.Exists)
                    {
                        dbMirror.ShouldBeRecreated      = CreationType.ByMirroring;
                        dbDescription.ShouldBeRecreated = CreationType.None;
                    }
                }
            }


            if (_listOfDbDescriptions.Find(db => db.ShouldBeRecreated == CreationType.FromScratch) != null)
            {
                foreach (var dbDescription in _listOfDbDescriptions)
                {
                    if (dbDescription.ShouldBeRecreated == CreationType.FromScratch)
                    {
                        RunSqlAgainstDatabase(dbDescription, ConfigurationManager.AppSettings["sqlCreateBackupDb"], dbDescription.ServerDirectory);
                    }
                }
                DeleteData();
                SpreadData();
            }
            else
            {
                foreach (var dbDescription in _listOfDbDescriptions)
                {
                    if (dbDescription.ShouldBeRecreated == CreationType.ByMirroring)
                    {
                        // get mirror data
                        var workingMirror = dbDescription.DbMirrors.Find(db => db.ShouldBeRecreated == CreationType.None); // it means the mirror exists and data should be taken from there

                        SynchManager.CreateDbMirror(dbDescription, workingMirror);

                        // update recreation status to none
                        dbDescription.ShouldBeRecreated = CreationType.None;
                    }
                }
            }

            // set d0 db as the main database
            DataOperationManager.InitializeDbsData(_listOfDbDescriptions, _listOfDbDescriptions[0]);
            DataOperationManager.UpdateConnString(_listOfDbDescriptions[0]);
        }