예제 #1
0
        public static async Task <ResultsItem> UpdateUserCoinAsync(LocalCoins.CryptoCoin coin)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    Coins serviceCoin = db.Coins.FirstOrDefault(x => x.CoinId == coin.CoinId);
                    if (serviceCoin == null)
                    {
                        return(ResultsItem.Error("This coin was not found."));
                    }

                    serviceCoin.Shares                = coin.Shares;
                    serviceCoin.CoinCurrency          = (short)coin.CoinCurrency;
                    serviceCoin.PricePerUnit          = coin.PricePerUnit;
                    serviceCoin.TotalPricePaidUsd     = coin.TotalPricePaidUSD;
                    serviceCoin.Exchange              = (short)coin.Exchange;
                    serviceCoin.OrderType             = (short)coin.OrderType;
                    serviceCoin.OrderDate             = coin.OrderDate;
                    serviceCoin.SoldCoinCurrency      = (short)coin.SoldCoinCurrency;
                    serviceCoin.SoldPricePerUnit      = coin.SoldPricePerUnit;
                    serviceCoin.TotalSoldPricePaidUsd = coin.TotalSoldPricePaidUSD;

                    db.Update(serviceCoin);
                    await db.SaveChangesAsync();
                }

                return(ResultsItem.Success("Successfully updated coin."));
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { "UpdateUserCoinAsync", $"coinId:{coin.CoinId},portfolioId:{coin.PortfolioId}" }, ex);
                return(ResultsItem.Error($"Unable to updated coin. {ex.Message}"));
            }
        }
예제 #2
0
        public static ResultsPair <LocalCoins.Portfolio> UpdatePortfolio(int portfolioId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    Portfolios portfolio = db.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId);
                    if (portfolio != null)
                    {
                        portfolio.Name        = portfolioName.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });
                        portfolio.DisplayType = (short)displayType;
                        portfolio.IsDefault   = isDefault;

                        db.Update(portfolio);
                        db.SaveChanges();
                    }

                    return(ResultsPair.Create(ResultsItem.Success("Successfully updated portfolio name."), portfolio.Adapt <LocalCoins.Portfolio>()));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { "UpdatePortfolio", $"portfolioId:{portfolioId},portfolioName:{portfolioName}" }, ex);
                return(ResultsPair.CreateError <LocalCoins.Portfolio>($"Unable to update portfolio. {ex.Message}"));
            }
        }
예제 #3
0
        private static async Task <ResultsPair <LocalAccount.PTUserInfo> > CreateNewPTUserInfo(LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    PTUserInfo ptUserInfo = new PTUserInfo
                    {
                        UserId                 = user.UserId,
                        SubscriptionLevel      = (byte)SubscriptionLevel.Free,
                        SubscriptionExpireDate = null
                    };

                    db.PTUserInfo.Add(ptUserInfo);
                    await db.SaveChangesAsync();

                    LocalAccount.PTUserInfo localSubscription = ptUserInfo.Adapt <LocalAccount.PTUserInfo>();

                    return(ResultsPair.Create(ResultsItem.Success("Successfully created a new subscription."), localSubscription));
                }
            }
            catch (Exception ex)
            {
                return(ResultsPair.CreateError <LocalAccount.PTUserInfo>($"Unable to create a new PTUserInfo: {ex.Message}"));
            }
        }
예제 #4
0
        public async Task <JsonResult> CreateNewUser(PegaUser user)
        {
            if (!ModelState.IsValid)
            {
                return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
            }
            if (!Regex.IsMatch(user.Username, @"^[a-zA-Z0-9_\-\.]+$"))
            {
                return(Json(ResultsItem.Error("Username must contain only: Letters(A-Z), Numbers(0-9), _, -, or .")));
            }
            if (!Utilities.IsValidEmailAddress(user.Email))
            {
                return(Json("Please enter a valid email address."));
            }

            var createPair = await AuthorizationLogic.CreateNewUser(user);

            if (createPair.Result.IsSuccess)
            {
                SetSession(Constant.Session.SessionCurrentUser, createPair.Value);
                TempData["UserCreatedTransferMessage"] = createPair.Result.Message;
                return(Json(ResultsItem.Success("Success")));
            }

            return(Json(ResultsItem.Error(createPair.Result.Message)));
        }
예제 #5
0
        public async Task <JsonResult> CurrentUserChangePassword(PegaUser user)
        {
            if (user.NewChangedPassword.Length < 8 || user.NewChangedPassword.Length > 30)
            {
                return(Json(ResultsItem.Error("Password changed failed: Password length must be from 8 - 30 characters.")));
            }
            if (user.NewChangedPassword != user.ConfirmNewChangedPassword)
            {
                return(Json(ResultsItem.Error("Passwords does not match.")));
            }
            if (CurrentUser.Username != user.Username)
            {
                return(Json(ResultsItem.Error("Username does not match.")));
            }

            // do-later: check if current pw is valid first. if (!AuthorizationLogic.AuthorizeUser(CurrentUser.Username, user.Password))

            // Change password
            var pwChangeResult = await AuthorizationLogic.ChangePassword(user.Username, user.NewChangedPassword);

            if (!pwChangeResult.IsSuccess)
            {
                return(Json(pwChangeResult));
            }

            HttpContext.Session.Clear();

            string successMessage = "Your password has been successfully reset. Please login again";

            TempData["message"] = successMessage;
            return(Json(ResultsItem.Success(successMessage)));
        }
예제 #6
0
        public static async Task <ResultsItem> CreateBBComment(LocalCommunity.BBComment comment, LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    comment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });

                    BBComments serviceComment = comment.Adapt <BBComments>();
                    serviceComment.CreateDate = DateTime.Now;
                    serviceComment.UserId     = user.UserId;
                    serviceComment.Message    = serviceComment.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });

                    db.BBComments.Add(serviceComment);
                    await db.SaveChangesAsync();

                    return(ResultsItem.Success("Successfully posted a new comment."));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}" }, ex);
                return(ResultsItem.Error($"Unable to create a comment. {ex.Message}"));
            }
        }
예제 #7
0
        public async Task <IActionResult> ConfirmEmail(string username, string authCode)
        {
            ResultsItem emailResult = await AuthorizationLogic.ConfirmEmail(username, authCode);

            TempData["message"] = emailResult.Message;
            return(RedirectToAction("Index", "Home"));
        }
예제 #8
0
        public async Task <JsonResult> ExecuteCoinChanges(CoinManagementVM vm)
        {
            ResultsItem validationResult = CoinManagementValidation(vm, isSoldMode: false);

            if (!validationResult.IsSuccess)
            {
                return(Json(validationResult));
            }

            vm.Coin.OrderType   = Types.OrderType.Buy;
            vm.Coin.Exchange    = Types.Exchanges.Custom;
            vm.Coin.PortfolioId = vm.SelectedPortfolioID;

            if (vm.Coin.TotalPricePaidUSD.GetValueOrDefault() == 0)
            {
                vm.Coin.TotalPricePaidUSD = vm.Coin.OrderDate.Date == DateTime.Now.Date ? vm.Coin.Shares * CryptoLogic.GetLatestPriceOfSymbol(vm.Coin.Symbol, await GetAllCoinsMarketDetailsAPI())
                                                                                        : CryptoLogic.GenerateTotalPricePaidUSD(vm.Coin, await GetAllHistoricCoinPrices());
            }

            var coinResult = vm.IsCreateMode ? await CryptoLogic.InsertCoinsToUserPortfolioAsync(new List <CryptoCoin> {
                vm.Coin
            }, CurrentUser, vm.SelectedPortfolioID)
                                             : await CryptoLogic.UpdateUserCoinAsync(vm.Coin, CurrentUser);

            return(Json(coinResult));
        }
예제 #9
0
        public static async Task <ResultsItem> CreateBBThread(LocalCommunity.BBThread thread, LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    thread.Message = thread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });
                    thread.UserId  = user.UserId;

                    BBThreads serviceMessageThread = thread.Adapt <BBThreads>();
                    serviceMessageThread.CreateDate = DateTime.Now;
                    serviceMessageThread.UserId     = user.UserId;
                    serviceMessageThread.Message    = serviceMessageThread.Message.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });
                    serviceMessageThread.Title      = serviceMessageThread.Title.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM });

                    db.BBThreads.Add(serviceMessageThread);
                    await db.SaveChangesAsync();

                    return(ResultsItem.Success("Successfully created a new thread"));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}" }, ex);
                return(ResultsItem.Error($"Unable to create a new thread. {ex.Message}"));
            }
        }
예제 #10
0
        public static async Task <ResultsItem> DeleteBBThread(int threadId, LocalAccount.PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    BBThreads serviceThread = db.BBThreads.FirstOrDefault(x => x.ThreadId == threadId);
                    if (serviceThread == null)
                    {
                        return(ResultsItem.Error("This thread was not found or has already been deleted."));
                    }
                    if (serviceThread.UserId != user.UserId)
                    {
                        return(ResultsItem.Error("This thread belongs to another user."));
                    }

                    db.Remove(serviceThread);
                    await db.SaveChangesAsync();

                    return(ResultsItem.Success("Successfully deleted this thread. Please refresh the page to see changes."));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}" }, ex);
                return(ResultsItem.Error($"Unable to delete this thread. {ex.Message}"));
            }
        }
예제 #11
0
        public static ResultsItem InsertNewAPI(LocalCoins.ExchangeApiInfo exchangeApiDetails, PegaUser user)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    ApiDetails serviceApi = new ApiDetails
                    {
                        Name        = exchangeApiDetails.Name.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }),
                        Exchange    = (short)exchangeApiDetails.Exchange,
                        ApiAction   = (short)exchangeApiDetails.ApiAction,
                        ApiPublic   = Cryptography.Encrypt(exchangeApiDetails.ApiPublic, Types.EncryptionType.ApiKey_Public, user),
                        ApiPrivate  = Cryptography.Encrypt(exchangeApiDetails.ApiPrivate, Types.EncryptionType.ApiKey_Private, user),
                        ApiThirdKey = exchangeApiDetails.ApiThirdKey.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }),
                        DateAdded   = DateTime.Now,
                        UserId      = user.UserId,
                    };

                    db.ApiDetails.Add(serviceApi);
                    db.SaveChanges();
                }

                return(ResultsItem.Success("Successfully created a new API."));
            }
            catch (Exception ex)
            {
                return(ResultsItem.Error($"Unable to create a new API. {ex.Message}"));
            }
        }
예제 #12
0
        public static async Task <ResultsPair <LocalCoins.Portfolio> > InsertNewPortfolio(int userId, string portfolioName, Types.PortfolioDisplayType displayType, bool isDefault)
        {
            try
            {
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    Portfolios portfolio = new Portfolios
                    {
                        UserId      = userId,
                        Name        = portfolioName.Clean(new[] { Types.CleanInputType.AZ09CommonCharsSM }),
                        DisplayType = (short)displayType,
                        IsDefault   = isDefault
                    };

                    db.Portfolios.Add(portfolio);
                    await db.SaveChangesAsync();

                    return(ResultsPair.Create(ResultsItem.Success("Successfully created a new portfolio."), portfolio.Adapt <LocalCoins.Portfolio>()));
                }
            }
            catch (Exception ex)
            {
                return(ResultsPair.CreateError <LocalCoins.Portfolio>($"Unable to create a new portfolio. {ex.Message}"));
            }
        }
예제 #13
0
 public static async Task <ResultsItem> DeleteUserCoinsAsync(List <CryptoCoin> coins, PegaUser user)
 {
     if (coins.Any(x => !IsValidDBRequest(user, x.PortfolioId, validatePortfolio: true).IsSuccess))
     {
         return(ResultsItem.Error(Lang.PortfolioNotFound));
     }
     return(await CryptoRepository.DeleteUserCoinAsync(coins));
 }
예제 #14
0
        public async Task <JsonResult> ImportSyncAPI(int apiId, int portfolioId)
        {
            ExchangeApiInfo exchangeApiInfo = CurrentUser.ExchangeApiList.FirstOrDefault(x => x.Id == apiId);

            if (exchangeApiInfo == null)
            {
                return(Json(ResultsItem.Error("This API Id cannot be found")));
            }

            if (!CurrentUser.HasPortfolio(portfolioId))
            {
                return(Json(ResultsItem.Error(Lang.PortfolioNotFound)));
            }

            // Test -> Move to .Tests solution
            //List<Core.Data.ServiceModels.ImportedCoin> importedCoins = FetchAPILogic.ImportCSV_Coins(exchangeApiInfo.Exchange,
            //     System.IO.File.OpenRead(@"C:\Users\Ref\Downloads\pegatrade_importFiles\api_test1\2nd-half.csv"));

            List <Core.Data.ServiceModels.ImportedCoin> importedCoins = await FetchAPILogic.ImportAPI_Coins(exchangeApiInfo, CurrentUser);

            if (importedCoins.IsNullOrEmpty())
            {
                return(Json(ResultsItem.Error(Lang.UnableToImportWrongKeyPermission)));
            }

            List <CryptoCoin> existingExchangeCoins = (await CryptoLogic.GetAllUserCoinsByPortfolioIdAsync(portfolioId)).Where(x => x.Exchange == exchangeApiInfo.Exchange).ToList();
            DateTime          latestDate            = existingExchangeCoins.IsNullOrEmpty() ? DateTime.MinValue : existingExchangeCoins.Max(x => x.OrderDate);

            // Get rid of ANY imported coins that are less than already existing date.
            // We dont' want to mess with those, we just want to add new ones.
            importedCoins = importedCoins.Where(x => x.OrderDate > latestDate).ToList();
            if (importedCoins.IsNullOrEmpty())
            {
                Json(ResultsItem.Error(Lang.ApiAlreadyUptoDate));
            }

            List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices());

            if (fetchedCoins.Count > 0)
            {
                // Get all current holding coins that will be affected by new coins. Delete them from db as well, we'll re-add them.
                existingExchangeCoins = existingExchangeCoins.Where(x => x.OrderType == Types.OrderType.Buy && fetchedCoins.Any(f => f.Symbol.EqualsTo(x.Symbol))).ToList();
                await CryptoLogic.DeleteUserCoinsAsync(existingExchangeCoins, CurrentUser);

                existingExchangeCoins.ForEach(x => x.CoinId = 0); // Reset PK so DB can generate a new one.
                existingExchangeCoins.AddRange(fetchedCoins);
                existingExchangeCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(existingExchangeCoins);

                ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(existingExchangeCoins, CurrentUser, portfolioId);

                if (insertResults.IsSuccess)
                {
                    return(Json(ResultsItem.Success("Successfully imported coins to your portfolio.")));
                }
            }

            return(Json(ResultsItem.Error(Lang.ApiNoNewTradesOrError)));
        }
예제 #15
0
        public async Task <ResultsItem> CreateBBThread(BBThread thread)
        {
            if (!ModelState.IsValid)
            {
                return(ResultsItem.Error(ModelState.GetAllErrorsString()));
            }

            OnThreadUpdatedCacheHandler(thread.CategoryCode, thread.OfficialCoinId.GetValueOrDefault());
            return(await CommunityLogic.CreateBBThread(thread, CurrentUser));
        }
예제 #16
0
        public PartialViewResult GeneratePartialViewError(string errorMessage)
        {
            ResultsItem result = new ResultsItem
            {
                MessageColor = "text-danger font-strong",
                Message      = errorMessage
            };

            return(PartialView("~/Views/Shared/_Messages.cshtml", result));
        }
예제 #17
0
        public async Task <ResultsItem> CreateBBComment(BBComment comment)
        {
            if (!ModelState.IsValid)
            {
                return(ResultsItem.Error(ModelState.GetAllErrorsString()));
            }

            OnThreadUpdatedCacheHandler(threadId: comment.ThreadId);
            OnCommentsUpdatedCacheHandler(comment.ThreadId);
            return(await CommunityLogic.CreateBBComment(comment, CurrentUser));
        }
예제 #18
0
        public async Task <JsonResult> DeletePortfolio(int portfolioId)
        {
            ResultsItem deleteResult = await CryptoLogic.DeletePortfolio(portfolioId, CurrentUser);

            if (deleteResult.IsSuccess)
            {
                CurrentUser.Portfolios = await CryptoLogic.GetAllUserPortfolioAsync(CurrentUser);

                SubmitCurrentUserUpdate();
            }
            return(Json(deleteResult));
        }
