Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using BinOp.BusinessLogic.Operations;
- using log4net;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using BinOp.Core;
- using BinOp.BusinessLogic.Caching;
- using BinOp.Site;
- using BinOp.DataAccess.Enums;
- using BinOp.SharedBusinessLogic.Helpers;
- using System.Configuration;
- using System.Data;
- using System.Threading;
- using System.Web.Security;
- using System.Web;
- using BinOp.Web;
- using BinOp.BusinessLogic.Globalization;
- using System.Globalization;
- using System.Collections.Specialized;
- using BinOp.BusinessLogic.Web.Commands;
- using BinOp.BusinessLogic.Web;
- using BinOp.SharedBusinessLogic.Enums;
- using System.Text.RegularExpressions;
- using BinOp.SharedBusinessLogic.Objects;
- using BinOp.BusinessLogic.Operations.BackOffice;
- using BinOp.BusinessLogic.Web.Mail;
- using BinOp.SharedBusinessLogic.Constants;
- namespace BinOp.SharedBusinessLogic.WebAPI
- {
- public class WebApi
- {
- #region Constants
- #endregion Constants
- private UserHelper UserHelper { get; set; }
- private InvestmentHelper InvestmentHelper { get; set; }
- private CommonHelper CommonHelper { get; set; }
- private CrmHelper CrmHelper { get; set; }
- public WebApi()
- {
- this.UserHelper = new UserHelper();
- this.InvestmentHelper = new InvestmentHelper();
- this.CommonHelper = new CommonHelper();
- this.CrmHelper = new CrmHelper();
- }
- private ILog logger = LogManager.GetLogger(typeof(WebApi));
- public PlatformUnixTime PlatformUnixTime()
- {
- long platformUnixTime = (long)((DateTime.Now.GetBinOpsTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
- return new PlatformUnixTime(platformUnixTime);
- }
- public string ReloadTexts()
- {
- SiteTextsCache.Instance.InitiateDataTable();
- return "SUCCESS";
- }
- public OperationResult CreateUser(string firstName, string lastName, string email, string password, int? partnerID = null)
- {
- OperationResult result = this.UserHelper.OpenAccount(
- firstName, lastName,
- null, String.Empty, 1, String.Empty, String.Empty, String.Empty,
- email, password,
- String.Empty, 0, false, partnerID, null,
- false, null, null, null);
- return result;
- }
- public OperationResult Login(string username, string password)
- {
- bool EmailExists = ((bool)UsersOperations.CheckIfEmailNameExists(username).ResultValue);
- if (!EmailExists)
- {
- return new OperationResult(false, "username does not exist", null);
- }
- if (!this.UserHelper.LoginUser(username, password).ProcessedSuccessful)
- {
- return new OperationResult(false, "wrong password", null);
- }
- return OperationResult.GenericSuccess;
- }
- public OperationResult GetBalance(int userID)
- {
- try
- {
- if (userID > 0)
- {
- return UsersOperations.ReloadBalance(userID);
- }
- return new OperationResult(false, MessageConstants.INVALID_USERID_TEXT, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult ChangePassword(string oldPassword, string newPassword, int userID)
- {
- try
- {
- if (userID > 0)
- {
- return UsersOperations.ChangePassword(userID, oldPassword, newPassword);
- }
- return new OperationResult(false, MessageConstants.INVALID_USERID_TEXT, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult UpdateUser(string firstName, string lastName, string email, int userID)
- {
- try
- {
- if (userID > 0)
- {
- return UsersOperations.SaveUserDetails(userID, email, firstName, lastName, String.Empty);
- }
- return new OperationResult(false, MessageConstants.INVALID_USERID_TEXT, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult Deposit(decimal amount, int userID)
- {
- try
- {
- if (userID > 0)
- {
- OperationResult res = PaymentOperations.StartPayment(userID, amount);
- int transactionId = Convert.ToInt32(res.ResultValue);
- if (transactionId > 0) // success
- {
- return PaymentOperations.PaymentPassed(transactionId);
- }
- else // failure
- {
- return PaymentOperations.SetFailedState(transactionId);
- }
- }
- return new OperationResult(false, string.Empty, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult Credit(decimal amount, int transactionType, int transactionSubType, int userID)
- {
- try
- {
- if (userID > 0)
- {
- return AccountsOperations.Credit(
- userID,
- amount,
- (TransactionTypes)transactionType,
- (TransactionSubTypes)transactionSubType,
- string.Empty, string.Empty, string.Empty, 1);
- }
- return new OperationResult(false, MessageConstants.INVALID_USERID_TEXT, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult Withdraw(decimal amount, int status, int userID)
- {
- try
- {
- if (userID > 0)
- {
- return AccountsOperations.Withdraw(userID, amount, status);
- }
- return new OperationResult(false, MessageConstants.INVALID_USERID_TEXT, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetGeneralTradeInfo(string email)
- {
- OperationResult result = this.InvestmentHelper.GetGeneralTradeInfoByEmail(email);
- return result;
- }
- public OperationResult GetInvestments(string email, string from, string to, bool isClosed, int partnerID = 0, int? assetID = null)
- {
- DateTime dateFrom;
- DateTime? nulableDateFrom = null;
- if (DateTime.TryParse(from, out dateFrom))
- {
- nulableDateFrom = dateFrom;
- }
- DateTime dateTo;
- DateTime? nulableDateTo = null;
- if (DateTime.TryParse(to, out dateTo))
- {
- nulableDateTo = dateTo;
- }
- OperationResult result = this.InvestmentHelper.GetInvestmentsByEmail(email, nulableDateFrom, nulableDateTo, isClosed, assetID, partnerID: partnerID);
- return result;
- }
- public OperationResult GetTradeVolume(string email, DateTime? from, DateTime? to)
- {
- OperationResult result = this.InvestmentHelper.GetTradeVolumeByEmail(email, from, to);
- return result;
- }
- public OperationResult GetInvestmentsByExternalParameter(string externalParameter, string email, string from, string to, bool isClosed, int? assetID = null, int crmUserID = 0)
- {
- DateTime dateFrom;
- DateTime? nulableDateFrom = null;
- if (DateTime.TryParse(from, out dateFrom))
- {
- nulableDateFrom = dateFrom;
- }
- DateTime dateTo;
- DateTime? nulableDateTo = null;
- if (DateTime.TryParse(to, out dateTo))
- {
- nulableDateTo = dateTo;
- }
- string externalParametersAsString = ConfigurationManager.AppSettings["ExternalParameters"];
- if (string.IsNullOrEmpty(externalParameter))
- {
- return new OperationResult(false, "externalParameter is required.", null);
- }
- if (!string.IsNullOrEmpty(externalParametersAsString))
- {
- OperationResult result = this.InvestmentHelper.GetInvestmentsByEmail(email, nulableDateFrom, nulableDateTo, isClosed, assetID, externalParameter, crmUserID);
- return result;
- }
- return new OperationResult(false, "Configuration is missing.", null);
- }
- public OperationResult GetAccountDetails(int partnerID = 0, string email = null)
- {
- try
- {
- OperationResult userResult = UsersOperations.LoadUserDetailsByEmail(email, partnerID);
- if (userResult.ProcessedSuccessful)
- {
- DataTable dtUsers = userResult.ResultValue as DataTable;
- if (dtUsers.Rows.Count > 0)
- {
- DataTable userTable = new DataTable();
- userTable.Columns.Add("ID", typeof(int));
- foreach (DataRow drUser in dtUsers.Rows)
- {
- DataRow newDataRow = userTable.NewRow();
- newDataRow["ID"] = (int)drUser[UserConstants.COLUMN_USER_ID];
- userTable.Rows.Add(newDataRow);
- }
- OperationResult result = UsersOperations.LoadUserDetails(0, userTable);
- return result;
- }
- else
- {
- return new OperationResult(false, MessageConstants.INVALID_USERNAME_TEXT, null);
- }
- }
- else
- {
- return userResult;
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult UpdateAccountDetails(string email, string firstName, string lastName, string phone, bool joinCommunity, string publicNickname, string countryCode = null)
- {
- try
- {
- OperationResult userResult = UsersOperations.LoadUserDetailsByEmail(email);
- if (userResult.ProcessedSuccessful)
- {
- DataTable dtUsers = userResult.ResultValue as DataTable;
- if (dtUsers.Rows.Count > 0)
- {
- DataRow drUser = dtUsers.Rows[0];
- OperationResult result = UsersOperations.SaveUserDetails((int)drUser[UserConstants.COLUMN_USER_ID], email, firstName, lastName, phone, null, countryCode);
- UsersOperations.SetSocialStatus((int)drUser[UserConstants.COLUMN_USER_ID], joinCommunity);
- UsersOperations.SetSocialInfo((int)drUser[UserConstants.COLUMN_USER_ID], publicNickname, string.Empty);
- if ((int)result.ResultValue == 0)
- {
- return new OperationResult(true, SiteTextsCache.Instance.GetValue("DetailsSaved", Thread.CurrentThread.CurrentCulture.ThreeLetterISOLanguageName), null);
- }
- else
- {
- return new OperationResult(true, SiteTextsCache.Instance.GetValue("EnterUserExists", Thread.CurrentThread.CurrentCulture.ThreeLetterISOLanguageName), null);
- }
- }
- return new OperationResult(false, "No user has been found.", null);
- }
- else
- {
- return userResult;
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetAccountOperations(string email, string from, string to, int accountOperationType, int partnerID = 0)
- {
- try
- {
- OperationResult userResult = UsersOperations.LoadUserDetailsByEmail(email, partnerID);
- if (userResult.ProcessedSuccessful)
- {
- DataTable dtUsers = userResult.ResultValue as DataTable;
- if (dtUsers.Rows.Count > 0)
- {
- DataRow drUser = dtUsers.Rows[0];
- DateTime dateFrom;
- DateTime? nulableDateFrom = null;
- if (DateTime.TryParse(from, out dateFrom))
- {
- nulableDateFrom = dateFrom;
- }
- DateTime dateTo;
- DateTime? nulableDateTo = null;
- if (DateTime.TryParse(to, out dateTo))
- {
- nulableDateTo = dateTo;
- }
- if (accountOperationType == 0 || accountOperationType < -1)
- {
- accountOperationType = -1;
- }
- OperationResult result = UsersOperations.LoadAccountOperations((int)drUser[UserConstants.COLUMN_USER_ID], (AccountOperationTypes)accountOperationType, nulableDateFrom, nulableDateTo);
- return result;
- }
- return new OperationResult(false, "No user has been found.", null);
- }
- else
- {
- return userResult;
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetAccountLimitOrders(string email, string from, string to, int assetID, int groupID, int pageNum, int count)
- {
- try
- {
- OperationResult userResult = UsersOperations.LoadUserDetailsByEmail(email);
- if (userResult.ProcessedSuccessful)
- {
- DataTable dtUsers = userResult.ResultValue as DataTable;
- if (dtUsers.Rows.Count > 0)
- {
- DataRow drUser = dtUsers.Rows[0];
- DateTime dateFrom;
- DateTime? nulableDateFrom = null;
- if (DateTime.TryParse(from, out dateFrom))
- {
- nulableDateFrom = dateFrom;
- }
- DateTime dateTo;
- DateTime? nulableDateTo = null;
- if (DateTime.TryParse(to, out dateTo))
- {
- nulableDateTo = dateTo;
- }
- if (assetID == 0 || assetID < -1)
- {
- assetID = -1;
- }
- if (groupID == 0 || groupID < -1)
- {
- groupID = -1;
- }
- if (pageNum < 1)
- {
- pageNum = 1;
- }
- if (count < 1)
- {
- count = 25;
- }
- DataSet data = BackOfficeOperations.SearchLimitOrders(pageNum, count, nulableDateFrom, nulableDateTo, (int)drUser[UserConstants.COLUMN_USER_ID], -1, -1, -1, assetID, groupID, -1, 0).ResultValue as DataSet;
- int total = Convert.ToInt32(data.Tables[0].Rows[0][0]);
- DataTable table = data.Tables[1];
- foreach (DataRow row in table.Rows)
- {
- row["AssetName"] = GetAssetName(row);
- }
- OperationResult result = new OperationResult(true, "success", table);
- return result;
- }
- return new OperationResult(false, "No user has been found.", null);
- }
- else
- {
- return userResult;
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult OpenAccountWithCredit(string firstName, string lastName, string email, string phone, decimal bonusAmount, string password = null,
- int? partnerID = null, string affID = null, string dateOfBirth = null, string language = null, string id = null, string session = null, bool isAmerican = false, bool isDemo = false, bool isDemoLogin = false, string countryCode = null)
- {
- bool EmailExists = ((bool)UsersOperations.CheckIfEmailNameExists(email).ResultValue);
- if (EmailExists)
- {
- return new OperationResult(false, MessageConstants.INVALID_USERNAME_DOES_NOT_EXISTS, null);
- }
- DateTime date = new DateTime(1996, 01, 01);
- if (dateOfBirth != null)
- {
- DateTime.TryParse(dateOfBirth, out date);
- }
- if (string.IsNullOrEmpty(countryCode) || countryCode.Length != 2)
- {
- countryCode = null;
- }
- if (password == null)
- {
- var autoGeneratedPasswordLength = int.Parse(ConfigurationManager.AppSettings["AutoGeneratedPasswordLength"] ?? "8");
- var autoGeneratedPasswordNonAlphaNumericLength = int.Parse(ConfigurationManager.AppSettings["AutoGeneratedPasswordNonAlphaNumericLength"] ?? "3");
- password = Membership.GeneratePassword(autoGeneratedPasswordLength, autoGeneratedPasswordNonAlphaNumericLength);
- }
- OperationResult result = this.UserHelper.OpenAccount(
- firstName, lastName,
- null, String.Empty, 1, phone, String.Empty, String.Empty,
- email, password,
- countryCode, 0, isDemo, partnerID, null,
- false, null, null, null, true, isAmerican: isAmerican, isDemoLogin: isDemoLogin);
- return OpenAccountAddtionalOperations(result, firstName, lastName, email, phone, bonusAmount, password, language, true, id, session);
- }
- public OperationResult GetResolveCountryCode()
- {
- string countryCode = WebUtils.ResolveUserCountryCode(HttpContext.Current);
- OperationResult result = new OperationResult(true, string.Empty, countryCode);
- if (!string.IsNullOrEmpty(countryCode))
- {
- BinOpCallingCodeResolver resolver = new BinOpCallingCodeResolver();
- var callingCode = resolver.ResolveCallingCode(countryCode);
- result.ResultValue = result.ResultValue.ToString() + ',' + callingCode;
- }
- return result;
- }
- public OperationResult HasUserDeposited(int userID)
- {
- try
- {
- if (userID > 0)
- {
- return UsersOperations.HasUserDeposited(userID);
- }
- return new OperationResult(false, MessageConstants.INVALID_USERID_TEXT, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetRiskGroups()
- {
- try
- {
- OperationResult result = RiskGroupsOperations.GetAll();
- return result;
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetUserRiskGroup(string email)
- {
- try
- {
- OperationResult result = RiskGroupsOperations.GetByEmail(email);
- return result;
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult SetUserRiskgroup(string email, int riskGroupID)
- {
- try
- {
- OperationResult result = RiskGroupsOperations.SetRiskGroupToUserByEmail(email, riskGroupID);
- int rowsCount = 0;
- if (int.TryParse(result.ResultValue.ToString(), out rowsCount))
- {
- if (rowsCount > 0)
- {
- return new OperationResult(true, "Successfully updated", null);
- }
- }
- return new OperationResult(false, "No records found", null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult Withdraw(string username, decimal amount)
- {
- try
- {
- OperationResult or = UsersOperations.LoadUserDetailsByEmail(username);
- if (or.ProcessedSuccessful)
- {
- DataTable dtUsers = or.ResultValue as DataTable;
- if (dtUsers.Rows.Count > 0)
- {
- DataRow drUser = dtUsers.Rows[0];
- return AccountsOperations.Withdraw((int)drUser[UserConstants.COLUMN_USER_ID], amount);
- }
- else
- {
- return new OperationResult(false, MessageConstants.INVALID_USERNAME_TEXT, null);
- }
- }
- else
- {
- return or;
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetLoggedInUsers()
- {
- try
- {
- OperationResult result = this.UserHelper.GetAllOnlineUsers();
- return result;
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public string GetAssetsList(int userID , int userLevelID)
- {
- //int countMostPopularAssets = (int)AllCache.Get<object>("CountMostPopularAssets");
- int countMostPopularAssets = 2;
- // get assets and most popular tables
- DataTable assetsDataTable = new DataTable();
- if (HttpContext.Current.User.Identity.IsAuthenticated && userID > 0)
- {
- assetsDataTable = AssetsOperations.LoadAllAssets(UserId: userID).ResultValue as DataTable;
- }
- else
- {
- assetsDataTable = AssetsOperations.LoadAllAssets().ResultValue as DataTable;
- }
- DataTable mostPopularAssets = BinOpsOperations.LoadMostPopularAssets(countMostPopularAssets).ResultValue as DataTable;
- //assetsDataTable.Select()
- // create hash of all popular assetIDs
- //HashSet<string> mostPopularAssetIDs = new HashSet<string>();
- //foreach (DataRow mpAssetRow in mostPopularAssets.Rows)
- // mostPopularAssetIDs.Add(mpAssetRow[COLUMN_ASSET_ID].ToString());
- Dictionary<string, int> mostPopularAssetIDs = new Dictionary<string, int>();
- for (int i = 0; i < mostPopularAssets.Rows.Count; ++i)
- mostPopularAssetIDs.Add(mostPopularAssets.Rows[i][InvestmentConstants.COLUMN_ASSET_ID].ToString(), i + 1);
- // start building the response string
- StringBuilder sb = new StringBuilder();
- sb.Append("[");
- DateTime currentTime = Shared.GetBinOpsTime(DateTime.Now);
- // for each row create a javascript array of objects, each object is an associative array {key:val} with data pertaining to the specific option
- foreach (DataRow assetRow in assetsDataTable.Rows)
- {
- if (assetRow[UserConstants.COLUMN_MIN_USER_LEVEL_ID] != DBNull.Value && userID > 0)
- {
- int minUserLevelId = Convert.ToInt32(assetRow[UserConstants.COLUMN_MIN_USER_LEVEL_ID]);
- if (minUserLevelId > userLevelID & userLevelID > 0)
- {
- continue;
- }
- }
- string assetID = assetRow[InvestmentConstants.COLUMN_ASSET_ID].ToString();
- string groupID = assetRow[InvestmentConstants.COLUMN_GROUP_ID].ToString();
- string marketID = assetRow[InvestmentConstants.COLUMN_MARKET_ID].ToString();
- string assetName = GetAssetName(assetRow);
- string floatingPoints = assetRow[InvestmentConstants.COLUMN_ASSET_FLOATING_POINTS].ToString();
- int spread = 0;
- if (!String.IsNullOrEmpty(assetRow[InvestmentConstants.COLUMN_ASSET_SPREAD].ToString()))
- spread = Convert.ToInt32(assetRow[InvestmentConstants.COLUMN_ASSET_SPREAD]);
- int isMostPopular = mostPopularAssetIDs.ContainsKey(assetID) ? mostPopularAssetIDs[assetID] : 0;
- DateTime startWorkingTime = Convert.ToDateTime(assetRow[InvestmentConstants.COLUMN_START_WORKING_TIME]);
- startWorkingTime = currentTime.Date.AddHours(startWorkingTime.Hour).AddMinutes(startWorkingTime.Minute);
- if (startWorkingTime.Hour < currentTime.Hour)
- {
- startWorkingTime = startWorkingTime.AddDays(1);
- }
- DateTime closeEodTime = Convert.ToDateTime(assetRow[InvestmentConstants.COLUMN_CLOSE_EOD_TIME]);
- DateTime eodTime = Convert.ToDateTime(assetRow[InvestmentConstants.COLUMN_EOD_TIME]);
- int profitLowPercent = Convert.ToInt32(assetRow[InvestmentConstants.COLUMN_PROFIT_LOW_PERCENT]);
- string isFavourite = assetRow[InvestmentConstants.COLUMN_IS_FAVOURITE].ToString();
- string closeDay = ConfigurationManager.AppSettings["SetMarketCloseDayOfTheWeek"];
- string closeTime = ConfigurationManager.AppSettings["SetMarketCloseTime"];
- string closeIgnor = ConfigurationManager.AppSettings["SetMarketCloseIgnor"];
- bool ignorCloseDate = false;
- bool.TryParse(closeIgnor, out ignorCloseDate);
- // ignor or not any markets close settings from the web.config
- if (!ignorCloseDate)
- {
- // gets and sets day and time from the web.config
- DateTime theTime = DateTime.Now.GetBinOpsTime();
- if (!string.IsNullOrEmpty(closeDay) && !string.IsNullOrEmpty(closeTime))
- {
- int closeDayNumber = 0;
- if (int.TryParse(closeDay, out closeDayNumber) && closeDayNumber == (int)theTime.DayOfWeek)
- {
- if (DateTime.TryParse(closeTime, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out closeEodTime))
- {
- eodTime = closeEodTime.AddMinutes(5);
- }
- }
- }
- else if (theTime.DayOfWeek == DayOfWeek.Friday) // default settings fro friday
- {
- closeEodTime = DateTime.Parse("1/1/2015 19:55:00", CultureInfo.InvariantCulture);
- eodTime = DateTime.Parse("1/1/2015 20:00:00", CultureInfo.InvariantCulture);
- }
- }
- string startWorkingTimeString = startWorkingTime.ToString(CommonConstants.ISO_FORMAT);
- string closeEodTimeString = closeEodTime.ToString(CommonConstants.ISO_FORMAT);
- string eodTimeString = eodTime.ToString(CommonConstants.ISO_FORMAT);
- string eodTimeFormattedString = eodTime.ToString("HH:mm (UTC)");
- sb.Append(string.Format("{{\"AID\":\"{0}\",\"GID\":\"{1}\",\"MID\":\"{2}\",\"AN\":\"{3}\",\"FP\":\"{4}\",\"MP\":\"{5}\",\"SP\":{6},\"SWT\":\"{7}\",\"CET\":\"{8}\",\"ET\":\"{9}\",\"ETF\":\"{10}\",\"PLP\":\"{11}\",\"IF\":\"{12}\"}}",
- assetID, groupID, marketID, assetName, floatingPoints, isMostPopular.ToString(), spread, startWorkingTimeString, closeEodTimeString, eodTimeString, eodTimeFormattedString, profitLowPercent, isFavourite));
- if (!assetsDataTable.Rows[assetsDataTable.Rows.Count - 1].Equals(assetRow))
- sb.Append(",");
- }
- // close the response string
- sb.Append("]");
- return sb.ToString();
- }
- public OperationResult GetAccountDetailsEx(string username, int partnerID = 0)
- {
- try
- {
- OperationResult or = BackOfficeOperations.LoadUserDetailsByIdentity(username, partnerID);
- if (or.ProcessedSuccessful)
- {
- return or;
- }
- else
- {
- return new OperationResult(false, MessageConstants.INVALID_USERNAME_TEXT, null);
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult PlaceOrder(string email, string gameType, int assetID, double amount, bool isCall, int percent, bool isVirtual,
- int dynamicTypeSlice, string expirationDate, int returnPercent, int timeSliceType, string binOpLevel)
- {
- try
- {
- if (string.IsNullOrEmpty(email))
- {
- return new OperationResult(false, MessageConstants.EMAIL_NOT_PROVIDED_TEXT, null);
- }
- NameValueCollection parameters = new NameValueCollection();
- parameters.Add("Name", "PlaceLongTermOrder");
- parameters.Add("GT", gameType);
- parameters.Add("Bid", assetID.ToString());
- parameters.Add("Amnt", amount.ToString());
- if (isCall)
- {
- parameters.Add("Ot", "CALL");
- }
- else
- {
- parameters.Add("Ot", "PUT");
- }
- parameters.Add("GI", "true");
- parameters.Add("P", percent.ToString());
- parameters.Add("OIID", "-1");
- parameters.Add("V", isVirtual.ToString());
- parameters.Add("DTS", dynamicTypeSlice.ToString());
- parameters.Add("ED", expirationDate);
- parameters.Add("RP", returnPercent.ToString());
- parameters.Add("TS", timeSliceType.ToString());
- parameters.Add("Lvl", binOpLevel);
- parameters.Add("CmdType", "PlaceLongTermOrder");
- OperationResult result = UsersOperations.LoadUserDetailsByEmail(email);
- if (result.ProcessedSuccessful)
- {
- DataTable data = result.ResultValue as DataTable;
- if (data.Rows.Count > 0)
- {
- BaseCommand baseCommand = BaseCommand.CreateCommand(parameters);
- baseCommand.SettingsCollection = ConfigurationManager.AppSettings;
- baseCommand.UserDescriptorObject = this.CommonHelper.InitUserInfo(data);
- string returnCode = baseCommand.Execute();
- // 1 = No opened binops
- // 2 = Not enough money
- // 3 - Blocked
- // 0 = Ok
- string[] returnCodeString = returnCode.Split(',');
- string returnedValue = null;
- if (returnCodeString.Count() > 1)
- {
- returnCode = returnCodeString[0];
- returnedValue = returnCodeString[1];
- }
- int returnCodeAsInt = 0;
- if (int.TryParse(returnCode, out returnCodeAsInt) & (returnCodeAsInt == 0 || returnCodeAsInt == 100))
- {
- return new OperationResult(true, "code: " + returnCode, returnedValue);
- }
- else
- {
- return new OperationResult(false, "code: " + returnCode, null);
- }
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetDynamicTimeSliceTypes(int assetID)
- {
- OperationResult result = new OperationResult();
- try
- {
- result = BinOpsOperations.GetDynamicTimeSliceTypes(assetID);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- return result;
- }
- public OperationResult BuyMoreTime(int investmentID, int time, int userID)
- {
- try
- {
- NameValueCollection parameters = new NameValueCollection();
- parameters.Add("Name", "BuyMoreTime");
- parameters.Add("TPM", time.ToString());
- parameters.Add("IiD", investmentID.ToString());
- parameters.Add("CmdType", "BuyMoreTime");
- BaseCommand baseCommand = BaseCommand.CreateCommand(parameters);
- baseCommand.SettingsCollection = ConfigurationManager.AppSettings;
- baseCommand.UserDescriptorObject = new UserDescriptor(userID, null, null, null, null, 0, null, null, DateTime.Now, null,
- null, null, null, 3, null, false, false, DateTime.Now, false,
- null, 0, 0, null, null, null, null, false, null, false, 0, false);
- string returnCode = baseCommand.Execute();
- // 1 = No opened binops
- // 2 = Not enough money
- // 3 - Blocked
- // 0 = Ok
- int returnCodeAsInt = 0;
- if (int.TryParse(returnCode, out returnCodeAsInt) & (returnCodeAsInt == 0 || returnCodeAsInt == 100))
- {
- return new OperationResult(true, "code: " + returnCode, null);
- }
- else
- {
- return new OperationResult(false, "code: " + returnCode, null);
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult ChangePassword(int userID, string oldPassword, string newPassword)
- {
- try
- {
- return UsersOperations.ChangePassword(userID, oldPassword, newPassword);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetTopTraders()
- {
- try
- {
- return new OperationResult(true, String.Empty, this.UserHelper.GetTopTraders());
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult ForgottenPassword(string email, string languageCode = null)
- {
- try
- {
- if (string.IsNullOrEmpty(email))
- {
- return new OperationResult(false, MessageConstants.EMAIL_NOT_PROVIDED_TEXT, null);
- }
- OperationResult operationResult = UsersOperations.RecoverPassword(email);
- if (operationResult.ProcessedSuccessful)
- {
- string newPassword = (string)operationResult.ResultValue;
- OperationResult detailsResult = UsersOperations.LoadUserDetailsByEmail(email);
- if (!detailsResult.ProcessedSuccessful)
- {
- logger.Error(detailsResult.Message);
- throw new InvalidOperationException("Failed to get user details by email");
- }
- DataTable userDetailsTable = detailsResult.ResultValue as DataTable;
- string firstName = (string)userDetailsTable.Rows[0]["FirstName"];
- string lastName = (string)userDetailsTable.Rows[0]["LastName"];
- if (string.IsNullOrEmpty(languageCode))
- {
- languageCode = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
- }
- SendMailNotification(languageCode, email, firstName, lastName, null, MailTypes.PasswordRecovered, password: newPassword);
- string isSupportReceiveMail = System.Configuration.ConfigurationManager.AppSettings["SupportReceiveMail"] ?? "";
- if (isSupportReceiveMail == CommonConstants.TRUE_VALUE_AS_TEXT)
- {
- SendMailNotification(languageCode, System.Configuration.ConfigurationManager.AppSettings["AdminMail"], firstName, lastName, null, MailTypes.PasswordRecovered, password: newPassword);
- }
- return new OperationResult(true, newPassword, null);
- }
- else
- {
- return new OperationResult(false, "No account with email " + email + " has been found.", null);
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult SendSupportMail(string subject, string message, string email, string languageCode = null)
- {
- try
- {
- if (string.IsNullOrEmpty(email))
- {
- return new OperationResult(false, MessageConstants.EMAIL_NOT_PROVIDED_TEXT, null);
- }
- if (string.IsNullOrEmpty(message))
- {
- return new OperationResult(false, "The message can't be empty.", null);
- }
- OperationResult detailsResult = UsersOperations.LoadUserDetailsByEmail(email);
- if (!detailsResult.ProcessedSuccessful)
- {
- logger.Error(detailsResult.Message);
- throw new InvalidOperationException("Failed to get user details by email");
- }
- DataTable userDetailsTable = detailsResult.ResultValue as DataTable;
- string firstName = (string)userDetailsTable.Rows[0]["FirstName"];
- string lastName = (string)userDetailsTable.Rows[0]["LastName"];
- if (string.IsNullOrEmpty(languageCode))
- {
- languageCode = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
- }
- SendMailNotification(languageCode, System.Configuration.ConfigurationManager.AppSettings["AdminMail"], firstName, lastName, null, MailTypes.ContactUs,
- dataRow: userDetailsTable.Rows[0], subject: subject, message: message, fromAddress: email);
- return new OperationResult(true, null, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult TermsAndConditions(string languageCode = null, bool removeHtml = false)
- {
- try
- {
- StringBuilder sb = new StringBuilder();
- if (string.IsNullOrEmpty(languageCode))
- {
- languageCode = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
- }
- sb.Append(SiteTextsCache.Instance.GetValue("AgreementPreambleText", languageCode));
- sb.Append(SiteTextsCache.Instance.GetValue("AgreementDepositText", languageCode));
- sb.Append(SiteTextsCache.Instance.GetValue("AgreementPolicyText", languageCode));
- sb.Append(SiteTextsCache.Instance.GetValue("AgreementAdditionalText", languageCode));
- sb.Append(SiteTextsCache.Instance.GetValue("AgreementUnderageText", languageCode));
- string result = sb.ToString();
- if (removeHtml)
- {
- result = Regex.Replace(result, "<.*?>", string.Empty);
- }
- return new OperationResult(true, result, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult ReferAFriendInfo(int userID)
- {
- try
- {
- OperationResult result = UsersOperations.GetReferredUsersCount(userID);
- return result;
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult ReferAFriendSendNotification(int userID, string email, string languageCode, string firstName, string lastName)
- {
- try
- {
- if (string.IsNullOrEmpty(languageCode))
- {
- languageCode = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
- }
- SendMailNotification(languageCode, email, firstName, lastName, email, MailTypes.ReferAFriend, refNUmber: userID.ToString());
- return new OperationResult(true, null, null);
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- }
- public List<SocialTradeObject> SocialTrades(int userID, int pageNumber, int pageSize)
- {
- List<SocialTradeObject> resultData = new List<SocialTradeObject>();
- try
- {
- int assetId = -1;
- int groupId = -1;
- int? userId = null;
- int call_put = -1;
- int myUserId = -1;
- if (pageSize < 1)
- {
- pageSize = 1;
- }
- if (pageNumber < 1)
- {
- pageNumber = 1;
- }
- if (userID > 0)
- {
- userId = userID;
- }
- OperationResult virtualLimitOrdersResult = null;
- OperationResult virtualTradesResult = null;
- OperationResult result1 = BusinessLogic.Operations.BinOpsOperations.GetSocialLimitOrders(pageNumber, pageSize, myUserId, userId, call_put, assetId, groupId);
- OperationResult result2 = BusinessLogic.Operations.BinOpsOperations.GetSocialOrders(pageNumber, pageSize, myUserId, userId, call_put, assetId, groupId);
- OperationResult result3 = BusinessLogic.Operations.BinOpsOperations.GetSocialQuickOptionsOrders(pageNumber, pageSize, myUserId, userId, call_put, assetId, groupId);
- if (userId == null)
- {
- virtualLimitOrdersResult = BinOpsOperations.GetSocialVirtualLimitOrders(1, pageSize, null, call_put, assetId, groupId);
- virtualTradesResult = BinOpsOperations.GetSocialVirtualTrades(1, pageSize, null, call_put, assetId, groupId);
- }
- DataSet data;
- int total = 0;
- DataTable limitTable;
- DataTable OrderTable;
- if (result1.ProcessedSuccessful)
- {
- data = result1.ResultValue as DataSet;
- total += Convert.ToInt32(data.Tables[0].Rows[0][0]);
- limitTable = data.Tables[1];
- foreach (DataRow limitRow in limitTable.Rows)
- {
- foreach (DataColumn dataColumn in limitRow.Table.Columns)
- {
- resultData.Add(new SocialTradeObject() { Name = dataColumn.ColumnName, Value = limitRow[dataColumn].ToString(), IsLimitOrder = true });
- }
- }
- }
- if (result2.ProcessedSuccessful)
- {
- data = result2.ResultValue as DataSet;
- total += Convert.ToInt32(data.Tables[0].Rows[0][0]);
- OrderTable = data.Tables[1];
- foreach (DataRow orderRow in OrderTable.Rows)
- {
- foreach (DataColumn dataColumn in orderRow.Table.Columns)
- {
- resultData.Add(new SocialTradeObject() { Name = dataColumn.ColumnName, Value = orderRow[dataColumn].ToString() });
- }
- }
- }
- if (result3.ProcessedSuccessful)
- {
- data = result3.ResultValue as DataSet;
- total += Convert.ToInt32(data.Tables[0].Rows[0][0]);
- OrderTable = data.Tables[1];
- foreach (DataRow orderRow in OrderTable.Rows)
- {
- foreach (DataColumn dataColumn in orderRow.Table.Columns)
- {
- resultData.Add(new SocialTradeObject() { Name = dataColumn.ColumnName, Value = orderRow[dataColumn].ToString() });
- }
- }
- }
- if (virtualLimitOrdersResult != null && virtualLimitOrdersResult.ProcessedSuccessful)
- {
- var virtualLimitOrdersTable = virtualLimitOrdersResult.ResultValue as DataTable;
- foreach (DataRow virtualLimitOrderRow in virtualLimitOrdersTable.Rows)
- {
- foreach (DataColumn dataColumn in virtualLimitOrderRow.Table.Columns)
- {
- resultData.Add(new SocialTradeObject() { Name = dataColumn.ColumnName, Value = virtualLimitOrderRow[dataColumn].ToString(), IsLimitOrder = true, IsVirtual = true });
- }
- }
- }
- if (virtualTradesResult != null && virtualTradesResult.ProcessedSuccessful)
- {
- var virtualTradesTable = virtualTradesResult.ResultValue as DataTable;
- foreach (DataRow virtualTradeRow in virtualTradesTable.Rows)
- {
- foreach (DataColumn dataColumn in virtualTradeRow.Table.Columns)
- {
- resultData.Add(new SocialTradeObject() { Name = dataColumn.ColumnName, Value = virtualTradeRow[dataColumn].ToString(), IsVirtual = true });
- }
- }
- }
- }
- catch (Exception ex)
- {
- logger.Error(ex.Message, ex);
- }
- return resultData;
- }
- public OperationResult SuperCash(int userID, string email, int socialCount)
- {
- OperationResult returnedObject = new OperationResult();
- try
- {
- Dictionary<string, int> formData = new Dictionary<string, int> { };
- Dictionary<string, int> Assets = new Dictionary<string, int> { };
- DataTable resultTable = new DataTable();
- resultTable.Columns.Add(InvestmentConstants.COLUMN_ASSET_ID, typeof(String));
- resultTable.Columns.Add(InvestmentConstants.COLUMN_IS_CALL, typeof(String));
- resultTable.Columns.Add(InvestmentConstants.COLUMN_EXPIRATION_TIME, typeof(String));
- resultTable.Columns.Add(InvestmentConstants.COLUMN_SOCIAL_BOT, typeof(String));
- resultTable.Columns.Add(InvestmentConstants.COLUMN_PAYOUT, typeof(String));
- OperationResult result = BusinessLogic.Operations.AssetsOperations.LoadAllSocialAssets(ConfigurationManager.AppSettings[CommonConstants.SOURCE_SYSTEM_NAME].ToString(), userID);
- DataSet data;
- DataTable OrderTable;
- if (result.ProcessedSuccessful)
- {
- data = result.ResultValue as DataSet;
- OrderTable = data.Tables[0];
- if (OrderTable.Rows.Count == 0)
- {
- return new OperationResult(true, string.Empty, null);
- }
- else
- {
- int i = 0;
- foreach (DataRow Row in OrderTable.Rows)
- {
- if (i >= socialCount) break;
- string socialBotID = Row[InvestmentConstants.COLUMN_SOCIAL_BOT].ToString();
- int socialBotId = Convert.ToInt32(socialBotID);
- string assetID = Row[InvestmentConstants.COLUMN_ASSET_ID].ToString();
- string isCall = Row[InvestmentConstants.COLUMN_IS_CALL].ToString();
- if (isCall == "True")
- {
- isCall = "1";
- }
- else
- {
- isCall = "0";
- }
- string expirationTime = Row[InvestmentConstants.COLUMN_EXPIRATION_TIME].ToString();
- DateTime date = Convert.ToDateTime(expirationTime);
- string current_date = date.Year + "-" + date.Month + "-" + date.Day + "T";
- string current_time = date.TimeOfDay + "";
- expirationTime = current_date + current_time;
- string investValue = Row["InvestmentValue"].ToString();
- string sourceSystem = Row["SourceSystem"].ToString();
- string payout = Row[InvestmentConstants.COLUMN_PAYOUT].ToString();
- string isVirtualTrade = Row["IsVirtualTrade"].ToString();
- bool isVirtual = Convert.ToBoolean(isVirtualTrade);
- string backOfficeSiteName = null;
- int isBackOfficeSite = 0; //проверка дали записа в базата идва от backOffice и ако е от там се проверява времето което остава до изтичане, ако е по - малко от
- if (sourceSystem.Contains("_"))
- { // 20 минути автоматично към времето се добавят още 60 минути, това в случай че маркета е все още отворен
- string[] backOfficeSite = sourceSystem.Split(new string[] { "_" }, StringSplitOptions.None);
- backOfficeSiteName = backOfficeSite[1];
- if (backOfficeSiteName == ConfigurationManager.AppSettings[CommonConstants.SOURCE_SYSTEM_NAME].ToString())
- {
- isBackOfficeSite = 1;
- }
- else
- {
- isBackOfficeSite = 2;
- }
- }
- int val;
- if (formData.TryGetValue(sourceSystem + "_" + userID, out val))
- {
- formData[sourceSystem + "_" + userID] = val + 1;
- }
- else
- {
- formData.Add(sourceSystem + "_" + userID, 1);
- }
- int value;
- if (Assets.TryGetValue(assetID, out value))
- {
- Assets[assetID] = value + 1;
- }
- else
- {
- Assets.Add(assetID, 1);
- }
- int currentValue = formData[sourceSystem + "_" + userID];
- int currentValueAsset = Assets[assetID];
- bool isOneAsset = false;
- if (currentValueAsset < 2)
- {
- isOneAsset = true;
- }
- else
- {
- if (isVirtual)
- {
- isOneAsset = true;
- }
- else
- {
- isOneAsset = false;
- }
- }
- bool IsAvalibleAssetID = false;
- DataTable assetsDataTable = AssetsOperations.LoadAllAssets().ResultValue as DataTable;
- // iterate all open position rows in the table
- foreach (DataRow openPositionRow in assetsDataTable.Rows)
- {
- string assetId = openPositionRow[InvestmentConstants.COLUMN_ASSET_ID].ToString();
- if (assetId == assetID)
- IsAvalibleAssetID = true;
- }
- if (IsAvalibleAssetID)
- {
- if (((currentValue < 5 && isOneAsset) && (isBackOfficeSite == 0 || isBackOfficeSite == 1)) && isBackOfficeSite != 2)
- {
- DataRow newRow = resultTable.NewRow();
- newRow[InvestmentConstants.COLUMN_ASSET_ID] = assetID;
- newRow[InvestmentConstants.COLUMN_IS_CALL] = isCall;
- newRow[InvestmentConstants.COLUMN_EXPIRATION_TIME] = expirationTime;
- newRow[InvestmentConstants.COLUMN_SOCIAL_BOT] = socialBotID;
- newRow[InvestmentConstants.COLUMN_PAYOUT] = payout;
- resultTable.Rows.Add(newRow);
- ++i;
- }
- }
- }
- returnedObject = new OperationResult(true, null, resultTable);
- }
- }
- }
- catch (Exception ex)
- {
- return new OperationResult(false, ex.Message, null);
- }
- return returnedObject;
- }
- public OperationResult CopyTrade(string email, int binopID, double amount, bool isCall, int percent, bool isVirtual)
- {
- try
- {
- if (string.IsNullOrEmpty(email))
- {
- return new OperationResult(false, MessageConstants.EMAIL_NOT_PROVIDED_TEXT, null);
- }
- OperationResult investmentResult = BinOpsOperations.GetInvestmentsByBinOpID(binopID, isVirtual);
- if (investmentResult.ProcessedSuccessful)
- {
- DataTable dataTable = investmentResult.ResultValue as DataTable;
- if (dataTable != null && dataTable.Rows.Count > 0)
- {
- int originalInvestmentID = -1;
- string binopLevel = string.Empty;
- if (!isVirtual)
- {
- int investID = 0;
- int.TryParse(dataTable.Rows[0][InvestmentConstants.COLUMN_INVESTMENT_ID].ToString(), out investID);
- int.TryParse(dataTable.Rows[0][InvestmentConstants.COLUMN_ORIGINAL_INVESTMENT_ID].ToString(), out originalInvestmentID);
- int.TryParse(dataTable.Rows[0][InvestmentConstants.COLUMN_ORIGINAL_VIRTUAL_TRADE_ID].ToString(), out originalInvestmentID);
- if (originalInvestmentID < 1)
- {
- originalInvestmentID = investID;
- }
- binopLevel = dataTable.Rows[0]["BinOpLevel"].ToString();
- }
- else
- {
- int.TryParse(dataTable.Rows[0]["VirtualTradeID"].ToString(), out originalInvestmentID);
- binopLevel = dataTable.Rows[0]["BinOpLevel"].ToString();
- }
- NameValueCollection parameters = new NameValueCollection();
- parameters.Add("Name", "PlaceOrder");
- parameters.Add("GT", "2");
- parameters.Add("Bid", binopID.ToString());
- parameters.Add("Amnt", amount.ToString());
- if (isCall)
- {
- parameters.Add("Ot", "CALL");
- }
- else
- {
- parameters.Add("Ot", "PUT");
- }
- parameters.Add("P", percent.ToString());
- parameters.Add("OIID", originalInvestmentID.ToString());
- parameters.Add("V", isVirtual.ToString());
- parameters.Add("DTS", null);
- //parameters.Add("TS", timeSliceType.ToString());
- parameters.Add("Lvl", binopLevel);
- parameters.Add("CmdType", "PlaceOrder");
- OperationResult result = UsersOperations.LoadUserDetailsByEmail(email);
- if (result.ProcessedSuccessful)
- {
- DataTable data = result.ResultValue as DataTable;
- if (data.Rows.Count > 0)
- {
- BaseCommand baseCommand = BaseCommand.CreateCommand(parameters);
- baseCommand.SettingsCollection = ConfigurationManager.AppSettings;
- baseCommand.UserDescriptorObject = this.CommonHelper.InitUserInfo(data);
- string returnCode = baseCommand.Execute();
- // 1 = No opened binops
- // 2 = Not enough money
- // 3 - Blocked
- // 0 = Ok
- int returnCodeAsInt = 0;
- if (int.TryParse(returnCode, out returnCodeAsInt) & (returnCodeAsInt == 0 || returnCodeAsInt == 100))
- {
- return new OperationResult(true, "code: " + returnCode, null);
- }
- else
- {
- return new OperationResult(false, "code: " + returnCode, null);
- }
- }
- }
- return result;
- }
- }
- }
- catch (Exception ex)
- {
- logger.Error(ex.Message, ex);
- return new OperationResult(false, ex.Message, null);
- }
- return new OperationResult(false, null, null);
- }
- public OperationResult SuperCashTrade(string email, int socialBotID, double amount, bool openOnePosition)
- {
- try
- {
- if (string.IsNullOrEmpty(email))
- {
- return new OperationResult(false, MessageConstants.EMAIL_NOT_PROVIDED_TEXT, null);
- }
- NameValueCollection parameters = new NameValueCollection();
- parameters.Add("Name", "PlaceSocialBotOrder");
- parameters.Add(InvestmentConstants.COLUMN_SOCIAL_BOT, socialBotID.ToString());
- parameters.Add("amount", amount.ToString());
- parameters.Add("OpenOnePosition", amount.ToString());
- parameters.Add("CmdType", "PlaceSocialBotOrder");
- OperationResult result = UsersOperations.LoadUserDetailsByEmail(email);
- if (result.ProcessedSuccessful)
- {
- DataTable data = result.ResultValue as DataTable;
- if (data.Rows.Count > 0)
- {
- BaseCommand baseCommand = BaseCommand.CreateCommand(parameters);
- baseCommand.SettingsCollection = ConfigurationManager.AppSettings;
- baseCommand.UserDescriptorObject = this.CommonHelper.InitUserInfo(data);
- string returnCode = baseCommand.Execute();
- // 1 = No opened binops
- // 2 = Not enough money
- // 3 - Blocked
- // 0 = Ok
- int returnCodeAsInt = 0;
- if (int.TryParse(returnCode, out returnCodeAsInt) & (returnCodeAsInt == 0 || returnCodeAsInt == 100))
- {
- return new OperationResult(true, "code: " + returnCode, null);
- }
- else
- {
- return new OperationResult(false, "code: " + returnCode, null);
- }
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- logger.Error(ex.Message, ex);
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult CopyLimitTrade(string email, int limitID, double amount, bool isVirtual)
- {
- try
- {
- if (string.IsNullOrEmpty(email))
- {
- return new OperationResult(false, MessageConstants.EMAIL_NOT_PROVIDED_TEXT, null);
- }
- NameValueCollection parameters = new NameValueCollection();
- parameters.Add("Name", "CopyLimitOrder");
- parameters.Add("LID", limitID.ToString());
- parameters.Add("A", amount.ToString());
- parameters.Add("OIID", "-1");
- parameters.Add("V", isVirtual.ToString());
- parameters.Add("CmdType", "CopyLimitOrder");
- OperationResult result = UsersOperations.LoadUserDetailsByEmail(email);
- if (result.ProcessedSuccessful)
- {
- DataTable data = result.ResultValue as DataTable;
- if (data.Rows.Count > 0)
- {
- BaseCommand baseCommand = BaseCommand.CreateCommand(parameters);
- baseCommand.SettingsCollection = ConfigurationManager.AppSettings;
- baseCommand.UserDescriptorObject = this.CommonHelper.InitUserInfo(data);
- string returnCode = baseCommand.Execute();
- // 1 = No opened binops
- // 2 = Not enough money
- // 3 - Blocked
- // 0 = Ok
- int returnCodeAsInt = 0;
- if (int.TryParse(returnCode, out returnCodeAsInt) & (returnCodeAsInt == 0 || returnCodeAsInt == 100))
- {
- return new OperationResult(true, "code: " + returnCode, null);
- }
- else
- {
- return new OperationResult(false, "code: " + returnCode, null);
- }
- }
- }
- return result;
- }
- catch (Exception ex)
- {
- logger.Error(ex.Message, ex);
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult CreatePartner(string username, string password, string crmKey, bool isActive)
- {
- try
- {
- if (string.IsNullOrEmpty(username))
- {
- return new OperationResult(false, MessageConstants.USERNAME_NOT_PROVIDED_TEXT, null);
- }
- OperationResult ValidateUserNameResult = BackOfficeUsersOperations.GetByUsername(username);
- if (ValidateUserNameResult.ProcessedSuccessful)
- {
- logger.Info(MessageConstants.USERNAME_EXISTS_TEXT);
- return new OperationResult(false, MessageConstants.USERNAME_EXISTS_TEXT, null);
- }
- else
- {
- DataTable rolesTable = new DataTable();
- rolesTable.Columns.Add("ID", typeof(int));
- DataRow newDataRow = rolesTable.NewRow();
- newDataRow["ID"] = 6;
- rolesTable.Rows.Add(newDataRow);
- if (string.IsNullOrEmpty(password))
- {
- var autoGeneratedPasswordLength = int.Parse(ConfigurationManager.AppSettings["AutoGeneratedPasswordLength"] ?? "8");
- var autoGeneratedPasswordNonAlphaNumericLength = int.Parse(ConfigurationManager.AppSettings["AutoGeneratedPasswordNonAlphaNumericLength"] ?? "3");
- password = Membership.GeneratePassword(autoGeneratedPasswordLength, autoGeneratedPasswordNonAlphaNumericLength);
- }
- OperationResult result = BackOfficeUsersOperations.Create(username, password, rolesTable, isActive, crmKey);
- if (result.ProcessedSuccessful)
- {
- DataTable dataTable = result.ResultValue as DataTable;
- int partnerID = 0;
- int.TryParse(dataTable.Rows[0][0].ToString(), out partnerID);
- if (partnerID > 0)
- {
- return new OperationResult(true, string.Empty, partnerID);
- }
- }
- return OperationResult.GenericFailure;
- }
- }
- catch (Exception ex)
- {
- logger.Error(ex.Message, ex);
- return new OperationResult(false, ex.Message, null);
- }
- }
- public OperationResult GetUserByEmail(string email, int partnerID = 0)
- {
- OperationResult userData = this.UserHelper.GetUserByEmail(email, partnerID);
- return userData;
- }
- #region Partner Related Methods
- public OperationResult OpenAccount(string firstName, string lastName, string email, string phone, decimal bonusAmount = 0, int? partnerID = null, string password = null, string countryCode = null, string description = null)
- {
- string language = string.Empty;
- if (phone == null)
- {
- phone = string.Empty;
- }
- if (!string.IsNullOrEmpty(countryCode) && countryCode.Length == 2)
- {
- language = countryCode;
- }
- if (password == null)
- {
- var autoGeneratedPasswordLength = int.Parse(ConfigurationManager.AppSettings["AutoGeneratedPasswordLength"] ?? "8");
- var autoGeneratedPasswordNonAlphaNumericLength = int.Parse(ConfigurationManager.AppSettings["AutoGeneratedPasswordNonAlphaNumericLength"] ?? "3");
- password = Membership.GeneratePassword(autoGeneratedPasswordLength, autoGeneratedPasswordNonAlphaNumericLength);
- }
- bool isSocial = false;
- if (!string.IsNullOrEmpty(description))
- {
- isSocial = true;
- }
- OperationResult result = this.UserHelper.OpenAccount(
- firstName, lastName,
- null, String.Empty, 1, phone, String.Empty, String.Empty,
- email, password,
- language, 0, false, partnerID, null,
- isSocial, description, null, null);
- return OpenAccountAddtionalOperations(result, firstName, lastName, email, phone, bonusAmount, password, countryCode, false, partnerID: partnerID);
- }
- public OperationResult ListCountries()
- {
- OperationResult result = SystemOperations.LoadAllCountries();
- return result;
- }
- public OperationResult GetAdditionalParameterValue(string name)
- {
- OperationResult result = AdditionalDataToStoreOperations.Exists(name, this.CommonHelper.GetIpAddress(HttpContext.Current));
- return result;
- }
- public OperationResult ListAssets(int assetID = 0)
- {
- OperationResult result = new OperationResult();
- int countMostPopularAssets = 2;
- DataTable assetsDataTable = null;
- if (assetID > 0)
- {
- assetsDataTable = AssetsOperations.LoadAllAssetsWithUserLevel(assetID: assetID, loadFromDb: true).ResultValue as DataTable;
- }
- else
- {
- assetsDataTable = AssetsOperations.LoadAllAssets().ResultValue as DataTable;
- }
- DataTable mostPopularAssets = BinOpsOperations.LoadMostPopularAssets(countMostPopularAssets).ResultValue as DataTable;
- Dictionary<string, int> mostPopularAssetIDs = new Dictionary<string, int>();
- for (int i = 0; i < mostPopularAssets.Rows.Count; ++i)
- mostPopularAssetIDs.Add(mostPopularAssets.Rows[i][InvestmentConstants.COLUMN_ASSET_ID].ToString(), i + 1);
- // start building the response string
- StringBuilder sb = new StringBuilder();
- DateTime currentTime = Shared.GetBinOpsTime(DateTime.Now);
- // for each row create a javascript array of objects, each object is an associative array {key:val} with data pertaining to the specific option
- foreach (DataRow assetRow in assetsDataTable.Rows)
- {
- string currentAssetID = assetRow[InvestmentConstants.COLUMN_ASSET_ID].ToString();
- string groupID = assetRow[InvestmentConstants.COLUMN_GROUP_ID].ToString();
- string marketID = assetRow[InvestmentConstants.COLUMN_MARKET_ID].ToString();
- string assetName = GetAssetName(assetRow);
- string floatingPoints = assetRow[InvestmentConstants.COLUMN_ASSET_FLOATING_POINTS].ToString();
- int spread = 0;
- if (!String.IsNullOrEmpty(assetRow[InvestmentConstants.COLUMN_ASSET_SPREAD].ToString()))
- spread = Convert.ToInt32(assetRow[InvestmentConstants.COLUMN_ASSET_SPREAD]);
- int isMostPopular = mostPopularAssetIDs.ContainsKey(currentAssetID) ? mostPopularAssetIDs[currentAssetID] : 0;
- DateTime startWorkingTime = Convert.ToDateTime(assetRow[InvestmentConstants.COLUMN_START_WORKING_TIME]);
- startWorkingTime = currentTime.Date.AddHours(startWorkingTime.Hour).AddMinutes(startWorkingTime.Minute);
- if (startWorkingTime.Hour < currentTime.Hour)
- {
- startWorkingTime = startWorkingTime.AddDays(1);
- }
- DateTime closeEodTime = Convert.ToDateTime(assetRow[InvestmentConstants.COLUMN_CLOSE_EOD_TIME]);
- DateTime eodTime = Convert.ToDateTime(assetRow[InvestmentConstants.COLUMN_EOD_TIME]);
- int profitLowPercent = Convert.ToInt32(assetRow[InvestmentConstants.COLUMN_PROFIT_LOW_PERCENT]);
- string closeDay = ConfigurationManager.AppSettings["SetMarketCloseDayOfTheWeek"];
- string closeTime = ConfigurationManager.AppSettings["SetMarketCloseTime"];
- string closeIgnor = ConfigurationManager.AppSettings["SetMarketCloseIgnor"];
- bool ignorCloseDate = false;
- bool.TryParse(closeIgnor, out ignorCloseDate);
- // ignor or not any markets close settings from the web.config
- if (!ignorCloseDate)
- {
- // gets and sets day and time from the web.config
- DateTime theTime = DateTime.Now.GetBinOpsTime();
- if (!string.IsNullOrEmpty(closeDay) && !string.IsNullOrEmpty(closeTime))
- {
- int closeDayNumber = 0;
- if (int.TryParse(closeDay, out closeDayNumber) && closeDayNumber == (int)theTime.DayOfWeek)
- {
- if (DateTime.TryParse(closeTime, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out closeEodTime))
- {
- eodTime = closeEodTime.AddMinutes(5);
- }
- }
- }
- else if (theTime.DayOfWeek == DayOfWeek.Friday) // default settings fro friday
- {
- closeEodTime = DateTime.Parse("1/1/2015 19:55:00", CultureInfo.InvariantCulture);
- eodTime = DateTime.Parse("1/1/2015 20:00:00", CultureInfo.InvariantCulture);
- }
- }
- string startWorkingTimeString = startWorkingTime.ToString(CommonConstants.ISO_FORMAT);
- string closeEodTimeString = closeEodTime.ToString(CommonConstants.ISO_FORMAT);
- string eodTimeString = eodTime.ToString(CommonConstants.ISO_FORMAT);
- string eodTimeFormattedString = eodTime.ToString("HH:mm (UTC)");
- sb.Append(string.Format("{{\"AID\":\"{0}\",\"GID\":\"{1}\",\"MID\":\"{2}\",\"AN\":\"{3}\",\"FP\":\"{4}\",\"MP\":\"{5}\",\"SP\":{6},\"SWT\":\"{7}\",\"CET\":\"{8}\",\"ET\":\"{9}\",\"ETF\":\"{10}\",\"PLP\":\"{11}\"}}",
- currentAssetID, groupID, marketID, assetName, floatingPoints, isMostPopular.ToString(), spread, startWorkingTimeString, closeEodTimeString, eodTimeString, eodTimeFormattedString, profitLowPercent));
- if (!assetsDataTable.Rows[assetsDataTable.Rows.Count - 1].Equals(assetRow))
- sb.Append(",");
- }
- // close the response string
- if (!string.IsNullOrEmpty(sb.ToString()))
- {
- result.ResultValue = sb.ToString();
- result.ProcessedSuccessful = true;
- }
- return result;
- }
- public OperationResult CreateCrmLead(string firstName, string lastName, string email, string phoneCountryCode,
- string phoneAreaCode, string phoneNumber, string ip, string promoCode = null, int? affID = null, string description = null, string countryCode = null)
- {
- bool EmailExists = ((bool)UsersOperations.CheckIfEmailNameExists(email).ResultValue);
- if (EmailExists)
- {
- return new OperationResult(false, MessageConstants.INVALID_USERNAME_DOES_NOT_EXISTS, null);
- }
- if (string.IsNullOrEmpty(ip))
- {
- ip = this.CommonHelper.GetIpAddress(HttpContext.Current);
- }
- this.CrmHelper.CreateCrmLead(firstName, lastName, email, phoneCountryCode, phoneAreaCode, phoneNumber, ip, null, promoCode, affID, description: description, countryCode: countryCode);
- return new OperationResult(true, null, null);
- }
- #endregion Partner Related Methods
- #region Private Methods
- private void SendMailNotification(string languageCode, string toAddress, string firstName, string lastName, string username, MailTypes mailType, string password = null,
- DataRow dataRow = null, string subject = null, string message = null, string fromAddress = null, string refNUmber = null)
- {
- ThreadPool.QueueUserWorkItem((state) =>
- {
- try
- {
- switch (mailType)
- {
- case MailTypes.PasswordRecovered:
- SiteMailer.Instance.SendPasswordRecovered(languageCode, toAddress, firstName, lastName, password);
- break;
- case MailTypes.ContactUs:
- SiteMailer.Instance.SendContacUs(languageCode, toAddress, fromAddress, firstName, lastName, dataRow["EMail"].ToString(), message, subject);
- break;
- case MailTypes.ReferAFriend:
- SiteMailer.Instance.SendReferAFriend(languageCode, toAddress, firstName, lastName, refNUmber);
- break;
- default:
- SiteMailer.Instance.SendUserCreatedNotification(languageCode, toAddress, firstName, lastName, username, password);
- break;
- }
- }
- catch (Exception ex)
- {
- logger.Error("Failed sending mail after user creation.", ex);
- }
- });
- }
- private string GetAssetName(DataRow asset)
- {
- string assetKey = (string)asset[InvestmentConstants.COLUMN_RES_KEY];
- string assetName = (string)asset[InvestmentConstants.COLUMN_ASSET_NAME];
- string assetSiteTextsKey = "AssetName_" + assetKey;
- string assetSiteTextsValue = SiteTextsCache.Instance.GetValue(assetSiteTextsKey, Thread.CurrentThread.CurrentCulture.ThreeLetterISOLanguageName);
- // if no translation value default to Asset Name from DB
- if (assetSiteTextsValue == String.Format("[{0}]", assetSiteTextsKey))
- {
- assetSiteTextsValue = assetName;
- }
- return assetSiteTextsValue;
- }
- private OperationResult OpenAccountAddtionalOperations(OperationResult result, string firstName, string lastName, string email, string phone, decimal bonusAmount,
- string password = null, string countryCode = null, bool login = true, string session = null, string id = null, int? partnerID = null)
- {
- int createduserID = 0;
- if (result.ProcessedSuccessful)
- {
- int.TryParse(result.ResultValue.ToString(), out createduserID);
- if (login)
- {
- result = Login(email, password);
- }
- else
- {
- result.ProcessedSuccessful = true;
- }
- if (result.ProcessedSuccessful)
- {
- this.CrmHelper.CreateCrmAccount(createduserID, firstName, lastName, email, String.Empty, String.Empty, phone,
- HttpContext.Current.Request.UserHostAddress, "Account", affID: partnerID);
- var languageCode = countryCode ?? Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName;
- SendMailNotification(languageCode, email, firstName, lastName, email, MailTypes.UserCreated, password: password);
- string binOpLimitCall = ConfigurationManager.AppSettings["DefaultBinOpLimitCall"] ?? "";
- string binOpLimitPut = ConfigurationManager.AppSettings["DefaultBinOpLimitPut"] ?? "";
- if (!String.IsNullOrEmpty(binOpLimitCall) &&
- !String.IsNullOrEmpty(binOpLimitPut))
- {
- UsersOperations.CreateLimit(
- email,
- TimeSliceTypes.All, (PercentageTypes)(-1), -1, -1,
- -1,
- -1,
- -1,
- -1,
- Convert.ToInt32(binOpLimitCall),
- Convert.ToInt32(binOpLimitPut));
- }
- if (createduserID> 0)
- {
- if (login)
- {
- return new OperationResult(false, MessageConstants.INVALID_SESSION_TEXT, null);
- }
- else
- {
- OperationResult userResult = UsersOperations.LoadUserDetailsByEmail(email);
- DataTable dataTable = userResult.ResultValue as DataTable;
- }
- if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(session))
- {
- ExternalParametersOperations.Save(createduserID, "id", id);
- ExternalParametersOperations.Save(createduserID, "session", session);
- }
- string defaultUserBalanceAlert = ConfigurationManager.AppSettings["DefaultUserBalanceAlert"] ?? "";
- if (!String.IsNullOrEmpty(defaultUserBalanceAlert))
- {
- UsersOperations.SetUserBalanceAlert(createduserID, Convert.ToInt32(defaultUserBalanceAlert));
- }
- string defaultUserPnLAlert = ConfigurationManager.AppSettings["DefaultUserPnLAlert"] ?? "";
- if (!String.IsNullOrEmpty(defaultUserPnLAlert))
- {
- UsersOperations.SetUserPnLAlert(createduserID, Convert.ToInt32(defaultUserPnLAlert));
- }
- if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DefaultBonus"]) && bonusAmount == 0)
- {
- bonusAmount = decimal.Parse(ConfigurationManager.AppSettings["DefaultBonus"]);
- }
- if (bonusAmount > 0)
- {
- return Credit(bonusAmount, (int)TransactionTypes.Bonus, (int)TransactionSubTypes.NewAccount, createduserID);
- }
- else
- {
- return result;
- }
- }
- }
- }
- return result;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement