Exemple #1
0
        public long GetMaxId()
        {
            long id = 0;

            try
            {
                _objUnitsEntity = _dbContext.POS_UNI.OrderByDescending(x => x.UNIT_ID).FirstOrDefault();
                if (_objUnitsEntity.UNIT_ID.ToString() == null)
                {
                    id = 1;
                }
                else
                {
                    id = _objUnitsEntity.UNIT_ID + 1;
                }

                return(id);
            }
            catch (Exception ex)
            {
                ExceptionLogger.WriteExceptionInDB(ex, ExceptionLevel.DAL, ExceptionType.Error);
                throw new DALException(ex.Message.ToString());
            }
        }
        public async Task <T> PutAsyncWithoutReturnContent <T>(string url, object payload, bool useAuthToken = true)
        {
            try
            {
                HttpResponseMessage response = await RequestAsync(HttpMethod.Put, url, payload).ConfigureAwait(false);

                string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                HandleIfErrorResponse(response.StatusCode, content);
                if (typeof(T) == typeof(string))
                {
                    return(GetValue <T>(content));
                }
            }
            catch (HttpRequestException ex)
            {
                ExceptionLogger.LogException(ex);
                Debug.WriteLine("Error in POST Request :" + ex.Message);
                Crashes.TrackError(ex, new Dictionary <string, string> {
                    { "Class Name : ", GetType().Name }, { "Method Name : ", MethodBase.GetCurrentMethod().Name }
                });
            }
            return(default(T));
        }
Exemple #3
0
        public DataRow GetRow
            ()
        {
            DataRow row = null;

            try
            {
                DataSet dataSet = new DataSet();
                using (MySqlDataAdapter adapter = new MySqlDataAdapter(command))
                {
                    adapter.Fill(dataSet);
                }
                if ((dataSet.Tables.Count > 0) && (dataSet.Tables[0].Rows.Count == 1))
                {
                    row = dataSet.Tables[0].Rows[0];
                }
            }
            catch (Exception exception)
            {
                ExceptionLogger.LogQueryError(command.CommandText, exception);
            }

            return(row);
        }
        /// <summary>
        /// Handles the AssemblyResolve event of the CurrentDomain control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="ResolveEventArgs"/> instance containing the event data.</param>
        /// <returns>Assembly.</returns>
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            // parts of the code borrowed from; Thanks To (C): https://weblog.west-wind.com/posts/2016/dec/12/loading-net-assemblies-out-of-seperate-folders

            // ignore resources..
            if (args.Name.Contains(".resources"))
            {
                return(null);
            }

            // check for assemblies already loaded..
            Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == args.Name);

            if (assembly != null)
            {
                return(assembly);
            }

            // Try to load by filename - split out the filename of the full assembly name
            // and append the base path of the original assembly (ie. look in the same dir)
            string filename = args.Name.Split(',')[0] + ".dll".ToLower();

            filename = Path.Combine(
                Path.GetDirectoryName(FormSettings.Settings.EditorSpellCustomDictionaryDefinitionFile) ?? string.Empty,
                filename);

            try
            {
                return(Assembly.LoadFrom(filename));
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogError(ex);
                return(null);
            }
        }
        protected virtual IEnumerable <EntityType> GetAll(string GET_ALL_STORED_PROCEDURE_NAME)
        {
            IDataBaseCommandExecutor storedProcedure = TryGetStoredProcedure(GET_ALL_STORED_PROCEDURE_NAME, new List <SqlParameter> {
            });

            DataSet resultDataSet = null;

            try
            {
                resultDataSet = storedProcedure.Execute();
            }
            catch (Exception)
            {
                string EXCEPTION_MESSAGE = $"Ошибка выполнения хранимой процедуры для получения всех записей класса {typeof(EntityType).ToString()} из базы данных!";

                ExceptionLogger.LogError(EXCEPTION_MESSAGE);

                throw;
            }

            if (resultDataSet != null)
            {
                DataTableMapper          mapper           = TryGetDataTableMapper(resultDataSet.Tables[0]);
                IEnumerable <EntityType> resultCollection = mapper.CreateListFromTable <EntityType>();

                return(resultCollection);
            }
            else
            {
                string EXCEPTION_MESSAGE = $"Результат выполнения хранимой процедуры для получения всех записей класса {typeof(EntityType).ToString()} из базы данных вернул Null!";

                ExceptionLogger.LogError(EXCEPTION_MESSAGE);

                throw new Exception();
            }
        }
Exemple #6
0
        public int CreateUnits(POS_UNI UnitsModel)
        {
            int     rowAffected     = 0;
            POS_UNI _objUnitsEntity = new POS_UNI();

            try
            {
                _objUnitsEntity.UNIT          = UnitsModel.UNIT;
                _objUnitsEntity.ISACTIVE_FLAG = UnitsModel.ISACTIVE_FLAG;
                _objUnitsEntity.ISPOSTED_FLAG = false;
                _objUnitsEntity.CREATEDBY     = UnitsModel.CREATEDBY;
                _objUnitsEntity.CREATEDWHEN   = UnitsModel.CREATEDWHEN;

                _dbContext.POS_UNI.Add(_objUnitsEntity);
                rowAffected = _dbContext.SaveChanges();

                return(rowAffected);
            }
            catch (Exception ex)
            {
                ExceptionLogger.WriteExceptionInDB(ex, ExceptionLevel.DAL, ExceptionType.Error);
                throw new DALException(ex.Message.ToString());
            }
        }
Exemple #7
0
        // Disposes the controls of this form..
        private void DoDispose()
        {
            try
            {
                using (vlcControl)     // dispose..
                {
                    vlcControl.Stop(); // do stop the playback before disposing..
                }
            }
            catch (Exception ex)
            {
                // I don't have the time to care about this..

                // log the exception..
                ExceptionLogger.LogError(ex);
            }

            try
            {
                if (m_GlobalHook != null)
                {
                    using (m_GlobalHook)                                  // dispose more..
                    {
                        m_GlobalHook.MouseMove -= M_GlobalHook_MouseMove; // release the event handlers..
                        m_GlobalHook.MouseDown -= M_GlobalHook_MouseDown;
                    }
                }
            }
            catch (Exception ex)
            {
                // log the exception..
                ExceptionLogger.LogError(ex);

                // And again: I don't have the time to care about this..more..
            }
        }
Exemple #8
0
        /// <summary>
        /// This method 'SaveWaitedlistBooking' will save all the waited list users
        /// </summary>
        /// <param name=" data"></param>
        /// <returns>Returns 1 if Success, 0 for failure</returns>
        public bool SaveWaitedlistBooking(BookingTableInputDTO bookingTableInput)
        {
            try
            {
                var dtClient = new DataTable();

                dtClient.Columns.Add("BookingID", typeof(Int64));
                dtClient.Columns.Add("TruflUserID", typeof(Int64));
                dtClient.Columns.Add("RestaurantID", typeof(Int64));
                dtClient.Columns.Add("PartySize", typeof(Int64));
                dtClient.Columns.Add("OfferType", typeof(Int64));
                dtClient.Columns.Add("OfferAmount", typeof(Int64));
                dtClient.Columns.Add("BookingStatus", typeof(Int64));
                dtClient.Columns.Add("Points", typeof(Int64));
                dtClient.Columns.Add("TruflUserCardDataID", typeof(Int64));
                dtClient.Columns.Add("TruflTCID", typeof(Int64));
                dtClient.Columns.Add("ModifiedDate", typeof(DateTime));
                dtClient.Columns.Add("ModifiedBy", typeof(Int64));
                dtClient.Columns.Add("Quoted", typeof(DateTime));
                dtClient.Columns.Add("PaymentStatus", typeof(string));
                dtClient.Columns.Add("TableNumbers", typeof(string));


                dtClient.Rows.Add(bookingTableInput.BookingID,
                                  bookingTableInput.TruflUserID,
                                  bookingTableInput.RestaurantID,
                                  bookingTableInput.PartySize,
                                  bookingTableInput.OfferType,
                                  bookingTableInput.OfferAmount,
                                  bookingTableInput.BookingStatus,
                                  bookingTableInput.Points,
                                  bookingTableInput.TruflUserCardDataID,
                                  bookingTableInput.TruflTCID,
                                  bookingTableInput.ModifiedDate,
                                  bookingTableInput.ModifiedBy,
                                  bookingTableInput.Quoted,
                                  bookingTableInput.PaymentStatus,
                                  bookingTableInput.TableNumbers
                                  );

                string connectionString = ConfigurationManager.AppSettings["TraflConnection"];
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("spSaveBooking", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        SqlParameter tvpParam = cmd.Parameters.AddWithValue("@BookingTY", dtClient);
                        tvpParam.SqlDbType = SqlDbType.Structured;
                        SqlParameter tvparam1 = cmd.Parameters.AddWithValue("@LoggedInUser", bookingTableInput.LoggedInUser);
                        tvparam1.SqlDbType = SqlDbType.Int;

                        SqlParameter pvNewId = new SqlParameter();
                        pvNewId.ParameterName = "@RetVal";
                        pvNewId.DbType        = DbType.Int32;
                        pvNewId.Direction     = ParameterDirection.Output;
                        cmd.Parameters.Add(pvNewId);

                        int status = cmd.ExecuteNonQuery();
                        if (status == 0)
                        {
                            return(false);
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionLogger.WriteToErrorLogFile(ex);
                return(false);
            }
        }
Exemple #9
0
        public bool TryAuthenticate(string AuthTicket)
        {
            try
            {
                UserData userData = UserDataFactory.GetUserData(AuthTicket, out byte errorCode);
                if (errorCode == 1 || errorCode == 2)
                {
                    Disconnect();
                    return(false);
                }

                #region Ban Checking
                //Let's have a quick search for a ban before we successfully authenticate..
                ModerationBan BanRecord = null;
                if (!string.IsNullOrEmpty(MachineId))
                {
                    if (CloudServer.GetGame().GetModerationManager().IsBanned(MachineId, out BanRecord))
                    {
                        if (CloudServer.GetGame().GetModerationManager().MachineBanCheck(MachineId))
                        {
                            Disconnect();
                            return(false);
                        }
                    }
                }

                if (userData.user != null)
                {
                    //Now let us check for a username ban record..
                    BanRecord = null;
                    if (CloudServer.GetGame().GetModerationManager().IsBanned(userData.user.Username, out BanRecord))
                    {
                        if (CloudServer.GetGame().GetModerationManager().UsernameBanCheck(userData.user.Username))
                        {
                            Disconnect();
                            return(false);
                        }
                    }
                }
                #endregion

                CloudServer.GetGame().GetClientManager().RegisterClient(this, userData.userID, userData.user.Username);
                _habbo           = userData.user;
                _habbo.ssoTicket = AuthTicket;
                if (_habbo != null)
                {
                    userData.user.Init(this, userData);

                    SendMessage(new AuthenticationOKComposer());
                    SendMessage(new AvatarEffectsComposer(_habbo.Effects().GetAllEffects));
                    SendMessage(new NavigatorSettingsComposer(_habbo.HomeRoom));
                    SendMessage(new FavouritesComposer(userData.user.FavoriteRooms));
                    SendMessage(new FigureSetIdsComposer(_habbo.GetClothing().GetClothingParts));
                    SendMessage(new UserRightsComposer(_habbo));
                    SendMessage(new AvailabilityStatusComposer());
                    SendMessage(new AchievementScoreComposer(_habbo.GetStats().AchievementPoints));
                    SendMessage(new BuildersClubMembershipComposer());
                    SendMessage(new CfhTopicsInitComposer(CloudServer.GetGame().GetModerationManager().UserActionPresets));
                    SendMessage(new BadgeDefinitionsComposer(CloudServer.GetGame().GetAchievementManager()._achievements));
                    SendMessage(new SoundSettingsComposer(_habbo.ClientVolume, _habbo.ChatPreference, _habbo.AllowMessengerInvites, _habbo.FocusPreference, FriendBarStateUtility.GetInt(_habbo.FriendbarState)));

                    if (GetHabbo().GetMessenger() != null)
                    {
                        GetHabbo().GetMessenger().OnStatusChanged(true);
                    }

                    if (!string.IsNullOrEmpty(MachineId))
                    {
                        if (_habbo.MachineId != MachineId)
                        {
                            using (IQueryAdapter dbClient = CloudServer.GetDatabaseManager().GetQueryReactor())
                            {
                                dbClient.SetQuery("UPDATE `users` SET `machine_id` = @MachineId WHERE `id` = @id LIMIT 1");
                                dbClient.AddParameter("MachineId", MachineId);
                                dbClient.AddParameter("id", _habbo.Id);
                                dbClient.RunQuery();
                            }
                        }

                        _habbo.MachineId = MachineId;
                    }

                    if (CloudServer.GetGame().GetPermissionManager().TryGetGroup(_habbo.Rank, out PermissionGroup PermissionGroup))
                    {
                        if (!String.IsNullOrEmpty(PermissionGroup.Badge))
                        {
                            if (!_habbo.GetBadgeComponent().HasBadge(PermissionGroup.Badge))
                            {
                                _habbo.GetBadgeComponent().GiveBadge(PermissionGroup.Badge, true, this);
                            }
                        }
                    }

                    if (!CloudServer.GetGame().GetCacheManager().ContainsUser(_habbo.Id))
                    {
                        CloudServer.GetGame().GetCacheManager().GenerateUser(_habbo.Id);
                    }

                    _habbo.InitProcess();

                    if (userData.user.GetPermissions().HasRight("mod_tickets"))
                    {
                        SendMessage(new ModeratorInitComposer(
                                        CloudServer.GetGame().GetModerationManager().UserMessagePresets,
                                        CloudServer.GetGame().GetModerationManager().RoomMessagePresets,
                                        CloudServer.GetGame().GetModerationManager().GetTickets));
                    }

                    if (CloudServer.GetGame().GetSettingsManager().TryGetValue("user.login.message.enabled") == "1")
                    {
                        SendMessage(new MOTDNotificationComposer(CloudServer.GetGame().GetLanguageManager().TryGetValue("user.login.message")));
                    }

                    if (ExtraSettings.WELCOME_MESSAGE_ENABLED)
                    {
                        SendMessage(new MOTDNotificationComposer(ExtraSettings.WelcomeMessage.Replace("%username%", GetHabbo().Username)));
                    }



                    if (ExtraSettings.TARGETED_OFFERS_ENABLED)
                    {
                        if (CloudServer.GetGame().GetTargetedOffersManager().TargetedOffer != null)
                        {
                            CloudServer.GetGame().GetTargetedOffersManager().Initialize(CloudServer.GetDatabaseManager().GetQueryReactor());
                            TargetedOffers TargetedOffer = CloudServer.GetGame().GetTargetedOffersManager().TargetedOffer;

                            if (TargetedOffer.Expire > CloudServer.GetIUnixTimestamp())
                            {
                                if (TargetedOffer.Limit != GetHabbo()._TargetedBuy)
                                {
                                    SendMessage(CloudServer.GetGame().GetTargetedOffersManager().TargetedOffer.Serialize());
                                }
                            }
                            else
                            {
                                using (var dbClient = CloudServer.GetDatabaseManager().GetQueryReactor())
                                    dbClient.runFastQuery("UPDATE targeted_offers SET active = 'false'");
                                using (var dbClient2 = CloudServer.GetDatabaseManager().GetQueryReactor())
                                    dbClient2.runFastQuery("UPDATE users SET targeted_buy = '0' WHERE targeted_buy > 0");
                            }
                        }
                    }

                    //SendMessage(new HCGiftsAlertComposer());



                    /*var nuxStatuss = new ServerPacket(ServerPacketHeader.NuxSuggestFreeGiftsMessageComposer);
                     * SendMessage(nuxStatuss);*/

                    CloudServer.GetGame().GetRewardManager().CheckRewards(this);
                    CloudServer.GetGame().GetAchievementManager().TryProgressHabboClubAchievements(this);
                    CloudServer.GetGame().GetAchievementManager().TryProgressRegistrationAchievements(this);
                    CloudServer.GetGame().GetAchievementManager().TryProgressLoginAchievements(this);
                    ICollection <MessengerBuddy> Friends = new List <MessengerBuddy>();
                    foreach (MessengerBuddy Buddy in GetHabbo().GetMessenger().GetFriends().ToList())
                    {
                        if (Buddy == null)
                        {
                            continue;
                        }

                        GameClient Friend = CloudServer.GetGame().GetClientManager().GetClientByUserID(Buddy.Id);
                        if (Friend == null)
                        {
                            continue;
                        }
                        string figure = GetHabbo().Look;
                    }
                    return(true);
                }
            }
            catch (Exception e)
            {
                ExceptionLogger.LogException(e);
            }
            return(false);
        }
        public ApiResponse GetRecentExceptions([FromQuery] int?top, [FromQuery] string endpoint, [FromQuery] string app, [FromQuery] string routine)
        {
            try
            {
                if (!top.HasValue)
                {
                    top = 20;
                }
                if (top > 800)
                {
                    top = 800;
                }

                string[] endpointLookup = null;
                string[] appLookup      = null;

                if (string.IsNullOrEmpty(endpoint) || endpoint.Equals("all", StringComparison.OrdinalIgnoreCase))
                {
                    endpoint = null;
                }
                if (string.IsNullOrEmpty(app) || app.Equals("all", StringComparison.OrdinalIgnoreCase))
                {
                    app = null;
                }
                if (string.IsNullOrEmpty(routine))
                {
                    routine = null;
                }

                if (endpoint != null)
                {
                    endpointLookup = endpoint.Split(',', StringSplitOptions.RemoveEmptyEntries);

                    if (endpointLookup.FirstOrDefault(e => e.Equals("all", StringComparison.OrdinalIgnoreCase)) != null)
                    {
                        endpointLookup = null;
                    }
                }

                if (app != null)
                {
                    appLookup = app.Split(',', StringSplitOptions.RemoveEmptyEntries);

                    if (appLookup.FirstOrDefault(a => a.Equals("all", StringComparison.OrdinalIgnoreCase)) != null)
                    {
                        appLookup = null;
                    }
                }

                var ret = from exception in ExceptionLogger.GetAll(endpointLookup)
                          where exception.HasAppTitle(appLookup) &&
                          (routine == null || (exception.execOptions?.MatchRoutine(routine) ?? false))
                          orderby exception.created.Ticks descending
                          select new
                {
                    id = exception.sId,
                    exception.created,
                    message = exception.message.Left(200, true),           // limit exception message length to something reasonable
                    exception.procedure,
                    exception.appTitle,
                    exception.appVersion,
                    relatedCount = exception.related?.Count ?? 0
                }
                ;

                return(ApiResponse.Payload(new
                {
                    Results = ret.Take(Math.Min(top.Value, ret.Count())),
                    TotalExceptionCnt = ExceptionLogger.TotalCnt
                }));
            }
            catch (Exception ex)
            {
                SessionLog.Exception(ex);
                return(ApiResponse.Exception(ex));
            }
        }
Exemple #11
0
        public Habbo(int Id, string Username, int Rank, string Motto, string Look, string Gender, int Credits, int ActivityPoints, int HomeRoom,
                     bool HasFriendRequestsDisabled, int LastOnline, bool AppearOffline, bool HideInRoom, double CreateDate, int Diamonds,
                     string machineID, string clientVolume, bool ChatPreference, bool FocusPreference, bool PetsMuted, bool BotsMuted, bool AdvertisingReportBlocked, double LastNameChange,
                     int GOTWPoints, bool IgnoreInvites, double TimeMuted, double TradingLock, bool AllowGifts, int FriendBarState, bool DisableForcedEffects, bool AllowMimic, int VIPRank)
        {
            _id             = Id;
            _username       = Username;
            _rank           = Rank;
            _motto          = Motto;
            _look           = Look;
            _gender         = Gender.ToLower();
            _footballLook   = PlusEnvironment.FilterFigure(Look.ToLower());
            _footballGender = Gender.ToLower();
            _credits        = Credits;
            _duckets        = ActivityPoints;
            _diamonds       = Diamonds;
            _gotwPoints     = GOTWPoints;
            _homeRoom       = HomeRoom;
            _lastOnline     = LastOnline;
            _accountCreated = CreateDate;
            _clientVolume   = new List <int>();
            foreach (string Str in clientVolume.Split(','))
            {
                int Val = 0;
                if (int.TryParse(Str, out Val))
                {
                    _clientVolume.Add(int.Parse(Str));
                }
                else
                {
                    _clientVolume.Add(100);
                }
            }

            _lastNameChange  = LastNameChange;
            _machineId       = machineID;
            _chatPreference  = ChatPreference;
            _focusPreference = FocusPreference;
            _isExpert        = IsExpert == true;

            _appearOffline         = AppearOffline;
            _allowTradingRequests  = true;                      //TODO
            _allowUserFollowing    = true;                      //TODO
            _allowFriendRequests   = HasFriendRequestsDisabled; //TODO
            _allowMessengerInvites = IgnoreInvites;
            _allowPetSpeech        = PetsMuted;
            _allowBotSpeech        = BotsMuted;
            _allowPublicRoomStatus = HideInRoom;
            _allowConsoleMessages  = true;
            _allowGifts            = AllowGifts;
            _allowMimic            = AllowMimic;
            _receiveWhispers       = true;
            _ignorePublicWhispers  = false;
            _playingFastFood       = false;
            _friendbarState        = FriendBarStateUtility.GetEnum(FriendBarState);
            _christmasDay          = ChristmasDay;
            _wantsToRideHorse      = 0;
            _timeAFK = 0;
            _disableForcedEffects = DisableForcedEffects;
            _vipRank = VIPRank;

            _disconnected = false;
            _habboSaved   = false;
            _changingName = false;

            _floodTime   = 0;
            _friendCount = 0;
            _timeMuted   = TimeMuted;
            _timeCached  = DateTime.Now;

            _tradingLockExpiry = TradingLock;
            if (_tradingLockExpiry > 0 && PlusEnvironment.GetUnixTimestamp() > TradingLockExpiry)
            {
                _tradingLockExpiry = 0;
                using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                {
                    dbClient.RunQuery("UPDATE `user_info` SET `trading_locked` = '0' WHERE `user_id` = '" + Id + "' LIMIT 1");
                }
            }

            _bannedPhraseCount  = 0;
            _sessionStart       = PlusEnvironment.GetUnixTimestamp();
            _messengerSpamCount = 0;
            _messengerSpamTime  = 0;
            _creditsTickUpdate  = Convert.ToInt32(PlusEnvironment.GetSettingsManager().TryGetValue("user.currency_scheduler.tick"));

            _tentId            = 0;
            _hopperId          = 0;
            _isHopping         = false;
            _teleportId        = 0;
            _isTeleporting     = false;
            _teleportingRoomId = 0;
            _roomAuthOk        = false;
            _currentRoomId     = 0;

            _hasSpoken                = false;
            _lastAdvertiseReport      = 0;
            _advertisingReported      = false;
            _advertisingReportBlocked = AdvertisingReportBlocked;

            _wiredInteraction   = false;
            _questLastCompleted = 0;
            _inventoryAlert     = false;
            _ignoreBobbaFilter  = false;
            _wiredTeleporting   = false;
            _customBubbleId     = 0;
            _onHelperDuty       = false;
            _fastfoodScore      = 0;
            _petId   = 0;
            _tempInt = 0;

            _lastGiftPurchaseTime       = DateTime.Now;
            _lastMottoUpdateTime        = DateTime.Now;
            _lastClothingUpdateTime     = DateTime.Now;
            _lastForumMessageUpdateTime = DateTime.Now;

            _giftPurchasingWarnings = 0;
            _mottoUpdateWarnings    = 0;
            _clothingUpdateWarnings = 0;

            _sessionGiftBlocked     = false;
            _sessionMottoBlocked    = false;
            _sessionClothingBlocked = false;

            FavoriteRooms = new ArrayList();
            Achievements  = new ConcurrentDictionary <string, UserAchievement>();
            Relationships = new Dictionary <int, Relationship>();
            RatedRooms    = new List <int>();

            //TODO: Nope.
            InitPermissions();

            #region Stats
            DataRow StatRow = null;
            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
            {
                dbClient.SetQuery("SELECT `id`,`roomvisits`,`onlinetime`,`respect`,`respectgiven`,`giftsgiven`,`giftsreceived`,`dailyrespectpoints`,`dailypetrespectpoints`,`achievementscore`,`quest_id`,`quest_progress`,`groupid`,`tickets_answered`,`respectstimestamp`,`forum_posts` FROM `user_stats` WHERE `id` = @user_id LIMIT 1");
                dbClient.AddParameter("user_id", Id);
                StatRow = dbClient.GetRow();

                if (StatRow == null)//No row, add it yo
                {
                    dbClient.RunQuery("INSERT INTO `user_stats` (`id`) VALUES ('" + Id + "')");
                    dbClient.SetQuery("SELECT `id`,`roomvisits`,`onlinetime`,`respect`,`respectgiven`,`giftsgiven`,`giftsreceived`,`dailyrespectpoints`,`dailypetrespectpoints`,`achievementscore`,`quest_id`,`quest_progress`,`groupid`,`tickets_answered`,`respectstimestamp`,`forum_posts` FROM `user_stats` WHERE `id` = @user_id LIMIT 1");
                    dbClient.AddParameter("user_id", Id);
                    StatRow = dbClient.GetRow();
                }

                try
                {
                    _habboStats = new HabboStats(Convert.ToInt32(StatRow["roomvisits"]), Convert.ToDouble(StatRow["onlineTime"]), Convert.ToInt32(StatRow["respect"]), Convert.ToInt32(StatRow["respectGiven"]), Convert.ToInt32(StatRow["giftsGiven"]),
                                                 Convert.ToInt32(StatRow["giftsReceived"]), Convert.ToInt32(StatRow["dailyRespectPoints"]), Convert.ToInt32(StatRow["dailyPetRespectPoints"]), Convert.ToInt32(StatRow["AchievementScore"]),
                                                 Convert.ToInt32(StatRow["quest_id"]), Convert.ToInt32(StatRow["quest_progress"]), Convert.ToInt32(StatRow["groupid"]), Convert.ToString(StatRow["respectsTimestamp"]), Convert.ToInt32(StatRow["forum_posts"]));

                    if (Convert.ToString(StatRow["respectsTimestamp"]) != DateTime.Today.ToString("MM/dd"))
                    {
                        _habboStats.RespectsTimestamp = DateTime.Today.ToString("MM/dd");
                        SubscriptionData SubData = null;

                        int DailyRespects = 10;

                        if (_permissions.HasRight("mod_tool"))
                        {
                            DailyRespects = 20;
                        }
                        else if (PlusEnvironment.GetGame().GetSubscriptionManager().TryGetSubscriptionData(VIPRank, out SubData))
                        {
                            DailyRespects = SubData.Respects;
                        }

                        _habboStats.DailyRespectPoints    = DailyRespects;
                        _habboStats.DailyPetRespectPoints = DailyRespects;

                        dbClient.RunQuery("UPDATE `user_stats` SET `dailyRespectPoints` = '" + DailyRespects + "', `dailyPetRespectPoints` = '" + DailyRespects + "', `respectsTimestamp` = '" + DateTime.Today.ToString("MM/dd") + "' WHERE `id` = '" + Id + "' LIMIT 1");
                    }
                }
                catch (Exception e)
                {
                    ExceptionLogger.LogException(e);
                }
            }

            Group G = null;
            if (!PlusEnvironment.GetGame().GetGroupManager().TryGetGroup(_habboStats.FavouriteGroupId, out G))
            {
                _habboStats.FavouriteGroupId = 0;
            }
            #endregion
        }
Exemple #12
0
        /// <summary>
        /// Updates address
        /// </summary>
        /// <returns></returns>
        public static async Task UpdateAddress()
        {
            try
            {
                using (IAddressBL addressBL = new AddressBL())
                {
                    //Read Sl.No
                    Write("Address #: ");
                    bool isNumberValid = int.TryParse(ReadLine(), out int serial);
                    if (isNumberValid)
                    {
                        serial--;
                        CustomerBL CustomerBL = new CustomerBL();
                        Customer   Customer   = await CustomerBL.GetCustomerByEmailBL(CommonData.CurrentUser.Email);

                        List <Address> addresses = await addressBL.GetAddressByCustomerIDBL(Customer.CustomerID);

                        if (serial <= addresses.Count - 1)
                        {
                            //Read inputs
                            Address address = addresses[serial];
                            Write("Address Line 1: ");
                            address.AddressLine1 = ReadLine();
                            Write("Address Line 2: ");
                            address.AddressLine2 = ReadLine();
                            Write("LandMark: ");
                            address.Landmark = ReadLine();
                            Write("City: ");
                            address.City = ReadLine();
                            Write("State: ");
                            address.State = ReadLine();


                            Write("PinCode: ");
                            address.PinCode = ReadLine();

                            //Invoke UpdateAddressBL method to update
                            bool isUpdated = await addressBL.UpdateAddressBL(address);

                            if (isUpdated)
                            {
                                WriteLine("Address Updated");
                            }
                        }
                        else
                        {
                            WriteLine($"Invalid Address #.\nPlease enter a number between 1 to {addresses.Count}");
                        }
                    }
                    else
                    {
                        WriteLine($"Invalid number.");
                    }
                }
            }
            catch (System.Exception ex)
            {
                ExceptionLogger.LogException(ex);
                WriteLine(ex.Message);
            }
        }
Exemple #13
0
        public bool OnCycle()
        {
            if (!this.Requested || String.IsNullOrEmpty(this.StringData) || this.StringData == "0;0;0" || this.SetItems.Count == 0)
            {
                return(false);
            }

            foreach (Item item in this.SetItems.Values.ToList())
            {
                if (Instance.GetRoomItemHandler().GetFloor == null && !Instance.GetRoomItemHandler().GetFloor.Contains(item))
                {
                    continue;
                }

                foreach (string I in this.ItemsData.Split(';'))
                {
                    if (string.IsNullOrEmpty(I))
                    {
                        continue;
                    }

                    int  itemId = Convert.ToInt32(I.Split(':')[0]);
                    Item II     = Instance.GetRoomItemHandler().GetItem(Convert.ToInt32(itemId));
                    if (II == null)
                    {
                        continue;
                    }

                    string[] partsString = I.Split(':');
                    try
                    {
                        if (string.IsNullOrEmpty(partsString[0]) || string.IsNullOrEmpty(partsString[1]))
                        {
                            continue;
                        }
                    }
                    catch { continue; }

                    string[] part = partsString[1].Split(',');

                    try
                    {
                        if (int.Parse(this.StringData.Split(';')[0]) == 1)//State
                        {
                            if (part.Count() >= 4)
                            {
                                this.SetState(II, part[4].ToString());
                            }
                            else
                            {
                                this.SetState(II, "1");
                            }
                        }
                    }
                    catch (Exception e) { ExceptionLogger.LogWiredException(e); }

                    try
                    {
                        if (int.Parse(this.StringData.Split(';')[1]) == 1)//Direction
                        {
                            this.SetRotation(II, Convert.ToInt32(part[3]));
                        }
                    }
                    catch (Exception e) { ExceptionLogger.LogWiredException(e); }

                    try
                    {
                        if (int.Parse(this.StringData.Split(';')[2]) == 1)//Position
                        {
                            this.SetPosition(II, Convert.ToInt32(part[0].ToString()), Convert.ToInt32(part[1].ToString()), Convert.ToDouble(part[2].ToString()));
                        }
                    }
                    catch (Exception e) { ExceptionLogger.LogWiredException(e); }
                }
            }
            this.Requested = false;
            return(true);
        }
        //(object/*ApiResponse | IActionResult*/, RoutineExecution, CommonReturnValue)
        public static async Task <ExecuteRoutineAsyncResult> ExecuteRoutineAsync(ExecOptions execOptions,
                                                                                 Dictionary <string, string> requestHeaders,
                                                                                 string referer,
                                                                                 string remoteIpAddress,
                                                                                 string appTitle,
                                                                                 string appVersion)
        {
            string debugInfo = null;

            Project     project  = null;
            Application app      = null;
            Endpoint    endpoint = null;
            Dictionary <string, string> responseHeaders = null;

            List <ExecutionPlugin> pluginList = null;

            RoutineExecution routineExecutionMetric = null;

            responseHeaders = new Dictionary <string, string>();

            try
            {
                if (!ControllerHelper.GetProjectAndAppAndEndpoint(execOptions.project, execOptions.application, execOptions.endpoint, out project,
                                                                  out app, out endpoint, out var resp))
                {
                    return(new ExecuteRoutineAsyncResult(resp, null, null, responseHeaders));
                }

                routineExecutionMetric = new RoutineExecution(endpoint, execOptions.schema, execOptions.routine);

                RealtimeTrackerThread.Instance.Enqueue(routineExecutionMetric);

                //  debugInfo += $"[{execOptions.schema}].[{execOptions.routine}]";

                string jsDALApiKey = null;

                if (requestHeaders.ContainsKey("api-key"))
                {
                    jsDALApiKey = requestHeaders["api-key"];
                }

                // make sure the source domain/IP is allowed access
                var mayAccess = app.MayAccessDbSource(referer, jsDALApiKey);

                if (!mayAccess.IsSuccess)
                {
                    return(new ExecuteRoutineAsyncResult(null, null, mayAccess, responseHeaders));
                }

                Dictionary <string, dynamic> outputParameters;
                int commandTimeOutInSeconds = 60;

                // PLUGINS
                var pluginsInitMetric = routineExecutionMetric.BeginChildStage("Init plugins");

                pluginList = InitPlugins(app, execOptions.inputParameters, requestHeaders);

                pluginsInitMetric.End();

                ////////////////////
                // Auth stage
                ///////////////////
                { // ask all ExecPlugins to authenticate
                    foreach (var plugin in pluginList)
                    {
                        if (!plugin.IsAuthenticated(execOptions.schema, execOptions.routine, out var error))
                        {
                            responseHeaders.Add("Plugin-AuthFailed", plugin.Name);
                            return(new ExecuteRoutineAsyncResult(new UnauthorizedObjectResult(error), null, null, responseHeaders));
                        }
                    }
                }

                var execRoutineQueryMetric = routineExecutionMetric.BeginChildStage("execRoutineQuery");

                string dataCollectorEntryShortId = DataCollectorThread.Enqueue(endpoint, execOptions);

                ///////////////////
                // Database call
                ///////////////////

                OrmDAL.ExecutionResult executionResult = null;

                try
                {
                    executionResult = await OrmDAL.ExecRoutineQueryAsync(
                        execOptions.CancellationToken,
                        execOptions.type,
                        execOptions.schema,
                        execOptions.routine,
                        endpoint,
                        execOptions.inputParameters,
                        requestHeaders,
                        remoteIpAddress,
                        pluginList,
                        commandTimeOutInSeconds,
                        execRoutineQueryMetric,
                        responseHeaders
                        );

                    outputParameters = executionResult.OutputParameterDictionary;
                    responseHeaders  = executionResult.ResponseHeaders;

                    execRoutineQueryMetric.End();

                    ulong?rows = null;

                    if (executionResult?.RowsAffected.HasValue ?? false)
                    {
                        rows = (ulong)executionResult.RowsAffected.Value;
                    }

                    DataCollectorThread.End(dataCollectorEntryShortId, rowsAffected: rows,
                                            durationInMS: execRoutineQueryMetric.DurationInMS,
                                            bytesReceived: executionResult.BytesReceived,
                                            networkServerTimeMS: executionResult.NetworkServerTimeInMS);
                }
                catch (Exception execEx)
                {
                    DataCollectorThread.End(dataCollectorEntryShortId, ex: execEx);

                    //                     if (execOptions != null && endpoint != null)
                    //                     {
                    //                         var wrapEx = new Exception($"Failed to execute {endpoint?.Pedigree}/{execOptions?.schema}/{execOptions?.routine}", execEx);

                    //                         // create a fake frame to include the exec detail - this way any logger logging the StackTrace will always include the relevant execution detail
                    //                         StackFrame sf = new($"{execOptions.type} {endpoint?.Pedigree}/{execOptions?.schema}/{execOptions?.routine}", 0);

                    //                         StackTrace st = new(sf);

                    //                         //?wrapEx.SetStackTrace(st);

                    // var allFields = wrapEx.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

                    // var fffff =string.Join("\r\n", allFields.Select(f=>f.Name).ToArray());

                    //                         var fi = wrapEx.GetType().GetField("_stackTraceString", BindingFlags.NonPublic | BindingFlags.Instance);

                    //                         fi.SetValue(wrapEx, $"{endpoint?.Pedigree}/{execOptions?.schema}/{execOptions?.routine}");

                    //                         throw wrapEx;
                    //                     }
                    //                     else throw;
                    throw; // rethrow
                }

                var prepareResultsMetric = routineExecutionMetric.BeginChildStage("Prepare results");

                if (!string.IsNullOrEmpty(executionResult.userError))
                {
                    return(new ExecuteRoutineAsyncResult(ApiResponse.ExclamationModal(executionResult.userError), routineExecutionMetric, mayAccess, responseHeaders));
                }

                var retVal = (IDictionary <string, object>) new System.Dynamic.ExpandoObject();
                var ret    = ApiResponse.Payload(retVal);

                retVal.Add("OutputParms", outputParameters);

                if (outputParameters != null)
                { // TODO: Consider making this a plugin
                    var possibleUEParmNames = (new string[] { "usererrormsg", "usrerrmsg", "usererrormessage", "usererror", "usererrmsg" }).ToList();

                    var ueKey = outputParameters.Keys.FirstOrDefault(k => possibleUEParmNames.Contains(k.ToLower()));

                    // if a user error msg is defined.
                    if (!string.IsNullOrWhiteSpace(ueKey) && !string.IsNullOrWhiteSpace(outputParameters[ueKey]))
                    {
                        ret.Message = outputParameters[ueKey];
                        ret.Title   = "Action failed";
                        ret.Type    = ApiResponseType.ExclamationModal;
                    }
                }

                if (execOptions.type == ExecType.Query)
                {
                    if (executionResult.ReaderResults != null)
                    {
                        var keys = executionResult.ReaderResults.Keys.ToList();

                        for (var i = 0; i < keys.Count; i++)
                        {
                            retVal.Add(keys[i], executionResult.ReaderResults[keys[i]]);
                        }

                        retVal.Add("HasResultSets", keys.Count > 0);
                        retVal.Add("ResultSetKeys", keys.ToArray());
                    }
                    else
                    {
                        var dataSet        = executionResult.DataSet;
                        var dataContainers = dataSet.ToJsonDS();

                        var keys = dataContainers.Keys.ToList();

                        for (var i = 0; i < keys.Count; i++)
                        {
                            retVal.Add(keys[i], dataContainers[keys[i]]);
                        }

                        retVal.Add("HasResultSets", keys.Count > 0);
                        retVal.Add("ResultSetKeys", keys.ToArray());
                    }
                }
                else if (execOptions.type == ExecType.NonQuery)
                {
                    // nothing to do
                }
                else if (execOptions.type == ExecType.Scalar)
                {
                    if (executionResult.ScalarValue is DateTime)
                    {
                        var dt = (DateTime)executionResult.ScalarValue;

                        // convert to Javascript Date ticks
                        var ticks = dt.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

                        ret = ApiResponseScalar.Payload(ticks, true);
                    }
                    else
                    {
                        ret = ApiResponse.Payload(executionResult.ScalarValue);
                    }
                }

                prepareResultsMetric.End();
                routineExecutionMetric.End(executionResult.RowsAffected ?? 0);

                // enqueue a second time as we now have an End date and rowsAffected
                RealtimeTrackerThread.Instance.Enqueue(routineExecutionMetric);

                return(new ExecuteRoutineAsyncResult(ret, routineExecutionMetric, mayAccess, responseHeaders));
            }
            catch (SqlException ex) when(execOptions.CancellationToken.IsCancellationRequested && ex.Number == 0 && ex.State == 0 && ex.Class == 11)
            {
                // if we ended up here with a SqlException and a Cancel has been requested, we are very likely here because of the exception "Operation cancelled by user."
                // since MS does not provide an easy way (like a specific error code) to detect this scenario we have to guess

                routineExecutionMetric?.Exception(ex);

                throw new OperationCancelledByUserException(ex);
            }
            catch (Exception ex)
            {
                routineExecutionMetric?.Exception(ex);

                Connection dbConn = null;

                if (endpoint != null)
                {
                    // TODO: Fix!
                    dbConn = endpoint.GetSqlConnection();

                    // if (debugInfo == null) debugInfo = "";

                    // if (dbConn != null)
                    // {
                    //     debugInfo = $"{ endpoint.Pedigree } - { dbConn.InitialCatalog } - { debugInfo }";
                    // }
                    // else
                    // {
                    //     debugInfo = $"{ endpoint.Pedigree } - (no connection) - { debugInfo }";
                    // }
                }

                var exceptionResponse = ApiResponse.ExecException(ex, execOptions, out var exceptionId, debugInfo, appTitle, appVersion);

                if (debugInfo == null)
                {
                    debugInfo = "";
                }
                debugInfo = exceptionId + " " + debugInfo;

                // TODO: Get Execution plugin list specifically
                if (pluginList != null)
                {
                    string externalRef;

                    if (dbConn != null)
                    {
                        using (var con = new SqlConnection(dbConn.ConnectionStringDecrypted))
                        {
                            try
                            {
                                string additionalInfo = debugInfo;

                                if (execOptions?.inputParameters != null)
                                {
                                    additionalInfo += " ";
                                    additionalInfo += string.Join(",", execOptions.inputParameters.Select(kv => $"{kv.Key}={kv.Value}").ToArray());
                                }

                                con.Open();
                                ProcessPluginExecutionExceptionHandlers(pluginList, con, ex, additionalInfo, appTitle, appVersion, out externalRef);
                                ((dynamic)exceptionResponse.Data).ExternalRef = externalRef;
                            }
                            catch (Exception e)
                            {
                                ExceptionLogger.LogException(e, "ProcessPluginExecutionExceptionHandlers", "jsdal-server");
                            }
                        }
                    } // else: TODO: Log fact that we dont have a proper connection string.. or should plugins handle that?
                }

                // return it as "200 (Ok)" because the exception has been handled
                return(new ExecuteRoutineAsyncResult(exceptionResponse, routineExecutionMetric, null, responseHeaders));
            }
        }
Exemple #15
0
        /// <summary>
        /// Enumerates installed RLs i.e
        ///  shows how you can enumerate thru one of
        ///	 the BizTalk's WMI objects and show all of its properties
        /// </summary>
        public List <BizTalk> GetBizTalkServicesStatistics()
        {
            var ServerId   = Convert.ToString(System.Web.HttpContext.Current.Session["ServerId"]);
            var ServerName = Convert.ToString(System.Web.HttpContext.Current.Session["ServerName"]);

            List <BizTalk> model = new List <BizTalk>();

            try
            {
                //Create the WMI search object.
                ManagementObjectSearcher Searcher = new ManagementObjectSearcher();

                ConnectionOptions options = new ConnectionOptions
                {
                    Username  = Convert.ToString(System.Web.HttpContext.Current.Session["Username"]),
                    Password  = Convert.ToString(System.Web.HttpContext.Current.Session["Password"]),
                    Authority = Convert.ToString(System.Web.HttpContext.Current.Session["Authority"])
                };



                // create the scope node so we can set the WMI root node correctly.
                ManagementScope Scope = new ManagementScope("\\\\" + ServerName + "\\root\\MicrosoftBizTalkServer", options);
                Searcher.Scope = Scope;

                // Build a Query to enumerate the MSBTS_ReceiveLocation instances if an argument
                // is supplied use it to select only the matching RL.

                //if (args.Length == 0)
                SelectQuery Query = new SelectQuery();
                Query.QueryString = "SELECT * FROM MSBTS_ReceiveLocation";
                //          else
                //Query.QueryString = "SELECT * FROM MSBTS_ReceiveLocation WHERE Name = '" + args[0] + "'";


                // Set the query for the searcher.
                Searcher.Query = Query;

                // Execute the query and determine if any results were obtained.
                ManagementObjectCollection QueryCol = Searcher.Get();

                // Use a bool to tell if we enter the for loop
                // below because Count property is not supported
                bool ReceiveLocationFound = false;



                // Enumerate all properties.
                foreach (ManagementBaseObject envVar in QueryCol)
                {
                    // There is at least one Receive Location
                    ReceiveLocationFound = true;

                    PropertyDataCollection envVarProperties = envVar.Properties;
                    BizTalk bizTalk = new BizTalk();
                    foreach (PropertyData envVarProperty in envVarProperties)
                    {
                        bizTalk.Name           = Convert.ToString(envVar["Name"]);
                        bizTalk.TransportType  = Convert.ToString(envVar["AdapterName"]);
                        bizTalk.Uri            = Convert.ToString(envVar["InboundTransportURL"]);
                        bizTalk.Status         = Convert.ToString(envVar["IsDisabled"]);
                        bizTalk.ReceiveHandler = Convert.ToString(envVar["HostName"]);
                        bizTalk.ReceivePort    = Convert.ToString(envVar["ReceivePortName"]);
                        bizTalk.RunDate        = DateTime.Now;
                        //bizTalk.ApplicationId = 24;
                        //bizTalk.ServerId = Convert.ToInt32(ServerId);
                        bizTalk.InstanceName = "FBCZOP";
                        model.Add(bizTalk);
                    }
                }

                if (!ReceiveLocationFound)
                {
                    Console.WriteLine("No receive locations found matching the specified name.");
                }
            }

            catch (Exception excep)
            {
                ExceptionLogger.SendErrorToText(excep);
            }

            return(model);
        }
Exemple #16
0
        /// <summary>
        /// Confirm Order
        /// </summary>
        /// <returns></returns>
        public static async Task ConfirmOrder()
        {
            try
            {
                IProductBL productBL = new ProductBL();
                Guid       tempOrderID;
                using (IOrderDetailBL orderDetailBL = new OrderDetailBL())
                {
                    CustomerBL CustomerBL = new CustomerBL();
                    Customer   Customer   = await CustomerBL.GetCustomerByEmailBL(CommonData.CurrentUser.Email);

                    AddressBL      addressBL = new AddressBL();
                    List <Address> addresses = await addressBL.GetAddressByCustomerIDBL(Customer.CustomerID);

                    double totalamount = 0;
                    int    quantity    = 0;
                    Guid   orderID     = Guid.NewGuid();
                    tempOrderID = orderID;
                    foreach (var cartProduct in cart)
                    {
                        OrderDetail orderDetail = new OrderDetail();
                        WriteLine("#\tAddressLine 1\tLandMark\tCity");
                        int serial = 0;
                        foreach (var address in addresses)
                        {
                            serial++;
                            WriteLine($"{serial}\t{address.AddressLine1}\t{address.Landmark}\t{address.City}");
                        }

                        Write("Address #: ");
                        bool isNumberValid = int.TryParse(ReadLine(), out int serial1);
                        if (isNumberValid)
                        {
                            serial1--;

                            if (serial1 <= addresses.Count - 1)
                            {
                                //Read inputs
                                Address address = addresses[serial1];
                                orderDetail.AddressId = address.AddressID;
                            }
                        }
                        orderDetail.OrderId                = orderID;
                        orderDetail.ProductID              = cartProduct.ProductID;
                        orderDetail.ProductPrice           = cartProduct.ProductPrice;
                        orderDetail.ProductQuantityOrdered = cartProduct.ProductQuantityOrdered;
                        orderDetail.TotalAmount            = (cartProduct.ProductPrice * cartProduct.ProductQuantityOrdered);
                        totalamount += orderDetail.TotalAmount;
                        quantity    += orderDetail.ProductQuantityOrdered;
                        bool isAdded;
                        Guid newguid;
                        (isAdded, newguid) = await orderDetailBL.AddOrderDetailsBL(orderDetail);
                    }

                    using (IOrderBL orderBL = new OrderBL())
                    {
                        Order order = new Order();
                        order.OrderId       = orderID;
                        order.CustomerID    = Customer.CustomerID;
                        order.TotalQuantity = quantity;
                        order.OrderAmount   = totalamount;
                        bool isAdded;
                        Guid newguid;
                        (isAdded, newguid) = await orderBL.AddOrderBL(order);

                        if (isAdded)
                        {
                            WriteLine("Order  Added");
                        }
                    }
                }
                IOrderBL orderBL1 = new OrderBL();

                Order order1 = await orderBL1.GetOrderByOrderIDBL(tempOrderID);

                WriteLine($"Your Order No. {order1.OrderNumber}\t{order1.TotalQuantity}\t{order1.OrderAmount}\t{order1.DateOfOrder}");
                WriteLine("Order Details");
                IOrderDetailBL     orderDetailBL1   = new OrderDetailBL();
                List <OrderDetail> orderDetailslist = await orderDetailBL1.GetOrderDetailsByOrderIDBL(tempOrderID);

                foreach (var item in orderDetailslist)
                {
                    Product product = await productBL.GetProductByProductIDBL(item.ProductID);

                    WriteLine($"{product.ProductName}\t{item.ProductPrice}\t{item.ProductQuantityOrdered}\t{item.TotalAmount}");
                }
                cart.Clear();
            }
            catch (System.Exception ex)
            {
                ExceptionLogger.LogException(ex);
                WriteLine(ex.Message);
            }
        }
Exemple #17
0
        /// <summary>
        /// Gets product based on ID/Name/Category
        /// </summary>
        /// <returns></returns>
        public static async Task GetProduct()
        {
            try
            {
                using (IProductBL productBL = new ProductBL())
                {
                    int choice;
                    WriteLine("Enter:\n1.Get all products\n2.Get product by product name.\n3.Get product by product category");
                    choice = int.Parse(ReadLine());
                    switch (choice)
                    {
                    case 1:

                        List <Product> allProductList = new List <Product>();
                        allProductList = await productBL.GetAllProductsBL();

                        break;

                    case 2:
                        Write("Product name: ");
                        string         productName     = ReadLine();
                        List <Product> productNameList = new List <Product>();
                        productNameList = await productBL.GetProductsByProductNameBL(productName);

                        break;

                    case 3:
                        WriteLine("Choose among the following categories:");
                        WriteLine("1.Camping Equipment");
                        WriteLine("2.Outdoor Equipment");
                        WriteLine("3.Personal Accessories");
                        WriteLine("4.Mountaineering Equipment");
                        WriteLine("5.Golf Equipment");
                        bool isCategory = int.TryParse(ReadLine(), out int choice1); Category givenCategory;
                        if (isCategory)
                        {
                            if (choice1 == 1)
                            {
                                givenCategory = Category.CampingEquipment;
                            }
                            else if (choice1 == 2)
                            {
                                givenCategory = Category.OutdoorEquipment;
                            }
                            else if (choice1 == 3)
                            {
                                givenCategory = Category.PersonalAccessories;
                            }
                            else if (choice1 == 4)
                            {
                                givenCategory = Category.MountaineeringEquipment;
                            }
                            else if (choice1 == 5)
                            {
                                givenCategory = Category.GolfEquipment;
                            }
                            else
                            {
                                givenCategory = Category.CampingEquipment;
                            }
                        }
                        else
                        {
                            givenCategory = Category.CampingEquipment;
                        }
                        List <Product> categoryProductList = new List <Product>();
                        categoryProductList = await productBL.GetProductsByProductCategoryBL(givenCategory);

                        break;

                    default: WriteLine("Invalid Choice"); break;
                    }
                }
            }
            catch (System.Exception ex)
            {
                ExceptionLogger.LogException(ex);
                WriteLine(ex.Message);
            }
        }
Exemple #18
0
        /// <summary>
        /// Gets the resource components for the compute hours of the Virtual machine resource. This includes components for software cost if present.
        /// </summary>
        /// <returns> Returns the list of resource components </returns>
        private List <ResourceComponent> GetResourceComponentForComputeHours()
        {
            List <ResourceComponent> componentList = new List <ResourceComponent>();

            // Create the compute hours component, Meter SubCategory value will be set later
            ResourceComponent computeHoursComponent = new ResourceComponent
            {
                ResourceType     = this.resource.Type,
                MeterCategory    = VMResourceConstants.VMMeterCategory,
                MeterSubCategory = null,
                MeterName        = VMResourceConstants.VMMeterName,
                Quantity         = Constants.HoursinaMonth,
                IsChargeable     = true
            };

            // Create the software cost component, Meter SubCategory value will be set later
            ResourceComponent softwareCostComponent = new ResourceComponent
            {
                ResourceType     = this.resource.Type,
                MeterCategory    = VMResourceConstants.VMMeterCategory,
                MeterSubCategory = null,
                MeterName        = VMResourceConstants.VMMeterName,
                Quantity         = Constants.HoursinaMonth,
                IsChargeable     = true
            };

            string vmSize = null, osType = null, createOption = null;

            if (this.prop.HardwareProfile != null && this.prop.HardwareProfile.VmSize != null)
            {
                // Fetch the VM Size
                vmSize = PropertyHelper.GetValueIfVariableOrParam(this.prop.HardwareProfile.VmSize, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
            }
            else
            {
                throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("properties.hardwareProfile.vmSize", this.nameOfResource));
            }

            if (vmSize.Equals(string.Empty))
            {
                throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("properties.hardwareProfile.vmSize", this.nameOfResource));
            }

            if (this.prop.StorageProfile != null && this.prop.StorageProfile.OsDisk != null)
            {
                // Fetch the OS Disk related info
                osType       = PropertyHelper.GetValueIfVariableOrParam(this.prop.StorageProfile.OsDisk.OsType, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
                createOption = PropertyHelper.GetValueIfVariableOrParam(this.prop.StorageProfile.OsDisk.CreateOption, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
            }
            else
            {
                throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("properties.storageProfile.osDisk", this.nameOfResource));
            }

            if (createOption == null)
            {
                throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("properties.storageProfile.osDisk.createOption", this.nameOfResource));
            }

            if (osType == null)
            {
                if (createOption != null && createOption.Equals("FromImage", StringComparison.OrdinalIgnoreCase))
                {
                    string vmImagePublisher = null, vmImageOffer = null, vmImageSKU = null;

                    // Fetch the VM Image info - Publisher, Offer and SKU
                    if (this.prop.StorageProfile != null && this.prop.StorageProfile.ImageReference != null)
                    {
                        vmImagePublisher = PropertyHelper.GetValueIfVariableOrParam(this.prop.StorageProfile.ImageReference.Publisher, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
                        vmImageOffer     = PropertyHelper.GetValueIfVariableOrParam(this.prop.StorageProfile.ImageReference.Offer, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
                        vmImageSKU       = PropertyHelper.GetValueIfVariableOrParam(this.prop.StorageProfile.ImageReference.Sku, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
                    }
                    else
                    {
                        throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("properties.storageProfile.imageReference", this.nameOfResource));
                    }

                    if (vmImagePublisher != null && vmImageOffer != null && vmImageSKU != null)
                    {
                        // Get the OS Type of the VM Image from the Online Helper method
                        osType = VMOnlineHelper.GetVMImageOSType(this.cspCreds, vmImagePublisher, vmImageOffer, vmImageSKU, this.location);
                        string meterSubCategoryForVMImageWithSoftwareCost = null;

                        // Get the Meter SubCategory for software cost of the VM Image is applicable
                        meterSubCategoryForVMImageWithSoftwareCost = VMImageHelper.GetMeterSubCategoryForVMImageWithSoftwareCost(this.cspCreds, vmImagePublisher, vmImageOffer, vmImageSKU, vmSize, this.location);
                        if (meterSubCategoryForVMImageWithSoftwareCost != null)
                        {
                            // Set the Meter SubCategory for Software Cost component, Add to the List of resource components
                            softwareCostComponent.MeterSubCategory = meterSubCategoryForVMImageWithSoftwareCost;
                            componentList.Add(softwareCostComponent);
                        }
                    }
                    else
                    {
                        throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("properties.storageProfile.publisher/offer/sku", this.nameOfResource));
                    }
                }
                else
                {
                    throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("storageProfile.osDisk.createOption", createOption, this.nameOfResource));
                }
            }

            string meterSubCategory     = null;
            string modifiedVMSizeString = VMHelper.ModifyVMSizeStringAsPerPricingSpecs(vmSize);

            if (osType != null)
            {
                // Fetch the Meter SubCategory as per the OS Type
                switch (osType.ToUpper())
                {
                case "WINDOWS":
                    meterSubCategory = string.Format(VMResourceConstants.VMMeterSubCategoryWindowsString, modifiedVMSizeString, osType);
                    break;

                case "LINUX":
                    meterSubCategory = string.Format(VMResourceConstants.VMMeterSubCategoryLinuxString, modifiedVMSizeString);
                    break;

                default:
                    throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("OSType", osType, this.nameOfResource));
                }
            }
            else
            {
                throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("OSType", string.Empty, this.nameOfResource));
            }

            // Set the Meter SubCategory for Compute Hours Cost component, Add to the List of resource components
            computeHoursComponent.MeterSubCategory = meterSubCategory;
            componentList.Add(computeHoursComponent);

            return(componentList);
        }
        /// <summary>
        /// Called for each time the timer ticks.
        /// </summary>
        /// <param name="State"></param>
        public void Run(object State)
        {
            try
            {
                if (_disabled)
                {
                    return;
                }

                if (_timerRunning)
                {
                    _timerLagging = true;
                    return;
                }

                _resetEvent.Reset();

                // BEGIN CODE
                List <UserCache> CacheList = BiosEmuThiago.GetGame().GetCacheManager().GetUserCache().ToList();
                if (CacheList.Count > 0)
                {
                    foreach (UserCache Cache in CacheList)
                    {
                        try
                        {
                            if (Cache == null)
                            {
                                continue;
                            }

                            UserCache Temp = null;

                            if (Cache.isExpired())
                            {
                                BiosEmuThiago.GetGame().GetCacheManager().TryRemoveUser(Cache.Id, out Temp);
                            }

                            Temp = null;
                        }
                        catch (Exception e)
                        {
                            ExceptionLogger.LogException(e);
                        }
                    }
                }

                CacheList = null;

                List <Habbo> CachedUsers = BiosEmuThiago.GetUsersCached().ToList();
                if (CachedUsers.Count > 0)
                {
                    foreach (Habbo Data in CachedUsers)
                    {
                        try
                        {
                            if (Data == null)
                            {
                                continue;
                            }

                            Habbo Temp = null;

                            if (Data.CacheExpired())
                            {
                                BiosEmuThiago.RemoveFromCache(Data.Id, out Temp);
                            }

                            if (Temp != null)
                            {
                                Temp.Dispose();
                            }

                            Temp = null;
                        }
                        catch (Exception e)
                        {
                            ExceptionLogger.LogException(e);
                        }
                    }
                }

                CachedUsers = null;
                // END CODE

                // Reset the values
                _timerRunning = false;
                _timerLagging = false;

                _resetEvent.Set();
            }
            catch (Exception e)
            {
                ExceptionLogger.LogException(e);
            }
        }