예제 #19
0
        public JsonResult DeleteImportAPI(int apiId)
        {
            ResultsItem results = CryptoLogic.DeleteAPI(apiId, CurrentUser);

            if (results.IsSuccess)
            {
                CurrentUser.ExchangeApiList = CurrentUser.ExchangeApiList.Where(x => x.Id != apiId).ToList();
                SubmitCurrentUserUpdate();
            }

            return(Json(results));
        }
예제 #20
0
        public JsonResult CreateNewImportAPI(ExchangeApiInfo exchangeApiInfo)
        {
            if (!ModelState.IsValid)
            {
                return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
            }

            exchangeApiInfo.ApiAction  = Types.ApiAction.TradesImport;
            exchangeApiInfo.ApiPrivate = exchangeApiInfo.ApiPrivate.Replace("%2B", "+");
            ResultsItem apiResult = CryptoLogic.InsertNewAPI(exchangeApiInfo, CurrentUser);

            return(Json(apiResult));
        }
예제 #21
0
        public async Task <JsonResult> DeleteCoin(int coinId, int portfolioId)
        {
            CryptoCoin fetchedCoin = await CryptoLogic.GetSingleCoinByUser(coinId, CurrentUser);

            if (fetchedCoin?.PortfolioId != portfolioId)
            {
                return(Json(ResultsItem.Error(Lang.PortfolioNotFound)));
            }
            return(Json(await CryptoLogic.DeleteUserCoinsAsync(new List <CryptoCoin> {
                new CryptoCoin {
                    CoinId = coinId, PortfolioId = portfolioId
                }
            }, CurrentUser)));
        }
예제 #22
0
        private ResultsItem CoinManagementValidation(CoinManagementVM vm, bool isSoldMode = false)
        {
            if (!ModelState.IsValid)
            {
                return(ResultsItem.Error(ModelState.GetAllErrorsString()));
            }

            if (!isSoldMode)
            {
                vm.Coin.Symbol = vm.Coin.Symbol.ToUpperInvariant();
                if (!vm.Coin.Symbol.StartsWith("BTC-") && !vm.Coin.Symbol.StartsWith("ETH-") && !vm.Coin.Symbol.StartsWith("USD-") && !vm.Coin.Symbol.StartsWith("USDT-"))
                {
                    return(ResultsItem.Error("Error: The coin symbol must start with BTC-, ETH-, USD-, or USDT-"));
                }

                if (vm.Coin.OrderDate > DateTime.Now)
                {
                    return(ResultsItem.Error("Error: Order date must be today or the past."));
                }

                vm.Coin.CoinCurrency = CryptoLogic.GenerateCoinCurrencyFromSymbol(vm.Coin.Symbol);
                if (vm.Coin.CoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.CoinCurrency == Types.CoinCurrency.EUR)
                {
                    return(ResultsItem.Error("Error: only BTC, ETH, and USD currency is currently supported."));
                }

                if (vm.Coin.PricePerUnit <= 0)
                {
                    return(ResultsItem.Error("Please enter Price Per Unit."));
                }
            }
            else
            {
                if (!CurrentUser.HasPortfolio(vm.Coin.PortfolioId))
                {
                    return(ResultsItem.Error(Lang.PortfolioNotFound));
                }
                if (vm.Coin.SoldCoinCurrency == Types.CoinCurrency.Unknown || vm.Coin.SoldPricePerUnit.GetValueOrDefault() <= 0)
                {
                    return(ResultsItem.Error("Please enter all sold details. TotalSoldPrice is optional."));
                }

                if (vm.SoldDate < vm.Coin.OrderDate)
                {
                    return(ResultsItem.Error("Sold date cannot be lower than Buy date. Unless you're a time traveler."));
                }
            }

            return(ResultsItem.Success());
        }