Exemple #20
0
        /// <summary>
        /// Gets the resource components for the Disks of the Virtual machine resource.
        /// </summary>
        /// <param name="diskURI">The URI of the disk</param>
        /// <param name="diskSize">The size of the Disk</param>
        /// <param name="storageResourceList">The list of storage resources in the ARM Template</param>
        /// <param name="isOSDisk">Set true for OS Disk and false for Data Disk</param>
        /// <returns> Returns the list of resource components </returns>
        private List <ResourceComponent> GetResourceComponentForDiskStorage(string diskURI, string diskSize, List <Resource> storageResourceList, bool isOSDisk)
        {
            List <ResourceComponent> storageComponentList            = new List <ResourceComponent>();
            List <ResourceComponent> storageDiskComponentList        = new List <ResourceComponent>();
            List <ResourceComponent> storageTransactionComponentList = new List <ResourceComponent>();

            // Get the Storage resource corresponding to the Storage of the Disk of the VM
            Resource diskStorageResource = PropertyHelper.SearchResourceInListByName(storageResourceList, diskURI);

            // Create the resource component for Storage of the VM disk, MeterSubCategory and MeterName will be set later
            ResourceComponent storageDiskComponent = new ResourceComponent
            {
                ResourceType     = this.resource.Type,
                MeterCategory    = StorageResourceConstants.StorageMeterCategory,
                MeterSubCategory = null,
                MeterName        = null,
                IsChargeable     = true
            };

            string storageAccountType = null;
            bool   isPremiumStorage   = false;

            StorageProperties storageProp = null;

            if (diskStorageResource != null && diskStorageResource.Properties != null)
            {
                // Get properties of the Storage resource
                storageProp = this.GetStoragePropertiesForStorageResource(diskStorageResource);
            }

            if (storageProp != null)
            {
                // Get Account Type of the Storage resource
                storageAccountType = PropertyHelper.GetValueIfVariableOrParam(storageProp.AccountType, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
            }

            // If Unable to fetch Storage Account Type, then, the template may be using existing storage account, Take Default Storage Account Type
            if (storageAccountType == null)
            {
                storageAccountType = StorageResourceConstants.StorageDefaultAccountType;
            }

            string meterSubCategory = null;

            // Set the Meter SubCategory based on the Storage Account Type
            if (StorageResourceConstants.StorageTypeAndMeterSubCategoryMap.TryGetValue(storageAccountType, out meterSubCategory))
            {
                storageDiskComponent.MeterSubCategory = meterSubCategory;
            }
            else
            {
                throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("StorageAccountType", storageAccountType, this.nameOfResource));
            }

            // Check if premium storage is used
            if (storageAccountType.Equals(StorageResourceConstants.StoragePremiumAccountType, StringComparison.OrdinalIgnoreCase))
            {
                isPremiumStorage = true;
            }

            double diskQuantity = 0;

            if (isOSDisk)
            {
                // Get default Storage for OS Disk from Constants/Config
                diskQuantity = isPremiumStorage ? VMResourceConstants.StoragePremiumOSDiskSize : VMResourceConstants.StorageOSDiskSize;
            }
            else
            {
                // Get the Storage size for the Data Disk
                double dataDiskQuantityValue = 0;
                if (diskSize != null && double.TryParse(diskSize, out dataDiskQuantityValue))
                {
                    if (isPremiumStorage)
                    {
                        // If Premium Storage, Map the disk size to the next greater available size of premium disk
                        for (int i = 0; i < StorageResourceConstants.StoragePremiumDiskValuesArray.Count(); i++)
                        {
                            double premiumDiskSizeValue = StorageResourceConstants.StoragePremiumDiskValuesArray[i];
                            if ((dataDiskQuantityValue <= premiumDiskSizeValue) || (i == StorageResourceConstants.StoragePremiumDiskValuesArray.Count() - 1))
                            {
                                diskQuantity = premiumDiskSizeValue;
                                break;
                            }
                        }
                    }
                    else
                    {
                        diskQuantity = dataDiskQuantityValue < VMResourceConstants.StorageDataDiskSize ? dataDiskQuantityValue : VMResourceConstants.StorageDataDiskSize;
                    }
                }
            }

            // Set the meter name for the Disk resource based on premium and standard
            if (isPremiumStorage)
            {
                string meterName = null;
                if (StorageResourceConstants.StoragePremiumDiskSizeAndMeterNameMap.TryGetValue(diskQuantity, out meterName))
                {
                    storageDiskComponent.MeterName = meterName;
                }
            }
            else
            {
                storageDiskComponent.MeterName = StorageResourceConstants.StorageMeterNameForVMDisk;
            }

            // Set the Quantity of the component to the Disk Size, Set 1 if its premium disk
            storageDiskComponent.Quantity = isPremiumStorage ? 1 : diskQuantity;
            storageComponentList.Add(storageDiskComponent);

            if (!isPremiumStorage)
            {
                // Add Storage transactions component if not a premium disk
                storageTransactionComponentList.Add(new ResourceComponent()
                {
                    ResourceType     = this.resource.Type,
                    MeterCategory    = StorageResourceConstants.DataManagementMeterCategory,
                    MeterSubCategory = StorageResourceConstants.DataManagementMeterSubCategoryForVMDisk,
                    MeterName        = StorageResourceConstants.DataManagementMeterNameForStorageTrans,
                    Quantity         = isOSDisk ? VMResourceConstants.DataManagementVMStorageOSDiskTrans : VMResourceConstants.DataManagementVMStorageDataDiskTrans,
                    IsChargeable     = true
                });
            }

            // Add the list of components obtained for the Storage Disk of the VM resource
            storageComponentList.AddRange(storageDiskComponentList);
            storageComponentList.AddRange(storageTransactionComponentList);
            return(storageComponentList);
        }
        public override void Process()
        {
            /*if (this.Device.State == Logic.Enums.State.IN_1VS1_BATTLE)
             * {
             *  Resources.Battles_V2.GetPlayer(this.Device.Player.Avatar.Battle_ID_V2, this.Device.Player.Avatar.UserId).Battle_Tick = CTick;
             * }*/

            if (Count > -1 && Constants.MaxCommand == 0 || Count > -1 && Count <= Constants.MaxCommand)
            {
                Device.Player.Tick();
                using (var Reader = new Reader(Commands))
                {
                    for (var _Index = 0; _Index < Count; _Index++)
                    {
                        var CommandID = Reader.ReadInt32();
                        if (CommandFactory.Commands.ContainsKey(CommandID))
                        {
                            var Command = Activator.CreateInstance(CommandFactory.Commands[CommandID], Reader,
                                                                   Device, CommandID) as Command;

                            if (Command != null)
                            {
#if DEBUG
                                Logger.Say("Battle Command " + CommandID + " has  been handled.", ConsoleColor.Blue);
#endif
                                try
                                {
                                    Command.Decode();
                                }
                                catch (Exception Exception)
                                {
                                    ExceptionLogger.Log(Exception,
                                                        $"Exception while decoding command {Command.GetType()}");
                                }

                                try
                                {
                                    Command.Process();
                                }
                                catch (Exception Exception)
                                {
                                    ExceptionLogger.Log(Exception,
                                                        $"Exception while executing command {Command.GetType()}");
                                }

                                Device.Last_Command = CommandID;
#if DEBUG
                                LCommands.Add(Command);
#endif
                            }
                        }
                        else
                        {
#if DEBUG
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Battle Command " + CommandID + " has not been handled.");
                            if (LCommands.Any())
                            {
                                Console.WriteLine("Previous command was " + LCommands.Last().Identifier + ". [" +
                                                  (_Index + 1) + " / " + Count + "]");
                            }
                            Console.ResetColor();
                            break;
#endif
                        }
                    }
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Gets the resource components for the Diagnostics if applicable/enabled for the Virtual machine resource.
        /// </summary>
        /// <returns> Returns the list of resource components </returns>
        private List <ResourceComponent> GetResourceComponentForDiagnostics()
        {
            List <ResourceComponent> componentList = new List <ResourceComponent>();

            string diagnosticsEnabled = null;

            if (this.prop.DiagnosticsProfile != null && this.prop.DiagnosticsProfile.BootDiagnostics != null)
            {
                // Fetch the Enabled property for Diagnostics of the VM resource
                diagnosticsEnabled = this.prop.DiagnosticsProfile.BootDiagnostics.Enabled;
            }

            if (diagnosticsEnabled != null && diagnosticsEnabled.Equals("true", StringComparison.OrdinalIgnoreCase))
            {
                // Get list of all storage resources in template
                List <Resource> storageResourceList   = this.template.Resources.FindAll(x => ARMResourceTypeConstants.ARMStorageResourceType.Equals(x.Type, StringComparison.OrdinalIgnoreCase));
                string          diagnosticsStorageURI = null;
                if (this.prop.DiagnosticsProfile != null && this.prop.DiagnosticsProfile.BootDiagnostics != null)
                {
                    // Fetch the URI of Diagnostics
                    diagnosticsStorageURI = this.prop.DiagnosticsProfile.BootDiagnostics.StorageUri;
                }

                Resource diagnosticsStorageResource = null;
                if (diagnosticsStorageResource != null)
                {
                    diagnosticsStorageResource = PropertyHelper.SearchResourceInListByName(storageResourceList, diagnosticsStorageURI);
                }

                string            storageAccountType = null;
                StorageProperties storageProp        = null;
                if (diagnosticsStorageResource != null && diagnosticsStorageResource.Properties != null)
                {
                    // Get the Properties of the Storage Resource associated with storing the Diagnostics of the VM
                    storageProp = this.GetStoragePropertiesForStorageResource(diagnosticsStorageResource);
                }

                if (storageProp != null)
                {
                    // Get the Storage Account Type
                    storageAccountType = PropertyHelper.GetValueIfVariableOrParam(storageProp.AccountType, this.template.Variables, this.template.Parameters, this.paramValue.Parameters);
                }

                // Use Default Storage Account Type, as template may be using existing storage account
                if (storageAccountType == null)
                {
                    storageAccountType = StorageResourceConstants.StorageDefaultAccountType;
                }

                if (storageAccountType != null && storageAccountType != StorageResourceConstants.StoragePremiumAccountType)
                {
                    // Create the resource component for Diagnostics
                    ResourceComponent diagnosticsComponent = new ResourceComponent
                    {
                        ResourceType     = this.resource.Type,
                        MeterCategory    = StorageResourceConstants.StorageMeterCategory,
                        MeterSubCategory = null,
                        MeterName        = StorageResourceConstants.StorageMeterNameForTable,
                        Quantity         = VMResourceConstants.StorageDiagnosticsTableSize,
                        IsChargeable     = true
                    };

                    string meterSubCategory = null;

                    // Set the Meter SubCategory based on the Storage Account Type
                    if (StorageResourceConstants.StorageTypeAndMeterSubCategoryMap.TryGetValue(storageAccountType, out meterSubCategory))
                    {
                        diagnosticsComponent.MeterSubCategory = meterSubCategory;
                    }
                    else
                    {
                        throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("StorageAccountType", storageAccountType, this.nameOfResource));
                    }

                    componentList.Add(diagnosticsComponent);

                    // Add the Storage Transactions component
                    componentList.Add(new ResourceComponent()
                    {
                        ResourceType     = this.resource.Type,
                        MeterCategory    = StorageResourceConstants.DataManagementMeterCategory,
                        MeterSubCategory = StorageResourceConstants.DataManagementMeterSubCategoryForVMDisk,
                        MeterName        = StorageResourceConstants.DataManagementMeterNameForStorageTrans,
                        Quantity         = VMResourceConstants.DataManagementVMDiagnosticsStorageTrans,
                        IsChargeable     = true
                    });
                }
                else
                {
                    throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("StorageAccountType for Diagnostics", storageAccountType, this.nameOfResource));
                }
            }

            return(componentList);
        }
Exemple #23
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            ExceptionDispatchInfo exceptionInfo;
            HttpControllerContext controllerContext = null;

            try
            {
                HttpControllerDescriptor controllerDescriptor = ControllerSelector.SelectController(request);
                if (controllerDescriptor == null)
                {
                    return(request.CreateErrorResponse(
                               HttpStatusCode.NotFound,
                               Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                               SRResources.NoControllerSelected));
                }

                IHttpController controller = controllerDescriptor.CreateController(request);
                if (controller == null)
                {
                    return(request.CreateErrorResponse(
                               HttpStatusCode.NotFound,
                               Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                               SRResources.NoControllerCreated));
                }

                controllerContext = CreateControllerContext(request, controllerDescriptor, controller);
                return(await controller.ExecuteAsync(controllerContext, cancellationToken));
            }
            catch (OperationCanceledException)
            {
                // Propogate the canceled task without calling exception loggers or handlers.
                throw;
            }
            catch (HttpResponseException httpResponseException)
            {
                return(httpResponseException.Response);
            }
            catch (Exception exception)
            {
                exceptionInfo = ExceptionDispatchInfo.Capture(exception);
            }

            Debug.Assert(exceptionInfo.SourceException != null);

            ExceptionContext exceptionContext = new ExceptionContext(
                exceptionInfo.SourceException,
                ExceptionCatchBlocks.HttpControllerDispatcher,
                request)
            {
                ControllerContext = controllerContext,
            };

            await ExceptionLogger.LogAsync(exceptionContext, cancellationToken);

            HttpResponseMessage response = await ExceptionHandler.HandleAsync(exceptionContext, cancellationToken);

            if (response == null)
            {
                exceptionInfo.Throw();
            }

            return(response);
        }