예제 #23
0
        public static async Task <ResultsItem> VoteBBComment(long commentId, bool isUpvote, LocalAccount.PegaUser user)
        {
            try
            {
                string message = "Successfully updated your vote. It will be reflected shortly.";
                using (PegasunDBContext db = new PegasunDBContext())
                {
                    var getServiceCommentTask = db.BBComments.FirstOrDefaultAsync(x => x.CommentId == commentId);
                    var getExistingVoteTask   = db.BBCommentVotes.FirstOrDefaultAsync(x => x.CommentId == commentId && x.UserId == user.UserId);

                    var serviceComment = await getServiceCommentTask;
                    var existingVote   = await getExistingVoteTask;

                    if (serviceComment == null)
                    {
                        return(ResultsItem.Error("This comment does not exist."));
                    }
                    if (existingVote != null)
                    {
                        if (existingVote.IsUpvote == isUpvote)
                        {
                            db.Remove(existingVote); message = "Successfully removed your vote. It will be reflected shortly.";
                        }                                                                                                                                              // Same vote (e.g. clicked on upvote twice), which means they are re-tracing their vote.
                        else
                        {
                            existingVote.IsUpvote = isUpvote;
                        }
                    }
                    else
                    {
                        var newServiceVote = new BBCommentVotes
                        {
                            CommentId = commentId,
                            IsUpvote  = isUpvote,
                            UserId    = user.UserId
                        };
                        db.BBCommentVotes.Add(newServiceVote);
                    }

                    db.SaveChanges();
                    return(ResultsItem.Success(message));
                }
            }
            catch (Exception ex)
            {
                Utilities.LogException(new[] { $"User:{user.Username}", $"CommentId:{commentId}" }, ex);
                return(ResultsItem.Error($"Unable to submit your vote. {ex.Message}"));
            }
        }
예제 #24
0
        public ActionResult UpdatePortfolio(int portfolioId)
        {
            Portfolio portfolio = CurrentUser.Portfolios.FirstOrDefault(x => x.PortfolioId == portfolioId);

            if (portfolio == null)
            {
                return(Json(ResultsItem.Error("Unable to find the correct portfolio associated with logged in user.")));
            }

            PortfolioVM vm = new PortfolioVM {
                Portfolio = portfolio, IsCreateMode = false
            };

            return(PartialView("Crud/_ManagePortfolio", vm));
        }
예제 #25
0
        public void CreateUserTest()
        {
            ResultsItem deleteResult = AuthorizationLogic.DeletePegaUser("Test1234").Result;

            PegaUser user = new PegaUser
            {
                Username = "******",
                Password = "******",
                Email    = "*****@*****.**",
                IsSubscribeNewsLetter = true
            };
            ResultsPair <PegaUser> result = AuthorizationLogic.CreateNewUser(user).Result;

            Assert.IsTrue(result.Result.ResultType == Types.ResultsType.Successful);
        }
예제 #26
0
        public async Task <JsonResult> ImportEtherAddress(ExchangeApiInfo apiInfo)
        {
            var resultsPair = await FetchAPILogic.ApiImport_EtherAddress(await GetAllCoinsMarketDetailsAPI(), apiInfo.ApiPublic, apiInfo.PortfolioID, CurrentUser);

            if (!resultsPair.Result.IsSuccess)
            {
                return(Json(resultsPair.Result));
            }

            await CryptoLogic.DeleteAllUserCoinByExchangeAsync(apiInfo.PortfolioID, Types.Exchanges.EtherAddressLookup, CurrentUser);

            ResultsItem insertResult = await CryptoLogic.InsertCoinsToUserPortfolioAsync(resultsPair.Value, CurrentUser, apiInfo.PortfolioID);

            return(Json(insertResult));
        }
예제 #27
0
        /// <summary>
        /// Returns the API result from Pegasun API
        /// </summary>
        /// <param name="response">the HttpResponseMessage</param>
        /// <param name="successMessage">You can send a custom success message or leave it empty. If empty, will use APIResult's default message.</param>
        public static ResultsItem GetSimpleHttpResponseResult(HttpResponseMessage response, string successMessage)
        {
            if (response.IsSuccessStatusCode)
            {
                string      jsonString = response.Content.ReadAsStringAsync().Result;
                ResultsItem apiResult  = NetJSON.NetJSON.Deserialize <PegasunAPIResult>(jsonString).ConvertToResultsItem();
                if (apiResult.ResultType == ResultsType.Successful)
                {
                    return(ResultsItem.Success(string.IsNullOrEmpty(successMessage) ? apiResult.Message : successMessage));
                }

                return(apiResult); // Error
            }

            return(ResultsItem.Error(Lang.ServerConnectionError));
        }