Exemple #24
0
 public bool LogException(ExceptionModel dto)
 {
     ExceptionLogger.LogException(dto.Message, dto.MethodName, dto.UserId);
     return(true);
 }
        public ApiResponse GetException([FromRoute] string id, [FromQuery(Name = "parent")] string parentId)
        {
            try
            {
                ExceptionWrapper ret = null;

                if (!string.IsNullOrWhiteSpace(parentId))
                {
                    var parent = ExceptionLogger.GetException(parentId);

                    if (parent == null)
                    {
                        return(ApiResponse.ExclamationModal($"A parent exception with id \"{parentId}\" could not be found."));
                    }

                    var child = parent.GetRelated(id);

                    if (child == null)
                    {
                        return(ApiResponse.ExclamationModal($"An exception with id \"{id}\" could not be found."));
                    }

                    ret = child;
                }
                else
                {
                    var ex = ExceptionLogger.GetException(id);

                    if (ex == null)
                    {
                        ex = ExceptionLogger.DeepFindRelated(id);
                    }

                    if (ex == null)
                    {
                        return(ApiResponse.ExclamationModal($"An exception with id \"{id}\" could not be found."));
                    }

                    ret = ex;
                }

                return(ApiResponse.Payload(new
                {
                    ret.appTitle,
                    ret.appVersion,
                    ret.created,
                    ret.errorCode,
                    ret.execOptions,
                    id = ret.sId,
                    ret.innerException,
                    ret.level,
                    ret.line,
                    ret.message,
                    ret.procedure,
                    ret.server,
                    //?ret.sqlErrorType,
                    ret.stackTrace,
                    ret.state,
                    ret.type,
                    ret.additionalInfo
                }));
            }
            catch (Exception ex)
            {
                SessionLog.Exception(ex);
                return(ApiResponse.Exception(ex));
            }
        }