예제 #28
0
        private static ResultsItem IsValidDBRequest(PegaUser user, int id, bool validateAPI = false, bool validatePortfolio = false, bool validateDemoUser = true)
        {
            if (validateDemoUser && user.Username.ToUpperInvariant() == "DEMOUSER")
            {
                return(ResultsItem.Error("DemoUser is not allowed to perform this action. Please login or create an account for free."));
            }
            if (validatePortfolio && !user.HasPortfolio(id))
            {
                return(ResultsItem.Error(Lang.PortfolioNotFound));
            }
            if (validateAPI && !user.ExchangeApiList.Any(x => x.Id == id))
            {
                return(ResultsItem.Error(Lang.ApiDeleteNotFound));
            }

            return(ResultsItem.Success(string.Empty));
        }
예제 #29
0
        public JsonResult SubmitContactUs(ContactUsVM vm)
        {
            if (ModelState.IsValid)
            {
                if (!Utilities.IsValidEmailAddress(vm.Email))
                {
                    return(Json(ResultsItem.Error("Please enter a valid email address.")));
                }

                // Send the email and grab the result
                bool mailSendSuccess = Utilities.SendEmailUsingSyneiGmail(vm.Email, vm.Name, vm.Subject, $"{vm.Name}, {vm.Email} | {vm.Message}");
                return(mailSendSuccess ? Json(ResultsItem.Success("Your email has been successfully sent. We'll get back to you as soon as possible. Thanks!"))
                                       : Json(ResultsItem.Error("Sending has failed. Please email us manually at [email protected].")));
            }

            return(Json(ResultsItem.Error(ModelState.GetAllErrorsString())));
        }
예제 #30
0
        // Warn, this will delete previous imported Exchange (BitTrex, Kraken, etc) trades
        public async Task <IActionResult> PostCSVTradeHistoryFile(IFormFile file, Types.Exchanges exchange, int portfolioId)
        {
            if (file == null || file.Length > 100000 ||
                (!file.FileName.EndsWith(".csv", StringComparison.OrdinalIgnoreCase) && !file.FileName.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase)))
            {
                return(Json(ResultsItem.Error("Please select a proper .csv/.xlsx file that is less than 100kb.")));
            }

            List <Core.Data.ServiceModels.ImportedCoin> importedCoins = new List <Core.Data.ServiceModels.ImportedCoin>();

            using (var stream = file.OpenReadStream())
            {
                importedCoins = FetchAPILogic.ImportCSV_Coins(exchange, stream);
            }

            if (importedCoins.IsNullOrEmpty())
            {
                return(Json(ResultsItem.Error(Lang.ImportFailedCSV)));
            }

            int maxAllowedImport = SubscriptionLogic.GetMaxAllowedTradesImportPerUser(CurrentUser.PTUserInfo.SubscriptionLevel);

            if (importedCoins.Count > maxAllowedImport)
            {
                return(Json(ResultsItem.Error(string.Format(Lang.CSVMaxImportAllowed, maxAllowedImport))));
            }

            List <CryptoCoin> fetchedCoins = FetchAPILogic.FormatCoinsAndGenerateTotalPricePaid(importedCoins, await GetAllHistoricCoinPrices());

            if (fetchedCoins.Count > 0)
            {
                fetchedCoins = CryptoLogic.FormatCoinsAndBoughtSoldLogicUpdate(fetchedCoins);

                await CryptoLogic.DeleteAllUserCoinByExchangeAsync(portfolioId, exchange, CurrentUser);

                ResultsItem insertResults = await CryptoLogic.InsertCoinsToUserPortfolioAsync(fetchedCoins, CurrentUser, portfolioId);

                if (insertResults.IsSuccess)
                {
                    return(Json(ResultsItem.Success("Successfully imported coins to your portfolio.")));
                }
            }

            return(Json(ResultsItem.Error("An error occured when trying to import trades. Are you sure the import .csv file has correct format?")));
        }