Exemple #26
0
        public bool TryAuthenticate(string authTicket)
        {
            try
            {
                UserData userData = UserDataFactory.GetUserData(authTicket, out byte errorCode);
                if (errorCode == 1 || errorCode == 2)
                {
                    Disconnect();
                    return(false);
                }

                #region Ban Checking
                //Let's have a quick search for a ban before we successfully authenticate..
                if (!string.IsNullOrEmpty(MachineId))
                {
                    if (PlusEnvironment.GetGame().GetModerationManager().IsBanned(MachineId, out _))
                    {
                        if (PlusEnvironment.GetGame().GetModerationManager().MachineBanCheck(MachineId))
                        {
                            Disconnect();
                            return(false);
                        }
                    }
                }

                if (userData.user != null)
                {
                    if (PlusEnvironment.GetGame().GetModerationManager().IsBanned(userData.user.Username, out _))
                    {
                        if (PlusEnvironment.GetGame().GetModerationManager().UsernameBanCheck(userData.user.Username))
                        {
                            Disconnect();
                            return(false);
                        }
                    }
                }
                #endregion

                if (userData.user == null) //Possible NPE
                {
                    return(false);
                }

                PlusEnvironment.GetGame().GetClientManager().RegisterClient(this, userData.UserId, userData.user.Username);
                _habbo = userData.user;
                if (_habbo != null)
                {
                    userData.user.Init(this, userData);

                    SendPacket(new AuthenticationOKComposer());
                    SendPacket(new AvatarEffectsComposer(_habbo.Effects().GetAllEffects));
                    SendPacket(new NavigatorSettingsComposer(_habbo.HomeRoom));
                    SendPacket(new FavouritesComposer(userData.user.FavoriteRooms));
                    SendPacket(new FigureSetIdsComposer(_habbo.GetClothing().GetClothingParts));
                    SendPacket(new UserRightsComposer(_habbo.Rank));
                    SendPacket(new AvailabilityStatusComposer());
                    SendPacket(new AchievementScoreComposer(_habbo.GetStats().AchievementPoints));
                    SendPacket(new BuildersClubMembershipComposer());
                    SendPacket(new CfhTopicsInitComposer(PlusEnvironment.GetGame().GetModerationManager().UserActionPresets));

                    SendPacket(new BadgeDefinitionsComposer(PlusEnvironment.GetGame().GetAchievementManager().Achievements));
                    SendPacket(new SoundSettingsComposer(_habbo.ClientVolume, _habbo.ChatPreference, _habbo.AllowMessengerInvites, _habbo.FocusPreference, FriendBarStateUtility.GetInt(_habbo.FriendbarState)));
                    //SendMessage(new TalentTrackLevelComposer());

                    if (GetHabbo().GetMessenger() != null)
                    {
                        GetHabbo().GetMessenger().OnStatusChanged(true);
                    }

                    if (!string.IsNullOrEmpty(MachineId))
                    {
                        if (_habbo.MachineId != MachineId)
                        {
                            using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().GetQueryReactor())
                            {
                                dbClient.SetQuery("UPDATE `users` SET `machine_id` = @MachineId WHERE `id` = @id LIMIT 1");
                                dbClient.AddParameter("MachineId", MachineId);
                                dbClient.AddParameter("id", _habbo.Id);
                                dbClient.RunQuery();
                            }
                        }

                        _habbo.MachineId = MachineId;
                    }

                    if (PlusEnvironment.GetGame().GetPermissionManager().TryGetGroup(_habbo.Rank, out PermissionGroup group))
                    {
                        if (!String.IsNullOrEmpty(group.Badge))
                        {
                            if (!_habbo.GetBadgeComponent().HasBadge(group.Badge))
                            {
                                _habbo.GetBadgeComponent().GiveBadge(group.Badge, true, this);
                            }
                        }
                    }

                    if (PlusEnvironment.GetGame().GetSubscriptionManager().TryGetSubscriptionData(_habbo.VIPRank, out SubscriptionData subData))
                    {
                        if (!String.IsNullOrEmpty(subData.Badge))
                        {
                            if (!_habbo.GetBadgeComponent().HasBadge(subData.Badge))
                            {
                                _habbo.GetBadgeComponent().GiveBadge(subData.Badge, true, this);
                            }
                        }
                    }

                    if (!PlusEnvironment.GetGame().GetCacheManager().ContainsUser(_habbo.Id))
                    {
                        PlusEnvironment.GetGame().GetCacheManager().GenerateUser(_habbo.Id);
                    }

                    _habbo.Look = PlusEnvironment.GetFigureManager().ProcessFigure(_habbo.Look, _habbo.Gender, _habbo.GetClothing().GetClothingParts, true);
                    _habbo.InitProcess();

                    if (userData.user.GetPermissions().HasRight("mod_tickets"))
                    {
                        SendPacket(new ModeratorInitComposer(
                                       PlusEnvironment.GetGame().GetModerationManager().UserMessagePresets,
                                       PlusEnvironment.GetGame().GetModerationManager().RoomMessagePresets,
                                       PlusEnvironment.GetGame().GetModerationManager().GetTickets));
                    }

                    if (PlusEnvironment.GetSettingsManager().TryGetValue("user.login.message.enabled") == "1")
                    {
                        SendPacket(new MotdNotificationComposer(PlusEnvironment.GetLanguageManager().TryGetValue("user.login.message")));
                    }

                    PlusEnvironment.GetGame().GetRewardManager().CheckRewards(this);
                    return(true);
                }
            }
            catch (Exception e)
            {
                ExceptionLogger.LogException(e);
            }
            return(false);
        }
        /// <summary>
        /// Gets the resource components for the resources in an ARM template
        /// </summary>
        /// <param name="template">The object containing the ARM Template</param>
        /// <param name="paramvalue">The object containing the values in the Parameter file</param>
        /// <param name="location">The Azure Location</param>
        /// <param name="cspCreds">CSP Account credentials object. A token will be generated using these credentials and used for making the online ARM API call</param>
        /// <param name="log">The object that will contain the exception messages</param>
        /// <returns> Returns the list of resource components</returns>
        public static List <ResourceComponent> GetResourceComponentsForTemplate(ARMTemplate template, ARMParamValue paramvalue, string location, CSPAccountCreds cspCreds, out StringBuilder log)
        {
            List <ResourceComponent> components = new List <ResourceComponent>();

            log = new StringBuilder(string.Empty);
            string locationAsPerARMSpecs = null;

            try
            {
                // Fetch the location as per ARM Specs from the mapping
                if (!LocationConstants.LocationAsPerARMSpecsMap.TryGetValue(location, out locationAsPerARMSpecs))
                {
                    throw new Exception(ExceptionLogger.GenerateLoggerTextForInvalidField("Location", location, "ARMTemplate"));
                }

                if (template.Resources != null && template.Resources.Count > 0)
                {
                    // Loop thru each resource in the ARM Template
                    foreach (Resource res in template.Resources)
                    {
                        ARMResourceType resType        = null;
                        string          nameOfResource = string.Empty;
                        if (res != null && res.Name != null)
                        {
                            // Fetch the name of the current resource
                            nameOfResource = PropertyHelper.GetValueIfVariableOrParam(res.Name, template.Variables, template.Parameters, paramvalue.Parameters);
                        }

                        // Check if resource or resource type is not null
                        if (res != null && res.Type != null)
                        {
                            // Check if resource type is in supported by this application
                            resType = ResourceTypeHelper.ResourceTypeList.Find(x => res.Type.Equals(x.ARMResourceTypeText, StringComparison.OrdinalIgnoreCase));

                            if (resType != null)
                            {
                                List <ResourceComponent> currentResourceComponents = new List <ResourceComponent>();

                                // Check if the resource type of the current resource does not have chargeable components
                                if (!resType.HasChargableComponents)
                                {
                                    currentResourceComponents.Add(new ResourceComponent()
                                    {
                                        ResourceType = res.Type,
                                        Quantity     = 0,
                                        IsChargeable = false
                                    });
                                }
                                else
                                {
                                    IComponentFetcher resCompFetcher = null;

                                    // Create the appropriate object to fetch the components of the resource
                                    switch (resType.ARMResourceTypeText)
                                    {
                                    // Public IP Resource
                                    case ARMResourceTypeConstants.ARMPublicIPResourceType:
                                        resCompFetcher = new PublicIPComponentFetcher();
                                        break;

                                    // Virtual Machine Resource
                                    case ARMResourceTypeConstants.ARMVMResourceType:
                                        resCompFetcher = new VMComponentFetcher();
                                        break;

                                    default:

                                        // Has Chargable Components but not yet supported
                                        log.AppendLine(ExceptionLogger.GenerateLoggerTextForUnSupportedResource(res.Type));
                                        break;
                                    }

                                    StringBuilder resLog = new StringBuilder(string.Empty);

                                    // Call the method to fetch the resource components
                                    List <ResourceComponent> resComp = resCompFetcher.GetResourceComponents(res, template, paramvalue, locationAsPerARMSpecs, cspCreds, out resLog);
                                    if (resLog != null)
                                    {
                                        log.Append(resLog);
                                    }

                                    if (resComp != null && resComp.Count > 0)
                                    {
                                        currentResourceComponents.AddRange(resComp);
                                    }
                                    else
                                    {
                                        log.AppendLine(ExceptionLogger.GenerateLoggerTextForNoResourceOutput(nameOfResource));
                                    }
                                }

                                foreach (ResourceComponent component in currentResourceComponents)
                                {
                                    component.ResourceName = nameOfResource;
                                }

                                components.AddRange(currentResourceComponents);
                            }
                            else
                            {
                                log.AppendLine(ExceptionLogger.GenerateLoggerTextForUnSupportedResource(res.Type));
                            }
                        }
                        else
                        {
                            if (res != null)
                            {
                                // Type of the resourse is missing/null, generate the message
                                log.AppendLine(ExceptionLogger.GenerateLoggerTextForMissingField("Type", nameOfResource));
                            }
                            else
                            {
                                // Resourse is missing/null, generate the message
                                log.AppendLine(ExceptionLogger.GenerateLoggerTextForMissingField("Resource", "ARMTemplate"));
                            }
                        }
                    }
                }
                else
                {
                    // Resources section in ARM template is missing/null, generate a message
                    throw new Exception(ExceptionLogger.GenerateLoggerTextForMissingField("RESOURCES", "ARMTemplate"));
                }
            }
            catch (Exception ex)
            {
                // Catch any exception and log the message
                components = null;
                log.AppendLine(ex.Message);
            }

            // Return the list of components obtained for the resources in the ARM template
            return(components);
        }
        /// <summary>
        /// GreatOutdoors page
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns></returns>
        static async Task Main(string[] args)
        {
            try
            {
                int option = 1;
                do
                {
                    int internalChoice = -2;
                    WriteLine("===============GREAT OUTDOORS MANAGEMENT SYSTEM=========================");
                    WriteLine("1.Existing User\n2.Retailer Registration");
                    WriteLine("Enter your choice");
                    int  choice;
                    bool isValidChoice = int.TryParse(ReadLine(), out choice);
                    if (isValidChoice)
                    {
                        switch (choice)
                        {
                        case 1:
                            do
                            {
                                //Invoke Login Screen
                                (UserType userType, IUser currentUser) = await ShowLoginScreen();

                                //Set current user details into CommonData (global data)
                                CommonData.CurrentUser     = currentUser;
                                CommonData.CurrentUserType = userType;

                                //Invoke User's Menu
                                if (userType == UserType.Admin)
                                {
                                    internalChoice = await AdminPresentation.AdminUserMenu();
                                }
                                else if (userType == UserType.SalesPerson)
                                {
                                    internalChoice = await SalesPersonPresentation.SalesPersonMenu();
                                }
                                else if (userType == UserType.Retailer)
                                {
                                    internalChoice = await RetailerPresentation.RetailerUserMenu();
                                }
                                else if (userType == UserType.Anonymous)
                                {
                                }
                            } while (internalChoice != -1);
                            break;

                        case 2:
                        {
                            await AddRetailer();
                        }
                        break;

                        default:
                        {
                            WriteLine("Invalid choice");
                        }
                        break;
                        }
                    }
                } while (option == 1);
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogException(ex);
                WriteLine(ex.Message);
            }

            WriteLine("Thank you!");
            ReadKey();
        }
Exemple #29
0
        /// <summary>
        /// This method 'Save Register User' will save Register user data
        /// </summary>
        /// <param name="SaveSignUpUserInfo"></param>
        /// <returns>Returns 1 if Success, 0 for failure</returns>
        public bool SaveSignUpUserInfo(TruflUserInputDTO registerUserInfo)
        {
            try
            {
                var dtClient = new DataTable();

                dtClient.Columns.Add("TruflUserID", typeof(Int32));
                dtClient.Columns.Add("RestaurantID", typeof(Int32));
                dtClient.Columns.Add("FullName", typeof(string));
                dtClient.Columns.Add("Email", typeof(string));
                dtClient.Columns.Add("pic", typeof(Byte[]));
                dtClient.Columns.Add("PhoneNumber", typeof(string));
                dtClient.Columns.Add("Password", typeof(string));
                //dtClient.Columns.Add("Salt", typeof(string));
                dtClient.Columns.Add("DOB", typeof(DateTime));
                dtClient.Columns.Add("ActiveInd", typeof(char));
                dtClient.Columns.Add("RestaurantEmpInd", typeof(Int32));
                dtClient.Columns.Add("TruflMemberType", typeof(string));
                dtClient.Columns.Add("TruflRelationship", typeof(Int32));
                dtClient.Columns.Add("TruflshareCode", typeof(string));
                dtClient.Columns.Add("ReferTruflUserID", typeof(Int32));
                dtClient.Columns.Add("ModifiedDate", typeof(DateTime));
                dtClient.Columns.Add("ModifiedBy", typeof(Int32));
                dtClient.Columns.Add("Waited", typeof(TimeSpan));

                //dtClient.Columns.Add("LoggedInUserType", typeof(string));



                dtClient.Rows.Add(
                    DBNull.Value,
                    DBNull.Value,
                    registerUserInfo.FullName,
                    registerUserInfo.Email,
                    DBNull.Value,
                    registerUserInfo.PhoneNumber,
                    registerUserInfo.Password,
                    //DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value,
                    DBNull.Value
                    );

                string connectionString = ConfigurationManager.AppSettings["TraflConnection"];
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("spSaveTruflUser", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        SqlParameter tvpParam = cmd.Parameters.AddWithValue("@TruflUserTY", dtClient);
                        tvpParam.SqlDbType = SqlDbType.Structured;
                        SqlParameter tvparam1 = cmd.Parameters.AddWithValue("@LoggedInUserType", registerUserInfo.LoggedInUserType);

                        SqlParameter pvNewId = new SqlParameter();
                        pvNewId.ParameterName = "@RetVal";
                        pvNewId.DbType        = DbType.Int32;
                        pvNewId.Direction     = ParameterDirection.Output;
                        cmd.Parameters.Add(pvNewId);

                        int status = cmd.ExecuteNonQuery();
                        if (status == 0)
                        {
                            return(false);
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var s = ex.Message;
                ExceptionLogger.WriteToErrorLogFile(ex);
                return(false);
            }
        }
Exemple #30
0
        public static async Task Main(string[] args)
        {
            try
            {
                int choice;
                do
                {
                    int internalChoice = 0;
                    WriteLine("*****************ECOMMERCE MANAGEMENT SYSTEM********************");
                    WriteLine("1.Existing User\n2.Customer Registration\n3.Exit");
                    WriteLine("Enter your choice");
                    bool isValidChoice = int.TryParse(ReadLine(), out choice);
                    if (isValidChoice)
                    {
                        switch (choice)
                        {
                        case 1:
                            do
                            {
                                (UserType userType, IUser currentUser) = await ShowLoginScreen();

                                UserData.CurrentUser     = currentUser;
                                UserData.CurrentUserType = userType;
                                if (userType == UserType.Admin)
                                {
                                    internalChoice = await AdminPresentation.AdminUserMenu();
                                }
                                else if (userType == UserType.Customer)
                                {
                                    internalChoice = await CustomerPresentation.CustomerUserMenu();
                                }
                                else if (userType == UserType.Anonymous)
                                {
                                    internalChoice = -2;
                                }
                            } while (internalChoice == -2);
                            break;

                        case 2:
                            await AddCustomer();

                            break;

                        case 3:
                            break;

                        default:
                            WriteLine("Invalid choice");
                            break;
                        }
                    }
                    else
                    {
                        WriteLine("Choice should be a number");
                    }
                    WriteLine("Thank you! Visit again!");
                } while (choice != 3);
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogException(ex);
                WriteLine(ex.Message);
            }
            ReadKey();
        }