/// <summary> /// Creates an instance of <see cref="SecurityUserControl"/> class. /// </summary> public SecurityUserControl() { InitializeComponent(); m_userAccounts = new UserAccounts(1, false); m_securityGroups = new SecurityGroups(1, false); m_applicationRoles = new ApplicationRoles(1, true); RefreshBindings(); this.Unloaded += new RoutedEventHandler(SecurityUserControl_Unloaded); m_userAccounts.BeforeSave += new System.ComponentModel.CancelEventHandler(m_userAccounts_BeforeSave); m_userAccounts.Saved += new System.EventHandler(m_userAccounts_Changed); m_userAccounts.Deleted += new System.EventHandler(m_userAccounts_Changed); m_securityGroups.Saved += new System.EventHandler(m_securityGroups_Changed); m_securityGroups.Deleted += new System.EventHandler(m_securityGroups_Changed); m_invalidPasswordMessage = new StringBuilder(); m_invalidPasswordMessage.Append("Password does not meet the following criteria:"); m_invalidPasswordMessage.AppendLine(); m_invalidPasswordMessage.Append("- Password must be at least 8 characters"); m_invalidPasswordMessage.AppendLine(); m_invalidPasswordMessage.Append("- Password must contain at least 1 digit"); m_invalidPasswordMessage.AppendLine(); m_invalidPasswordMessage.Append("- Password must contain at least 1 upper case letter"); m_invalidPasswordMessage.AppendLine(); m_invalidPasswordMessage.Append("- Password must contain at least 1 lower case letter"); }
public static UserAccounts GetUsersInRole(int roleID) { UserAccounts uars = null; // get a configured DbCommand object DbCommand comm = DbAct.CreateCommand(); // set the stored procedure name comm.CommandText = "up_GetUsersInRole"; ADOExtenstion.AddParameter(comm, "roleID", roleID); // execute the stored procedure DataTable dt = DbAct.ExecuteSelectCommand(comm); // was something returned? if (dt != null && dt.Rows.Count > 0) { uars = new UserAccounts(); UserAccount art = null; foreach (DataRow dr in dt.Rows) { art = new UserAccount(dr); uars.Add(art); } } return uars; }
/// <summary> /// Gets all the users in a role /// </summary> /// <param name="roleID"></param> /// <returns></returns> public static IList<UserAccount> GetUsersInRole(int roleID) { UserAccounts uars = null; DbCommand comm = DbAct.CreateCommand(); comm.CommandText = "up_GetUsersInRole"; comm.AddParameter("roleID", roleID); DataTable dt = DbAct.ExecuteSelectCommand(comm); if (dt == null || dt.Rows.Count <= 0) return uars; uars = new UserAccounts(); uars.AddRange(from DataRow dr in dt.Rows select new UserAccount(dr)); return uars; }
/// <summary> /// Creates an instance of <see cref="SecurityUserControl"/> class. /// </summary> public SecurityUserControl() { ConfigurationFile config; CategorizedSettingsElementCollection settings; InitializeComponent(); config = ConfigurationFile.Current; settings = config.Settings["securityProvider"]; // Set up defaults for config file settings m_passwordRequirementsRegex = AdoSecurityProvider.DefaultPasswordRequirementsRegex; m_passwordRequirementsError = AdoSecurityProvider.DefaultPasswordRequirementsError; // Make sure default config file settings exist settings.Add("PasswordRequirementsRegex", m_passwordRequirementsRegex, "Regular expression used to validate new passwords for database users."); settings.Add("PasswordRequirementsError", m_passwordRequirementsError, "Error message to be displayed when new database user password fails regular expression test."); // Read settings from config file m_passwordRequirementsRegex = settings["PasswordRequirementsRegex"].ValueAs(m_passwordRequirementsRegex); m_passwordRequirementsError = settings["PasswordRequirementsError"].ValueAs(m_passwordRequirementsError); // Initialize view models m_userAccounts = new UserAccounts(1, false); m_securityGroups = new SecurityGroups(1, false); m_applicationRoles = new ApplicationRoles(1, true); RefreshBindings(); // Attach to events Unloaded += SecurityUserControl_Unloaded; m_userAccounts.BeforeSave += m_userAccounts_BeforeSave; m_userAccounts.Saved += m_userAccounts_Changed; m_userAccounts.Deleted += m_userAccounts_Changed; m_securityGroups.Saved += m_securityGroups_Changed; m_securityGroups.Deleted += m_securityGroups_Changed; }
public ActionResult Online() { _uas = new UserAccounts(); _uas.GetOnlineUsers(); _uas.Sort( (p1, p2) => p2.LastActivityDate.CompareTo(p1.LastActivityDate)); return View(_uas); }
private void GetUserContacts(ProfileModel model) { var ucons = new UserConnections(); ucons.GetUserConnections(_ua.UserAccountID); ucons.Shuffle(); var irlContacts = new UserAccounts(); var cyberAssociates = new UserAccounts(); foreach (UserConnection uc1 in ucons.Where(uc1 => uc1.IsConfirmed)) { UserAccount userCon; switch (uc1.StatusType) { case 'C': if (cyberAssociates.Count >= Maxcountusers) continue; userCon = uc1.ToUserAccountID != _ua.UserAccountID ? new UserAccount(uc1.ToUserAccountID) : new UserAccount(uc1.FromUserAccountID); cyberAssociates.Add(userCon); break; case 'R': if (irlContacts.Count >= Maxcountusers) continue; userCon = uc1.ToUserAccountID != _ua.UserAccountID ? new UserAccount(uc1.ToUserAccountID) : new UserAccount(uc1.FromUserAccountID); irlContacts.Add(userCon); break; } } if (irlContacts.Count > 0) { model.IRLFriendCount = irlContacts.Count; } if (cyberAssociates.Count > 0) { model.CyberFriendCount = cyberAssociates.Count; } }
private void LoadVisitorsView(string userName) { int maxcountusers = 100; mu = Membership.GetUser(); uad = new UserAccountDetail(); ua = new UserAccount(userName); uad.GetUserAccountDeailForUser(ua.UserAccountID); UserAccountDetail uadLooker = new UserAccountDetail(); uadLooker.GetUserAccountDeailForUser(Convert.ToInt32(mu.ProviderUserKey)); if (mu != null && ua.UserAccountID > 0 && uad.EnableProfileLogging && uad.EnableProfileLogging) { ArrayList al = ProfileLog.GetRecentProfileViews(ua.UserAccountID); if (al != null && al.Count > 0) { UserAccounts uas = new UserAccounts(); UserAccount viewwer = null; foreach (int ID in al) { viewwer = new UserAccount(ID); if (!viewwer.IsLockedOut && viewwer.IsApproved) { uad = new UserAccountDetail(); uad.GetUserAccountDeailForUser(ID); if (uad.EnableProfileLogging == false) continue; if (uas.Count >= maxcountusers) break; uas.Add(viewwer); } } ViewBag.TheViewers = uas.ToUnorderdList; } } }
public ActionResult Index() { // CONTESTS Contest cndss = Contest.GetCurrentContest(); ContestVideos cvids = new ContestVideos(); Videos vidsInContest = new Videos(); BootBaronLib.AppSpec.DasKlub.BOL.Video vid2 = null; foreach (ContestVideo cv1 in cvids) { vid2 = new BootBaronLib.AppSpec.DasKlub.BOL.Video(cv1.VideoID); vidsInContest.Add(vid2); } vidsInContest.Sort(delegate(BootBaronLib.AppSpec.DasKlub.BOL.Video p1, BootBaronLib.AppSpec.DasKlub.BOL.Video p2) { return p2.PublishDate.CompareTo(p1.PublishDate); }); SongRecords sngrcds3 = new SongRecords(); SongRecord sng3 = new SongRecord(); foreach (BootBaronLib.AppSpec.DasKlub.BOL.Video v1 in vidsInContest) { sng3 = new SongRecord(v1); sngrcds3.Add(sng3); } ViewBag.ContestVideoList = sngrcds3.VideosList(); ViewBag.CurrentContest = cndss; // PhotoItems pitms = new PhotoItems(); pitms.UseThumb = true; pitms.ShowTitle = false; pitms.GetPhotoItemsPageWise(1, 4); ViewBag.PhotoList = pitms.ToUnorderdList; Contents cnts = new Contents(); cnts.GetContentPageWiseAll(1, 3); ViewBag.RecentArticles = cnts.ToUnorderdList; UserAccounts uas = new UserAccounts(); uas.GetNewestUsers(); ViewBag.NewestUsers = uas.ToUnorderdList; Videos newestVideos = new Videos(); newestVideos.GetMostRecentVideos(); SongRecords newSongs = new SongRecords(); SongRecord sng1 = null; foreach (BootBaronLib.AppSpec.DasKlub.BOL.Video v1 in newestVideos) { sng1 = new SongRecord(v1); newSongs.Add(sng1); } ViewBag.NewestVideos = newSongs.VideosList(); BootBaronLib.AppSpec.DasKlub.BOL.Video vid = new BootBaronLib.AppSpec.DasKlub.BOL.Video(BootBaronLib.AppSpec.DasKlub.BOL.Video.RandomVideoIDVideo()); ViewBag.RandomVideoKey = vid.ProviderKey; ///video submit MultiProperties addList = null; PropertyType propTyp = null; MultiProperties mps = null; // video typesa propTyp = new PropertyType(SiteEnums.PropertyTypeCode.VIDTP); mps = new MultiProperties(propTyp.PropertyTypeID); mps.Sort(delegate(MultiProperty p1, MultiProperty p2) { return p1.DisplayName.CompareTo(p2.DisplayName); }); ViewBag.VideoTypes = mps; // person types propTyp = new PropertyType(SiteEnums.PropertyTypeCode.HUMAN); mps = new MultiProperties(propTyp.PropertyTypeID); mps.Sort(delegate(MultiProperty p1, MultiProperty p2) { return p1.DisplayName.CompareTo(p2.DisplayName); }); ViewBag.PersonTypes = mps; //// footage types propTyp = new PropertyType(SiteEnums.PropertyTypeCode.FOOTG); mps = new MultiProperties(propTyp.PropertyTypeID); mps.Sort(delegate(MultiProperty p1, MultiProperty p2) { return p1.DisplayName.CompareTo(p2.DisplayName); }); addList = new MultiProperties(); ViewBag.FootageTypes = mps; return View(); }
private void LoadVisitorsView(string userName) { const int maxcountusers = 100; _uad = new UserAccountDetail(); if (userName != null) _ua = new UserAccount(userName); _uad.GetUserAccountDeailForUser(_ua.UserAccountID); var uadLooker = new UserAccountDetail(); if (_mu == null) return; uadLooker.GetUserAccountDeailForUser(Convert.ToInt32(_mu.ProviderUserKey)); if (_mu == null || _ua.UserAccountID <= 0 || !_uad.EnableProfileLogging || !_uad.EnableProfileLogging) return; ArrayList al = ProfileLog.GetRecentProfileViews(_ua.UserAccountID); if (al == null || al.Count <= 0) return; var uas = new UserAccounts(); foreach (int id in al) { var viewwer = new UserAccount(id); if (viewwer.IsLockedOut || !viewwer.IsApproved) continue; _uad = new UserAccountDetail(); _uad.GetUserAccountDeailForUser(id); if (_uad.EnableProfileLogging == false) continue; if (uas.Count >= maxcountusers) break; uas.Add(viewwer); } ViewBag.TheViewers = uas.ToUnorderdList; }
public void ProcessRequest(HttpContext context) { // context.Response.ContentType = "text/plain"; // context.Response.CacheControl = "no-cache"; // context.Response.AddHeader("Pragma", "no-cache"); // //context.Response.AddHeader("Pragma", "no-store"); // //context.Response.AddHeader("cache-control", "no-cache"); //context.Response.Cache.SetCacheability(HttpCacheability.NoCache); // context.Response.Cache.SetNoServerCaching(); if (string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()])) return; SiteEnums.QueryStringNames ptyc = (SiteEnums.QueryStringNames)Enum.Parse(typeof(SiteEnums.QueryStringNames), context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()]); // Dictionary<string, Subgurim.Chat.Usuario> usrrs = null; StringBuilder sb = null; MembershipUser mu = null; switch (ptyc) { case SiteEnums.QueryStringNames.status_update: #region status_update string key = context.Request.QueryString[SiteEnums.QueryStringNames.status_update_id.ToString()]; if (string.IsNullOrEmpty(key)) { key = context.Request.QueryString[SiteEnums.QueryStringNames.most_applauded_status_update_id.ToString()]; } int statusUpdateID = Convert.ToInt32(key); StatusUpdate statup = null; if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()])) { mu = Membership.GetUser(); Acknowledgement ack = new Acknowledgement(); ack.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); ack.UserAccountID = Convert.ToInt32(mu.ProviderUserKey); ack.AcknowledgementType = Convert.ToChar(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()]); ack.StatusUpdateID = statusUpdateID; statup = new StatusUpdate(statusUpdateID); if (!Acknowledgement.IsUserAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey))) { ack.Create(); StatusUpdateNotification sun = new StatusUpdateNotification(); if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { // sun.GetStatusUpdateNotificationForUserStatus(Convert.ToInt32(mu.ProviderUserKey), statusUpdateID, SiteEnums.ResponseType.A); sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.A); } else if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.B.ToString())) { //sun.GetStatusUpdateNotificationForUserStatus(Convert.ToInt32(mu.ProviderUserKey), statusUpdateID, SiteEnums.ResponseType.B); sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.B); } if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID) { sun.UserAccountID = statup.UserAccountID; SiteEnums.ResponseType rspType = SiteEnums.ResponseType.U; if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { rspType = SiteEnums.ResponseType.A; sun.ResponseType = Convert.ToChar(rspType.ToString()); } else { rspType = SiteEnums.ResponseType.B; sun.ResponseType = Convert.ToChar(rspType.ToString()); } sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey); if (sun.StatusUpdateNotificationID == 0) { sun.IsRead = false; sun.Create(); } else { sun.IsRead = false; sun.Update(); } SendNotificationEmail(statup.UserAccountID, rspType, sun.StatusUpdateID); } context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statup.StatusAcknowledgements) + @"""}"); } else { // reverse ack.GetAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey)); ack.Delete(); // TODO: DELETE NOTIFICATION context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statup.StatusAcknowledgements) + @"""}"); } } else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()])) { mu = Membership.GetUser(); StatusCommentAcknowledgement ack = new StatusCommentAcknowledgement(); ack.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); ack.UserAccountID = Convert.ToInt32(mu.ProviderUserKey); ack.AcknowledgementType = Convert.ToChar(context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()]); ack.StatusCommentID = statusUpdateID; // this is really the commentID (or should be) StatusComment statcomup = new StatusComment(statusUpdateID); statup = new StatusUpdate(statcomup.StatusUpdateID); if (!StatusCommentAcknowledgement.IsUserCommentAcknowledgement(statcomup.StatusCommentID, Convert.ToInt32(mu.ProviderUserKey))) { ack.Create(); StatusUpdateNotification sun = new StatusUpdateNotification(); if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { sun.GetStatusUpdateNotificationForUserStatus(statcomup.UserAccountID, statcomup.StatusUpdateID, SiteEnums.ResponseType.A); } else { sun.GetStatusUpdateNotificationForUserStatus(statcomup.UserAccountID, statcomup.StatusUpdateID, SiteEnums.ResponseType.B); } if (Convert.ToInt32(mu.ProviderUserKey) != statcomup.UserAccountID) { sun.UserAccountID = statcomup.UserAccountID; SiteEnums.ResponseType rspType = SiteEnums.ResponseType.U; if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { rspType = SiteEnums.ResponseType.A; sun.ResponseType = Convert.ToChar(rspType.ToString()); } else { rspType = SiteEnums.ResponseType.B; sun.ResponseType = Convert.ToChar(rspType.ToString()); } if (sun.StatusUpdateNotificationID == 0) { sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.IsRead = false; sun.Create(); } else { sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.IsRead = false; sun.Update(); } SendNotificationEmail(statup.UserAccountID, rspType, sun.StatusUpdateID); } context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statcomup.StatusCommentAcknowledgementsOptions) + @"""}"); } else { // reverse ack.GetCommentAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey)); ack.Delete(); // TODO: DELETE NOTIFICATION context.Response.Write(@"{""StatusAcks"": """ + HttpUtility.HtmlEncode(statcomup.StatusCommentAcknowledgementsOptions) + @"""}"); } } else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]) && !string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]) ) { mu = Membership.GetUser(); if (mu == null) return; StatusComment statCom = new StatusComment(); statCom.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); statCom.Message = HttpUtility.HtmlEncode(context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]); statCom.StatusUpdateID = statusUpdateID; statCom.UserAccountID = Convert.ToInt32(mu.ProviderUserKey); //statCom.GetStatusCommentMessage(); // ? ignore this duplicate now // TODO: CHECK IF THERE IS A RECENT MESSAGE THAT IS THE SAME if (statCom.StatusCommentID == 0) { //BUG: THERE IS AN EVENT HANDLER THAT HAS QUEUED UP TOO MANY StatusUpdate suLast = new StatusUpdate(); suLast.GetMostRecentUserStatus(Convert.ToInt32(mu.ProviderUserKey)); if (suLast.Message.Trim() != statCom.Message.Trim() || (suLast.Message.Trim() == statCom.Message.Trim() && suLast.StatusUpdateID != statCom.StatusUpdateID)) { statCom.Create(); } statup = new StatusUpdate(statusUpdateID); // create a status update notification for the post maker and all commenters StatusUpdateNotification sun = null; if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID) { sun = new StatusUpdateNotification(); sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.C); if (sun.StatusUpdateNotificationID == 0) { sun.ResponseType = Convert.ToChar(SiteEnums.ResponseType.C.ToString()); sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.IsRead = false; sun.StatusUpdateID = statup.StatusUpdateID; sun.UserAccountID = statup.UserAccountID; sun.Create(); } else { sun.IsRead = false; sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.Update(); } SendNotificationEmail(statup.UserAccountID, SiteEnums.ResponseType.C, sun.StatusUpdateID); } StatusComments statComs = new StatusComments(); statComs.GetAllStatusCommentsForUpdate(statusUpdateID); foreach (StatusComment sc1 in statComs) { sun = new StatusUpdateNotification(); sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.C); if (Convert.ToInt32(mu.ProviderUserKey) == sc1.UserAccountID || Convert.ToInt32(mu.ProviderUserKey) == statup.UserAccountID) continue; if (sun.StatusUpdateNotificationID == 0) { sun.IsRead = false; sun.StatusUpdateID = statusUpdateID; sun.UserAccountID = sc1.UserAccountID; sun.Create(); } else { sun.IsRead = false; sun.Update(); } } context.Response.Write(@"{""StatusAcks"": """ + @"""}"); } } else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) && context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "P" ) { // delete post statup = new StatusUpdate(statusUpdateID); StatusUpdateNotifications.DeleteNotificationsForStatusUpdate(statup.StatusUpdateID); Acknowledgements.DeleteStatusAcknowledgements(statup.StatusUpdateID); StatusComments statComs = new StatusComments(); statComs.GetAllStatusCommentsForUpdate(statup.StatusUpdateID); foreach (StatusComment sc1 in statComs) { StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements(sc1.StatusCommentID); } StatusComments.DeleteStatusComments(statup.StatusUpdateID); statup.Delete(); if (statup.PhotoItemID != null) { PhotoItem pitm = new PhotoItem(Convert.ToInt32(statup.PhotoItemID)); S3Service s3 = new S3Service(); s3.AccessKeyID = AmazonCloudConfigs.AmazonAccessKey; s3.SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey; if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw)) { s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw); } if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard)) { s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard); } if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb)) { s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb); } pitm.Delete(); } context.Response.Write(@"{""StatusAcks"": """ + @"""}"); } else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) && context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "C" ) { // delete comment StatusComment statCom = new StatusComment( Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.status_com_id.ToString()])); StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements(statCom.StatusCommentID); statCom.Delete(); context.Response.Write(@"{""StatusUpdateID"": """ + statCom.StatusUpdateID.ToString() + @"""}"); } else if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.all_comments.ToString()])) { mu = Membership.GetUser(); if (mu == null) return; StatusComments preFilter = new StatusComments(); preFilter.GetAllStatusCommentsForUpdate(statusUpdateID); StatusComments statComs = new StatusComments(); foreach (BootBaronLib.AppSpec.DasKlub.BOL.StatusComment su1 in preFilter) { if (!BootBaronLib.AppSpec.DasKlub.BOL.BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID)) { statComs.Add(su1); } } statComs.IncludeStartAndEndTags = true; sb = new StringBuilder(100); sb.Append(statComs.ToUnorderdList); context.Response.Write(@"{""StatusComs"": """ + HttpUtility.HtmlEncode(sb.ToString()) + @"""}"); } else if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.comment_page.ToString()])) { int pcount = Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.comment_page.ToString()]); StatusUpdates statups = new StatusUpdates(); pcount = pcount + 10; StatusUpdates preFilter = new StatusUpdates(); preFilter.GetStatusUpdatesPageWise(pcount, 1); StatusUpdates sus = new StatusUpdates(); mu = Membership.GetUser(); foreach (BootBaronLib.AppSpec.DasKlub.BOL.StatusUpdate su1 in preFilter) { if (!BootBaronLib.AppSpec.DasKlub.BOL.BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID)) { statups.Add(su1); } } statups.IncludeStartAndEndTags = false; context.Response.Write(@"{""StatusUpdates"": """ + HttpUtility.HtmlEncode(statups.ToUnorderdList) + @"""}"); } #endregion break; case SiteEnums.QueryStringNames.begin_playlist: #region begin_playlist context.Response.Write( PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[ SiteEnums.QueryStringNames.playlist.ToString()]))); #endregion break; case SiteEnums.QueryStringNames.menu: #region menu mu = Membership.GetUser(); // menu updates // get count in video room int userCountChat = 0; // get new mail int userMessages = 0; // get new users int unconfirmedUsers = 0; // status notifications int notifications = 0; if (mu != null) { // log off users who are offline UserAccounts uasOffline = new UserAccounts(); uasOffline.GetWhoIsOffline(true); UserAccount offlineUser = null; foreach (UserAccount uaoff1 in uasOffline) { ChatRoomUser cru = new ChatRoomUser(); cru.GetChatRoomUserByUserAccountID(uaoff1.UserAccountID); if (cru.ChatRoomUserID > 0) { cru.DeleteChatRoomUser(); } offlineUser = new UserAccount(uaoff1.UserAccountID); offlineUser.RemoveCache(); } userCountChat = ChatRoomUsers.GetChattingUserCount(); userMessages = BootBaronLib.AppSpec.DasKlub.BOL.DirectMessages.GetDirectMessagesToUserCount(mu); unconfirmedUsers = BootBaronLib.AppSpec.DasKlub.BOL.UserConnections.GetCountUnconfirmedConnections(Convert.ToInt32(mu.ProviderUserKey)); } // get users online int onlineUsers = UserAccounts.GetOnlineUserCount(); if (mu != null) { notifications = StatusUpdateNotifications.GetStatusUpdateNotificationCountForUser(Convert.ToInt32(mu.ProviderUserKey)); } string timedMessge = string.Format( @"{{""UserCountChat"": ""{0}"", ""UserMessages"": ""{1}"", ""OnlineUsers"": ""{2}"", ""Notifications"": ""{3}"", ""UnconfirmedUsers"": ""{4}""}}",userCountChat,userMessages,onlineUsers,notifications,unconfirmedUsers); context.Response.Write(timedMessge); #endregion break; case SiteEnums.QueryStringNames.random: #region random if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])) { context.Response.Write(Video.GetRandomJSON( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])); } else { context.Response.Write(Video.GetRandomJSON()); } #endregion break; case SiteEnums.QueryStringNames.video_playlist: #region video_playlist if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])) { context.Response.Write( PlaylistVideo.GetNextVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]), context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])); } else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()])) { context.Response.Write( PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]))); } else { context.Response.Write( PlaylistVideo.CurrentVideoInPlaylist( Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]) )); } #endregion break; case SiteEnums.QueryStringNames.video: #region video Video vid = new Video("YT", context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()]); VideoLog.AddVideoLog(vid.VideoID, context.Request.UserHostAddress); context.Response.Write(Video.GetVideoJSON(context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()])); #endregion break; case SiteEnums.QueryStringNames.begindate: #region begindate //string[] dates = HttpUtility.UrlDecode( // context.Request.QueryString[SiteEnums.QueryStringNames.begindate.ToString()] // ).Split('G'); DateTime dtBegin = Convert.ToDateTime(context.Request.QueryString[SiteEnums.QueryStringNames.begindate.ToString()]); dtBegin = new DateTime(dtBegin.Year, dtBegin.Month, 1); DateTime dtEnd = dtBegin.AddMonths(1).AddDays(-1); Events tds = new Events(); tds.GetEventsForLocation( dtBegin, dtEnd, context.Request.QueryString[SiteEnums.QueryStringNames.country_iso.ToString()], context.Request.QueryString[SiteEnums.QueryStringNames.region.ToString()], context.Request.QueryString[SiteEnums.QueryStringNames.city.ToString()]); CalendarItems citms = GetCitms(tds, dtBegin, dtEnd, true); //[ 100, 500, 300, 200, 400 ] sb = new StringBuilder(); sb.Append("["); int processed = 1; foreach (CalendarItem ci1 in citms) { if (processed == citms.Count) { sb.Append(ci1.StartDate.Day); } else { sb.Append(ci1.StartDate.Day); sb.Append(", "); } processed++; } sb.Append("]"); context.Response.Write(sb.ToString()); #endregion break; case SiteEnums.QueryStringNames.playlist: #region playlist if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])) { context.Response.Write( PlaylistVideo.GetNextVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]), context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])); } else if (!string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()])) { context.Response.Write( PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]))); } else { context.Response.Write( PlaylistVideo.CurrentVideoInPlaylist( Convert.ToInt32(context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]) )); } #endregion break; default: // ? break; } }
public async Task AddReminderMinute(uint minute = 0, [Remainder] string reminderString = null) { try { if (minute > 1439) { await CommandHandeling.ReplyAsync(Context, "Booole. [time] have to be in range 0-1439 (in minutes)"); return; } var hour = 0; var timeFormat = $"{minute}m"; if (minute >= 60) { for (var i = 0; minute >= 59; i++) { minute = minute - 59; hour++; timeFormat = $"{hour}h {minute}m"; } } var timeString = timeFormat; //// MAde t ominutes var timeDateTime = DateTime.UtcNow + TimeSpan.ParseExact(timeString, ReminderFormat.Formats, CultureInfo.CurrentCulture); var randomIndex = _secureRandom.Random(0, OctoNamePull.OctoNameRu.Length - 1); var randomOcto = OctoNamePull.OctoNameRu[randomIndex]; var extra = randomOcto.Split(new[] { "](" }, StringSplitOptions.RemoveEmptyEntries); var name = extra[0].Remove(0, 1); var url = extra[1].Remove(extra[1].Length - 1, 1); var bigmess = $"{reminderString}\n\n" + $"We will send you a DM in __**{timeDateTime}**__ `by UTC`\n" + $"**Time Now: {DateTime.UtcNow}** `by UTC`"; var embed = new EmbedBuilder(); embed.WithAuthor(Context.User); embed.WithTimestamp(DateTimeOffset.UtcNow); embed.WithColor(_secureRandom.Random(0, 255), _secureRandom.Random(0, 255), _secureRandom.Random(0, 255)); embed.AddField($"**____**", $"{bigmess}"); embed.WithTitle($"{name} напомнит тебе:"); embed.WithUrl(url); await CommandHandeling.ReplyAsync(Context, embed); var account = UserAccounts.GetAccount(Context.User, 0); //account.SocketUser = SocketGuildUser(Context.User); var newReminder = new CreateReminder(timeDateTime, reminderString); account.ReminderList.Add(newReminder); UserAccounts.SaveAccounts(0); } catch { var botMess = await ReplyAsync( "boo... An error just appear >_< \n" + "Say `HelpRemind`"); HelperFunctions.DeleteMessOverTime(botMess, 5); } }
public async Task OctopusPicture() { try { var embed = new EmbedBuilder(); var account = UserAccounts.GetAccount(Context.User, 0); var difference = DateTime.UtcNow - account.LastOctoPic; if (difference.TotalHours > 5) { var randomKeyPossible = _secureRandom.Random(0, 100000); if (randomKeyPossible == 1448) { embed.AddField("Boole!?", "What is it? Some king of a quest... I found a number - **228**, " + "what can it mean... if you will know, say `quest ANSWER`, I think this should be one eglish word."); } } account.LastOctoPic = DateTime.UtcNow; UserAccounts.SaveAccounts(0); var index = _secureRandom.Random(0, 254); if (index == 5 || index == 38 || index == 69) { var lll = await Context.Channel.SendMessageAsync("boole"); HelperFunctions.DeleteMessOverTime(lll, 6); } else { var octoIndex = _secureRandom.Random(0, OctoPicPull.OctoPics.Length - 1); var octoToPost = OctoPicPull.OctoPics[octoIndex]; var color1Index = _secureRandom.Random(0, 254); var color2Index = _secureRandom.Random(0, 254); var color3Index = _secureRandom.Random(0, 254); var randomIndex = _secureRandom.Random(0, OctoNamePull.OctoNameRu.Length); var randomOcto = OctoNamePull.OctoNameRu[randomIndex]; embed.WithDescription($"{randomOcto} found:"); embed.WithFooter("lil octo notebook"); embed.WithColor(color1Index, color2Index, color3Index); embed.WithAuthor(Context.User); embed.WithImageUrl("" + octoToPost); await CommandHandeling.ReplyAsync(Context, embed); if (octoIndex == 19) { var lll = await Context.Channel.SendMessageAsync("Ooooo, it was I who just passed Dark Souls!"); HelperFunctions.DeleteMessOverTime(lll, 6); } if (octoIndex == 9) { var lll = await Context.Channel.SendMessageAsync("I'm drawing an octopus :3"); HelperFunctions.DeleteMessOverTime(lll, 6); } if (octoIndex == 26) { var lll = await Context.Channel.SendMessageAsync( "Oh, this is New Year! time to gift turtles!!"); HelperFunctions.DeleteMessOverTime(lll, 6); } } } catch { // await ReplyAsync("boo... An error just appear >_< \nTry to use this command properly: **Octo**\n"); } }
public async Task DisplayPoints() { #region points IUser user = Context.User; await Utils.SendLog(Context.Message.Content, Context.User); int x = UserAccounts.GetAccount((SocketGuildUser)user).Points; var eb = new EmbedBuilder() { Color = Color.DarkBlue, Author = new EmbedAuthorBuilder() { IconUrl = $"{user.GetAvatarUrl()}", Name = $"{user.Username}#{user.Discriminator}", }, Description = $"You have `{x}` Points as your total balance.", Footer = new EmbedFooterBuilder() { Text = $"{DateTime.Now}", }, }; eb.WithColor(Color.Blue); if (x > 0 || x == 0) { if (x > 29) { if (x > 69) { if (x > 119) { if (x > 179) { if (x > 249) { eb.WithFields( new EmbedFieldBuilder() { IsInline = false, Name = "Current rank", Value = $"You are currently on rank: {Utils.DataRank5.Mention}" }, new EmbedFieldBuilder() { IsInline = false, Name = "Progress to the next rank", Value = "You have no rank to further progress to, congratulations!" }); await ReplyAsync("", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); await(user as IGuildUser).AddRoleAsync(Utils.DataRank5); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank4); return; } if (x < 250) { var count5 = 250 - x; eb.WithFields( new EmbedFieldBuilder() { IsInline = false, Name = "Current rank", Value = $"You are currently on rank: {Utils.DataRank4.Mention}" }, new EmbedFieldBuilder() { IsInline = false, Name = "Progress to the next rank", Value = $"You need `{count5}` more points to get to the next rank: {Utils.DataRank5.Mention}" }); await ReplyAsync("", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); await(user as IGuildUser).AddRoleAsync(Utils.DataRank4); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank3); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank5); return; } } if (x < 180) { var count4 = 180 - x; eb.WithFields( new EmbedFieldBuilder() { IsInline = false, Name = "Current rank", Value = $"You are currently on rank: {Utils.DataRank3.Mention}" }, new EmbedFieldBuilder() { IsInline = false, Name = "Progress to the next rank", Value = $"You need `{count4}` more points to get to the next rank: {Utils.DataRank4.Mention}" }); await ReplyAsync("", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); await(user as IGuildUser).AddRoleAsync(Utils.DataRank3); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank2); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank4); return; } } if (x < 120) { var count3 = 120 - x; eb.WithFields( new EmbedFieldBuilder() { IsInline = false, Name = "Current rank", Value = $"You are currently on rank: {Utils.DataRank2.Mention}" }, new EmbedFieldBuilder() { IsInline = false, Name = "Progress to the next rank", Value = $"You need `{count3}` more points to get to the next rank: {Utils.DataRank3.Mention}" }); await ReplyAsync("", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); await(user as IGuildUser).AddRoleAsync(Utils.DataRank2); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank1); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank3); return; } } if (x < 70) { var count2 = 70 - x; eb.WithFields( new EmbedFieldBuilder() { IsInline = false, Name = "Current rank", Value = $"You are currently on rank: {Utils.DataRank1.Mention}" }, new EmbedFieldBuilder() { IsInline = false, Name = "Progress to the next rank", Value = $"You need `{count2}` more points to get to the next rank: {Utils.DataRank2.Mention}" }); await ReplyAsync("", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); await(user as IGuildUser).AddRoleAsync(Utils.DataRank1); return; } } } if (x < 30) { var count1 = 30 - x; eb.WithFields( new EmbedFieldBuilder() { IsInline = false, Name = "Current rank", Value = "You currently do not have a rank!" }, new EmbedFieldBuilder() { IsInline = false, Name = "Progress to the next rank", Value = $"you need `{count1}` more points to get to rank: {Utils.DataRank1.Mention}" }); await ReplyAsync("", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); await(user as IGuildUser).RemoveRoleAsync(Utils.DataRank1); return; } else { await ReplyAsync("Error executing command", false, eb.Build(), null, new AllowedMentions() { MentionRepliedUser = true }, new MessageReference(Context.Message.Id)); } return; #endregion }
public async Task RemoveSeries(SocketGuildUser user, [Remainder] string series) { var account = UserAccounts.GetAccount(Context.User); await RemoveClassSeries(series, user, (SocketTextChannel)Context.Channel); }
private void LoadFilteredUsers(bool isAjax, FindUsersModel model) { _mu = MembershipWrapper.GetUser(); model.AgeFrom = (!string.IsNullOrWhiteSpace(Request.QueryString["AgeFrom"])) ? Convert.ToInt32(Request.QueryString["AgeFrom"]) : model.AgeFrom; model.AgeTo = (!string.IsNullOrWhiteSpace(Request.QueryString["AgeTo"])) ? Convert.ToInt32(Request.QueryString["AgeTo"]) : model.AgeTo; UserAccountDetail uad; if (_mu != null) { if (!isAjax) { uad = new UserAccountDetail(); uad.GetUserAccountDeailForUser(Convert.ToInt32(_mu.ProviderUserKey)); if (!string.IsNullOrWhiteSpace(Request.QueryString.ToString())) { uad.FindUserFilter = Request.QueryString.ToString(); uad.Update(); } else if (!string.IsNullOrWhiteSpace(uad.FindUserFilter)) { Response.Redirect(string.Format("~/findusers?{0}", uad.FindUserFilter)); } } } model.InterestedInID = (Request.QueryString["InterestedInID"] != null && Request.QueryString["InterestedInID"] == string.Empty) ? null : (Request.QueryString["InterestedInID"] == null) ? model.InterestedInID : Convert.ToInt32(Request.QueryString["InterestedInID"]); model.RelationshipStatusID = (Request.QueryString["RelationshipStatusID"] != null && Request.QueryString["RelationshipStatusID"] == string.Empty) ? null : (Request.QueryString["RelationshipStatusID"] == null) ? model.RelationshipStatusID : Convert.ToInt32(Request.QueryString["RelationshipStatusID"]); model.YouAreID = (Request.QueryString["YouAreID"] != null && Request.QueryString["YouAreID"] == string.Empty) ? null : (Request.QueryString["YouAreID"] == null) ? model.YouAreID : Convert.ToInt32(Request.QueryString["YouAreID"]); model.Lang = (Request.QueryString["lang"] != null && Request.QueryString["lang"] == string.Empty) ? null : Request.QueryString["lang"] ?? model.Lang; model.PostalCode = (Request.QueryString["postalcode"] != null && Request.QueryString["postalcode"] == string.Empty) ? null : Request.QueryString["postalcode"] ?? model.PostalCode; model.Country = (Request.QueryString["country"] != null && Request.QueryString["country"] == string.Empty) ? null : Request.QueryString["country"] ?? model.Country; _uas = new UserAccounts(); bool sortByDistance; _uas.GetListUsers(_userPageNumber, PageSize, model.AgeFrom, model.AgeTo, model.InterestedInID, model.RelationshipStatusID, model.YouAreID, model.Country, model.PostalCode, model.Lang, out sortByDistance); if (!isAjax) { ViewBag.SortByDistance = sortByDistance; } if (_mu == null || isAjax) return; if (string.IsNullOrWhiteSpace(Request.QueryString.ToString())) return; uad = new UserAccountDetail(); uad.GetUserAccountDeailForUser(Convert.ToInt32(_mu.ProviderUserKey)); uad.FindUserFilter = Request.QueryString.ToString(); uad.Update(); }
public JsonResult OnlineNow() { _uas = new UserAccounts(); _uas.GetOnlineUsers(); _uas.Sort( (p1, p2) => p2.LastActivityDate.CompareTo(p1.LastActivityDate)); return Json(new { Value = _uas.ToUnorderdList }); }
public void Execute(IJobExecutionContext context) { using (var contextDb = new DasKlubDbContext()) { var oneWeekAgo = DateTime.UtcNow.AddDays(-7); const int totalTopAmount = 3; var mostPopularForumPosts = contextDb.ForumPost .Where(x => x.CreateDate > oneWeekAgo) .GroupBy(x => x.ForumSubCategoryID) .OrderByDescending(y => y.Count()) .Take(totalTopAmount) .ToList(); if (mostPopularForumPosts.Count == totalTopAmount) { var threads = new StringBuilder(); foreach (var item in mostPopularForumPosts) { ForumSubCategory forumThread = contextDb.ForumSubCategory .FirstOrDefault(x => x.ForumSubCategoryID == item.Key); ForumCategory forum = contextDb.ForumCategory .FirstOrDefault(x => x.ForumCategoryID == forumThread.ForumCategoryID); threads.Append(forumThread.Title); threads.AppendLine(); threads.AppendFormat("{0}/forum/{1}/{2}", GeneralConfigs.SiteDomain, forum.Key, forumThread.Key); threads.AppendLine(); threads.Append("------------------------------"); threads.AppendLine(); threads.AppendLine(); } string top3Threads = threads.ToString(); DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo; Calendar cal = dfi.Calendar; int weekNumber = cal.GetWeekOfYear(DateTime.UtcNow, dfi.CalendarWeekRule, dfi.FirstDayOfWeek); string title = string.Format("TOP {0} Forum Threads [Week: {1}, {2}]", totalTopAmount, weekNumber, DateTime.UtcNow.Year); var uas = new UserAccounts(); uas.GetAll(); foreach (UserAccount user in uas) { var uad = new UserAccountDetail(); uad.GetUserAccountDeailForUser(user.UserAccountID); if (!uad.EmailMessages || uad.UserAccountDetailID == 0) continue; string message = string.Format( "Hello {0}! {1}{1}{2}", user.UserName, Environment.NewLine, top3Threads); System.Threading.Thread.Sleep(1000 / MaxEmailsPerSecond); _mail.SendMail(AmazonCloudConfigs.SendFromEmail, user.EMail, title, message); Log.Info(string.Format("Sent top 3 to: {0}", user.EMail)); } } else { Log.Info("Not enough forum activity to mail users"); } } }
public StatsUser(UserAccounts accounts, ServerAccounts serverAccounts) { _accounts = accounts; _serverAccounts = serverAccounts; }
/// <summary> /// Handles "Download Zip" button-click events /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MaterialsZipButton_Click(object sender, System.EventArgs e) { string path = ConfigurationSettings.AppSettings["MaterialsDir"] + ModInfo.Id + "\\"; string[] filenames = getAccessLevelFiles(ModInfo.Id); //string[] filenames = Directory.GetFiles( path ); string userAccessLevel = "All"; if (Context.User.Identity.IsAuthenticated) { UserAccounts.UserInfo zui = UserAccounts.getUserInfo(Context.User.Identity.Name); if (((int)zui.Role) == 0) { userAccessLevel = "Users"; } else if (((int)zui.Role) >= 1 && ((int)zui.Role) < 5) { userAccessLevel = "Faculty"; } } userAccessLevel = leastAccessLevel(ModInfo.Id, userAccessLevel); string fileWithoutPath = "materials-" + userAccessLevel + "-" + ModInfo.Id + ".zip"; string fileWithPath = path + fileWithoutPath; // Once the zip file is created, it is stored and not created again. // If this module is in the 'InProgress' or 'PendingApproval' states, // we need to delete the zip file if it exists, because the submitter // can edit the materials before the module has been approved. If the // Zip file is not deleted, it may contain links to Materials that don't // exist, and it may be missing links to Materials that do exist. if (ModInfo.Status == ModuleStatus.InProgress || ModInfo.Status == ModuleStatus.PendingApproval) { // Need to store file under different file name than the usual filename // since the submitter may create the zip file before submission, // submit the module (turning the status potentially to approved), // and having an incorrect zip file exist later fileWithPath = path + "tempMaterials-" + userAccessLevel + "-" + ModInfo.Id + ".zip"; if (File.Exists(fileWithPath)) { File.Delete(fileWithPath); } } // If the zip file does not already exist, create it if (!File.Exists(fileWithPath)) { ZipOutputStream s = new ZipOutputStream(File.Create(fileWithPath)); //*****************************************************************************// //********** NOTE: Code taken from \samples\cs\CreateZipFile\Main.cs **********// //********** from file: 050SharpZipLib_SourceSamples.zip **********// //********** made available by SharpDevelop at: **********// //********** http://www.icsharpcode.net/OpenSource/SD/Download **********// //*****************************************************************************// // Modified to use MaterialInfo objects instead of strings Crc32 crc = new Crc32(); s.SetLevel(6); // 0 - store only to 9 - means best compression foreach (string file in filenames) { if (file != null) { //string filepath = ConfigurationSettings.AppSettings["MaterialsDir"] + file.ModuleID + "\\" + file.Link; FileStream fs = File.OpenRead(path + file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); // our code - hides our internal file structure ZipEntry entry = new ZipEntry(file); // end of our code entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); s.Close(); //*****************************************************************************// //*************************** End of Borrowed Code ****************************// //*****************************************************************************// } // Redirect them directly to the file for downloading/opening Response.Redirect("Materials/" + ModInfo.Id + "/" + fileWithoutPath); }
public static async Task HandleReactionAdded(Cacheable <IUserMessage, ulong> cacheMessage, SocketReaction reaction) { if (reaction.User.Value.IsBot) { return; } //var up = ControlEmojis["up"]; //var down = ControlEmojis["down"]; var stopInv = ControlEmojis["stopInv"]; var sell = ControlEmojis["sell"]; var yes = ControlEmojis["yes"]; var no = ControlEmojis["no"]; if (ListenForReactionMessages.ContainsKey(reaction.MessageId)) { await reaction.Message.Value.RemoveReactionAsync(reaction.Emote, reaction.User.Value); if (ListenForReactionMessages[reaction.MessageId] == reaction.User.Value.Id) { if (reaction.Emote.Name == ControlEmojis["up"].Name) { await HandleMovement(reaction, cacheMessage.Value.Content, true); } else if (reaction.Emote.Name == ControlEmojis["down"].Name) { await HandleMovement(reaction, cacheMessage.Value.Content, false); } else if (reaction.Emote.Name == ControlEmojis["stopInv"].Name) { await reaction.Message.Value.DeleteAsync(); } else if (reaction.Emote.Name == ControlEmojis["sell"].Name) { await reaction.Message.Value.RemoveAllReactionsAsync(); await reaction.Message.Value.AddReactionAsync(ControlEmojis["yes"]); await reaction.Message.Value.AddReactionAsync(ControlEmojis["no"]); } else if (reaction.Emote.Name == ControlEmojis["yes"].Name) { await reaction.Message.Value.RemoveAllReactionsAsync(); await reaction.Message.Value.Channel.SendMessageAsync("you accepted the selling request."); //await reaction.Message.Value.AddReactionAsync(up); //await reaction.Message.Value.AddReactionAsync(down); await reaction.Message.Value.AddReactionAsync(stopInv); await reaction.Message.Value.AddReactionAsync(sell); } else if (reaction.Emote.Name == ControlEmojis["no"].Name) { await reaction.Message.Value.RemoveAllReactionsAsync(); await reaction.Message.Value.Channel.SendMessageAsync("you denied the selling request."); //await reaction.Message.Value.AddReactionAsync(up); //await reaction.Message.Value.AddReactionAsync(down); await reaction.Message.Value.AddReactionAsync(stopInv); await reaction.Message.Value.AddReactionAsync(sell); } else if (reaction.Emote.Name == ControlEmojis["right"].Name) { var account = UserAccounts.GetAccount(reaction.User.Value as SocketGuildUser); var testing = account.CurrentCharacter; string fullstring = null; int pagenumber = account.PageNumber + 1; const int itemsPerPage = 10; List <string> items = new List <string>(); foreach (var item in testing.Inventory) { items.Add(item.Name); } var lastPage = 1 + (items.Count / (itemsPerPage + 1)); if (pagenumber > lastPage) { pagenumber = 1; } int quickmaf = 10 - items.Count(); if (quickmaf < 0) { quickmaf = 0; } int InventoryItemCount = 10 - quickmaf; for (var i = 0; i < itemsPerPage; i++) { var index = itemsPerPage * (pagenumber - 1) + i; var itemname = " "; if (index < items.Count) { itemname = items[index]; } fullstring += string.Format("║ {0, -35}║\n", itemname); } var output = string.Format("{0}'s inventory:\n╔════════════════════════════════════╗\n{1}║ {2, -35}║\n╠════════════════════════════════════╩═══════════════════════════════════╗\n", testing.Name, fullstring, $"page {pagenumber}/{lastPage}..."); var count = 0; for (int i = 0; i < output.Length; i++) { if (output[i] == '\n') { if (count == 2) { output = output.Insert(i, LineIndicator); break; } else { count++; } } } var Seperated = SeperateTheLines(output); foreach (string s in Seperated) { if (ContainsLineIndicator(s)) { string ItemName = null; string Class = null; string DamageOramount = null; string Desc = null; var GetItem = s.Split('║', StringSplitOptions.RemoveEmptyEntries)[0]; GetItem = GetItem.Remove(0, 1); GetItem = GetItem.Remove(GetItem.Length - 1, 1); char c; var pos = GetItem.Length; do { pos--; c = GetItem[pos]; } while (c == ' '); GetItem = GetItem.Remove(++pos, GetItem.Length - pos); var CurrentItem = testing.Inventory.Where(x => x.Name == GetItem).FirstOrDefault(); var nextItem = ItemsListWs.workStation.Items[CurrentItem.ID]; if (CurrentItem.Amount > 0) { ItemName = $"Item Name: {GetItem}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Amount: {CurrentItem.Amount}"; Desc = nextItem.Description; } else { ItemName = $"Item Name: {GetItem}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Damage: {nextItem.Damage}"; Desc = nextItem.Description; } var message = (string.Format("```{0}║ {1, -24}{2, -24}{3, -23}║\n║{4, -72}║\n║ {5, -71}║\n║ {6, -71}║\n║{4, -72}║\n╚════════════════════════════════════════════════════════════════════════╝```", output, ItemName, Class, DamageOramount, " ", "Description:", Desc)); await reaction.Message.Value.ModifyAsync(x => x.Content = message); account.PageNumber = pagenumber; UserAccounts.SaveAccounts(account); } } } else if (reaction.Emote.Name == ControlEmojis["left"].Name) { var account = UserAccounts.GetAccount(reaction.User.Value as SocketGuildUser); var testing = account.CurrentCharacter; string fullstring = null; int pagenumber = account.PageNumber - 1; List <string> items = new List <string>(); foreach (var item in testing.Inventory) { items.Add(item.Name); } const int itemsPerPage = 10; var lastPage = 1 + (items.Count / (itemsPerPage + 1)); if (pagenumber == 0) { pagenumber = lastPage; } int quickmaf = 10 - items.Count(); if (quickmaf < 0) { quickmaf = 0; } int InventoryItemCount = 10 - quickmaf; for (var i = 0; i < itemsPerPage; i++) { var index = itemsPerPage * (pagenumber - 1) + i; var itemname = " "; if (index < items.Count) { itemname = items[index]; } fullstring += string.Format("║ {0, -35}║\n", itemname); } var output = string.Format("{0}'s inventory:\n╔════════════════════════════════════╗\n{1}║ {2, -35}║\n╠════════════════════════════════════╩═══════════════════════════════════╗\n", testing.Name, fullstring, $"page {pagenumber}/{lastPage}..."); var count = 0; for (int i = 0; i < output.Length; i++) { if (output[i] == '\n') { if (count == 2) { output = output.Insert(i, LineIndicator); break; } else { count++; } } } var Seperated = SeperateTheLines(output); foreach (string s in Seperated) { if (ContainsLineIndicator(s)) { string ItemName = null; string Class = null; string DamageOramount = null; string Desc = null; var GetItem = s.Split('║', StringSplitOptions.RemoveEmptyEntries)[0]; GetItem = GetItem.Remove(0, 1); GetItem = GetItem.Remove(GetItem.Length - 1, 1); char c; var pos = GetItem.Length; do { pos--; c = GetItem[pos]; } while (c == ' '); GetItem = GetItem.Remove(++pos, GetItem.Length - pos); var CurrentItem = testing.Inventory.Where(x => x.Name == GetItem).FirstOrDefault(); var nextItem = ItemsListWs.workStation.Items[CurrentItem.ID]; if (CurrentItem.Amount > 0) { ItemName = $"Item Name: {GetItem}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Amount: {CurrentItem.Amount}"; Desc = nextItem.Description; } else { ItemName = $"Item Name: {GetItem}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Damage: {nextItem.Damage}"; Desc = nextItem.Description; } var message = (string.Format("```{0}║ {1, -24}{2, -24}{3, -23}║\n║{4, -72}║\n║ {5, -71}║\n║ {6, -71}║\n║{4, -72}║\n╚════════════════════════════════════════════════════════════════════════╝```", output, ItemName, Class, DamageOramount, " ", "Description:", Desc)); await reaction.Message.Value.ModifyAsync(x => x.Content = message); account.PageNumber = pagenumber; UserAccounts.SaveAccounts(account); } } } } } }
public JsonResult OnlineNow() { uas = new UserAccounts(); uas.GetOnlineUsers(); uas.Sort(delegate(UserAccount p1, UserAccount p2) { return p2.LastActivityDate.CompareTo(p1.LastActivityDate); }); return Json(new { Value = uas.ToUnorderdList }); }
public async Task InventoryTesting(int pagenumber = 1) { var account = UserAccounts.GetAccount(Context.User); var testing = account.CurrentCharacter; string fullstring = null; List <string> items = new List <string>(); foreach (var item in testing.Inventory) { items.Add(item.Name); } int quickmaf = 10 - items.Count(); if (quickmaf < 0) { quickmaf = 0; } int InventoryItemCount = 10 - quickmaf; const int itemsPerPage = 10; for (var i = 0; i < itemsPerPage; i++) { var index = itemsPerPage * (pagenumber - 1) + i; var itemname = " "; if (index < items.Count) { itemname = items[i]; } fullstring += string.Format("║ {0, -35}║\n", itemname); } var lastPage = 1 + (items.Count / (itemsPerPage + 1)); var output = string.Format("{0}'s inventory:\n╔════════════════════════════════════╗\n{1}║ {2, -35}║\n╠════════════════════════════════════╩═══════════════════════════════════╗\n", testing.Name, fullstring, $"page {pagenumber}/{lastPage}..."); var count = 0; for (int i = 0; i < output.Length; i++) { if (output[i] == '\n') { if (count == 2) { output = output.Insert(i, LineIndicator); break; } else { count++; } } } var Seperated = SeperateTheLines(output); foreach (string s in Seperated) { if (ContainsLineIndicator(s)) { string ItemName = null; string Class = null; string DamageOramount = null; string Desc = null; var GetItem = s.Split('║', StringSplitOptions.RemoveEmptyEntries)[0]; GetItem = GetItem.Remove(0, 1); GetItem = GetItem.Remove(GetItem.Length - 1, 1); char c; var pos = GetItem.Length; do { pos--; c = GetItem[pos]; } while (c == ' '); GetItem = GetItem.Remove(++pos, GetItem.Length - pos); var CurrentItem = testing.Inventory.Where(x => x.Name == GetItem).FirstOrDefault(); var nextItem = ItemsListWs.workStation.Items[CurrentItem.ID]; if (CurrentItem.Amount > 0) { ItemName = $"Item Name: {GetItem}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Amount: {CurrentItem.Amount}"; Desc = nextItem.Description; } else { ItemName = $"Item Name: {GetItem}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Damage: {nextItem.Damage}"; Desc = nextItem.Description; } var message = await ReplyAsync(string.Format("```{0}║ {1, -24}{2, -24}{3, -23}║\n║{4, -72}║\n║ {5, -71}║\n║ {6, -71}║\n║{4, -72}║\n╚════════════════════════════════════════════════════════════════════════╝```", output, ItemName, Class, DamageOramount, " ", "Description:", Desc)); ListenForReactionMessages.Add(message.Id, Context.User.Id); account.PageNumber = pagenumber; await message.AddReactionAsync(ControlEmojis["left"]); await message.AddReactionAsync(ControlEmojis["up"]); await message.AddReactionAsync(ControlEmojis["down"]); await message.AddReactionAsync(ControlEmojis["right"]); await message.AddReactionAsync(ControlEmojis["stopInv"]); await message.AddReactionAsync(ControlEmojis["sell"]); } } }
public ActionResult BlockedUsers() { if (_mu != null) _ua = new UserAccount(_mu.UserName); if (_ua.UserAccountID == 0) return View(); _contacts = new UserAccounts(); var bus = new BlockedUsers(); if (_mu != null) bus.GetBlockedUsers(Convert.ToInt32(_mu.ProviderUserKey)); foreach (UserAccount ua1 in bus.Select(uc1 => new UserAccount(uc1.UserAccountIDBlocked))) { _contacts.Add(ua1); } ViewBag.BlockedUsers = _contacts.ToUnorderdList; return View(); }
private static string PerformMove(string[] messageLines, bool dirUp, SocketReaction context) { string ItemName = null; string Class = null; string DamageOramount = null; string Desc = null; // Get the current index of the line indicator var currentIndex = GetCurrentIndex(messageLines); var newIndex = currentIndex + (dirUp ? -1 : 1); var currentItemName = GetItemName(messageLines, currentIndex); var newMessage = new StringBuilder(); if (newIndex > 1 && newIndex < messageLines.Length - 7) { // Get the name of the next item var nextItemName = GetItemName(messageLines, newIndex, currentItemName); // Get the current and next item var account = UserAccounts.GetAccount(context.User.Value as SocketGuildUser); var testing = account.CurrentCharacter; if (nextItemName == "") { ItemName = $"Item Name: "; Class = $"Class: "; DamageOramount = $" "; Desc = " "; } else { var CurrentItem = testing.Inventory.Where(x => x.Name == nextItemName).FirstOrDefault(); var nextItem = ItemsListWs.workStation.Items[CurrentItem.ID]; if (CurrentItem.Amount > 0) { ItemName = $"Item Name: {nextItemName}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Amount: {CurrentItem.Amount}"; Desc = nextItem.Description; } else { ItemName = $"Item Name: {nextItemName}"; Class = $"Class: {nextItem.Class}"; DamageOramount = $"Damage: {nextItem.Damage}"; Desc = nextItem.Description; } } // Move the line indicator var line = messageLines[currentIndex]; messageLines[currentIndex] = line.Substring(0, line.Length - LineIndicator.Length); messageLines[newIndex] = $"{messageLines[newIndex]}{LineIndicator}"; var descIndex = messageLines.Length - 6; for (int i = 0; i < descIndex; i++) { newMessage.Append($"{messageLines[i]}\n"); } var emptyLine = "║ ║"; var closingLine = "╚════════════════════════════════════════════════════════════════════════╝"; var desc = string.Format("║ {0, -24}{1, -24}{2, -23}║\n{3, -72}\n║ {4, -71}║\n║ {5, -71}║\n{3, -72}\n{6, -72}```", ItemName, Class, DamageOramount, emptyLine, "Description:", Desc, closingLine); newMessage.Append(desc); } else { foreach (string s in messageLines) { newMessage.Append($"{s}\n"); } } return(newMessage.ToString()); }
private UserAccounts LoadTopForumUsers(IEnumerable<int> mostPostsInForum) { var topForumUsers = new UserAccounts(); topForumUsers.AddRange(mostPostsInForum.Select(topForumUser => new UserAccount(topForumUser))); return topForumUsers; }
public static async void CheckPulls(object sender, ElapsedEventArgs e) { try { ulong zeroGuildId = 0; var allUserAccounts = UserAccounts.GetOrAddUserAccountsForGuild(zeroGuildId); foreach (var t in allUserAccounts) { if (Global.Client.GetUser(t.Id) != null) { var globalAccount = Global.Client.GetUser(t.Id); var account = UserAccounts.GetAccount(globalAccount, zeroGuildId); var difference = DateTime.UtcNow - account.LastDailyPull; if (difference.TotalHours > 39 && account.DailyPullPoints >= 1) { try { var dmChannel = await globalAccount.GetOrCreateDMChannelAsync(); var embed = new EmbedBuilder(); embed.WithFooter("lil octo notebook"); embed.WithTitle("OctoNotification"); embed.WithDescription("You have lost all the ponts ;c"); await dmChannel.SendMessageAsync("", false, embed.Build()); account.DailyPullPoints = 0; UserAccounts.SaveAccounts(zeroGuildId); } catch { Console.WriteLine($"ERROR DM SENING {account.UserName} Closed DM"); account.DailyPullPoints = 0; UserAccounts.SaveAccounts(zeroGuildId); return; } } if (account.DailyPullPoints >= 28) { var mylorikGlobal = Global.Client.GetUser(181514288278536193); var mylorik = UserAccounts.GetAccount(mylorikGlobal, zeroGuildId); if (mylorik.KeyPullName != null) { var fullKeysNameList = mylorik.KeyPullName.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var fullKeysKeyList = mylorik.KeyPullKey.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); if (fullKeysNameList.Length == 1) { Array.Resize(ref fullKeysNameList, fullKeysNameList.Length + 2); Array.Resize(ref fullKeysKeyList, fullKeysKeyList.Length + 2); fullKeysNameList[fullKeysNameList.Length - 2] = "Nothing"; fullKeysNameList[fullKeysNameList.Length - 1] = "Nothing"; fullKeysKeyList[fullKeysKeyList.Length - 2] = "boole?"; fullKeysKeyList[fullKeysKeyList.Length - 1] = "boole?"; } else if (fullKeysNameList.Length == 2) { Array.Resize(ref fullKeysNameList, fullKeysNameList.Length + 1); Array.Resize(ref fullKeysKeyList, fullKeysKeyList.Length + 1); fullKeysNameList[fullKeysNameList.Length - 1] = "Nothing"; fullKeysKeyList[fullKeysKeyList.Length - 1] = "boole?"; } int randonKey1; int randonKey2; int randonKey3; do { randonKey1 = SecureRandomStatic.Random(0, fullKeysNameList.Length); randonKey2 = SecureRandomStatic.Random(0, fullKeysNameList.Length); randonKey3 = SecureRandomStatic.Random(0, fullKeysNameList.Length); } while (randonKey1 == randonKey2 || randonKey2 == randonKey3 || randonKey1 == randonKey3); UserAccounts.SaveAccounts(zeroGuildId); var dmChannel = await globalAccount.GetOrCreateDMChannelAsync(); var embed = new EmbedBuilder(); var text = "**IMPORTANT, pelase read BEFORE cKey command:**\nIf you are NOT going to PLAY this game - please say `cKey 0`, and we will use this key to the one who WILL play the game.\n\n" + $"Choose one or zero:\nSay `cKey number`\n\n**1. {fullKeysNameList[randonKey1]}**\n**2. {fullKeysNameList[randonKey2]}**\n**3. {fullKeysNameList[randonKey3]}**\n\n**0. Nothing**\n\n" + $"Boole.\n{new Emoji("<:octo_hi:465374417644552192>")}"; embed.WithFooter("lil octo notebook"); embed.WithColor(Color.Green); embed.WithTitle("You can choose a game now!"); embed.WithDescription(text); await dmChannel.SendMessageAsync("", false, embed.Build()); account.PullToChoose = null; account.PullToChoose += $"{randonKey1}%%"; account.PullToChoose += $"{randonKey2}%%"; account.PullToChoose += $"{randonKey3}%%"; account.DailyPullPoints = 0; UserAccounts.SaveAccounts(zeroGuildId); } else { var dmChannel = await globalAccount.GetOrCreateDMChannelAsync(); var embed = new EmbedBuilder(); embed.WithFooter("lil octo notebook"); embed.WithColor(Color.Green); embed.WithTitle("OctoNotification"); embed.WithDescription("Booole... There is no more keys.... ;c"); await dmChannel.SendMessageAsync("", false, embed.Build()); } } } } } catch { Console.WriteLine("Failed To ReadFile(CheckPulls). Will ty in 5 sec."); } }
public void GetContactsForUser(string userName, char contactType) { ua = new UserAccount(userName); // if (Membership.GetUser().UserName != ua.UserName) return View(); if (ua.UserAccountID == 0) return; contacts = new UserAccounts(); UserAccount ua1 = null; ucons = new UserConnections(); ucons.GetUserConnections(ua.UserAccountID); foreach (UserConnection uc1 in ucons) { if (!uc1.IsConfirmed || uc1.StatusType != contactType) continue; if (uc1.FromUserAccountID == ua.UserAccountID) { ua1 = new UserAccount(uc1.ToUserAccountID); } else { ua1 = new UserAccount(uc1.FromUserAccountID); } if (ua1.IsApproved && !ua1.IsLockedOut) { contacts.Add(ua1); } } ViewBag.UserName = ua.UserName; ViewBag.ContactsCount = Convert.ToString(contacts.Count); ViewBag.Contacts = contacts.ToUnorderdList; }
public AttackDamageActiveTree(UserAccounts accounts, ArmorReduction armorReduction) { _accounts = accounts; _armorReduction = armorReduction; }
public ActionResult ContactRequest() { NameValueCollection nvc = Request.QueryString; ua = new UserAccount(nvc["username"]); uas = new UserAccounts(); uas.Add(ua); ViewBag.UserTo = uas.ToUnorderdList; ViewBag.ContactType = nvc["contacttype"]; ViewBag.UserNameTo = ua.UserName; char contype = Convert.ToChar(nvc["contacttype"]); switch (contype) { case 'R': ViewBag.HeaderRequest = string.Format("{0} : {1}", ua.UserName, BootBaronLib.Resources.Messages.HaveYouMetInRealLife); ViewBag.HeaderRequest += string.Format( @"<img src=""{0}"" />", VirtualPathUtility.ToAbsolute("~/content/images/userstatus/handprint_small.png")); break; case 'C': ViewBag.HeaderRequest = string.Format("{0} : {1}", ua.UserName, BootBaronLib.Resources.Messages.WouldYouLikeToBeCyberAssociates); ViewBag.HeaderRequest += string.Format( @"<img src=""{0}"" />", VirtualPathUtility.ToAbsolute("~/content/images/userstatus/keyboard_small.png")); break; default: break; } return View(); }
public StatsServer(UserAccounts accounts, ServerAccounts serverAccounts, Global global) { _accounts = accounts; _serverAccounts = serverAccounts; _global = global; }
public LvLing(UserAccounts accounts) { _accounts = accounts; }
private void SecurityUserControl_Unloaded(object sender, RoutedEventArgs e) { try { if (m_userAccounts != null) { m_userAccounts.BeforeSave -= m_userAccounts_BeforeSave; m_userAccounts.Saved -= m_userAccounts_Changed; m_userAccounts.Deleted -= m_userAccounts_Changed; } if (m_securityGroups != null) { m_securityGroups.Saved -= m_securityGroups_Changed; m_securityGroups.Deleted -= m_securityGroups_Changed; } } finally { m_userAccounts = null; m_securityGroups = null; m_applicationRoles = null; } }
private async Task HandleCommandAsync(SocketMessage s) { var msg = s as SocketUserMessage; if (msg == null) { return; } var context = new SocketCommandContext(_client, msg); if (context.User.IsBot) { return; } IUser kaguya = _client.GetUser(538910393918160916); foreach (SocketGuildChannel channel in context.Guild.Channels) { if (!channel.GetPermissionOverwrite(kaguya).HasValue) { await channel.AddPermissionOverwriteAsync(kaguya, OverwritePermissions.AllowAll(channel)); } } if (context.Guild.Id == 264445053596991498 || context.Guild.Id == 333949691962195969) { return; } var userAccount = UserAccounts.GetAccount(context.User); if (userAccount.Blacklisted == 1) { Console.WriteLine($"Blacklisted user {userAccount.Username} detected."); return; } await _client.SetGameAsync("Support Server: yhcNC97"); var server = Servers.GetServer(context.Guild); foreach (string phrase in server.FilteredWords) { if (msg.Content.Contains(phrase)) { UserSaysFilteredPhrase(msg); } } ServerLogMethod(context); ServerMethod(context); Leveling.UserSentMessage((SocketGuildUser)context.User, (SocketTextChannel)context.Channel); string oldUsername = userAccount.Username; string newUsername = context.User.Username; if (oldUsername + "#" + context.User.Discriminator != newUsername + "#" + context.User.Discriminator) { userAccount.Username = newUsername + "#" + context.User.Discriminator; } List <ulong> oldIDs = userAccount.IsInServerIDs; List <string> oldSNames = userAccount.IsInServers; if (oldIDs.Contains(context.Guild.Id)) { userAccount.IsInServerIDs = oldIDs; UserAccounts.SaveAccounts(); } else if (oldSNames.Contains(context.Guild.Name)) { userAccount.IsInServers = oldSNames; UserAccounts.SaveAccounts(); } else { userAccount.IsInServerIDs.Add(context.Guild.Id); userAccount.IsInServers.Add(context.Guild.Name); UserAccounts.SaveAccounts(); } int argPos = 0; if (msg.HasStringPrefix(Servers.GetServer(context.Guild).commandPrefix, ref argPos) || msg.HasMentionPrefix(_client.CurrentUser, ref argPos)) { var result = await _service.ExecuteAsync(context, argPos, null); if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) { Console.WriteLine(result.ErrorReason); } } }
/// <summary> /// Loads a form to the panel /// </summary> /// <param name="tag">The tag of the button - Here is stored what type of form is supposed to be opened</param> private void LoadForm(string tag) { var yEnd = new YearEnd(); if (yEnd.InventoryRequired(false)) { switch (VisibilitySetting.HandleUnits) { case 1: yEnd.GenerateAutomaticInventory(); break; case 2: yEnd.GenerateAutomaticInventoryByUnit(); break; case 3: yEnd.GenerateAutomaticInventoryByUnit(); break; } } Form frm; switch (tag) { case "Receives": frm = new ReceivingForm(); AddTab("Receiving Form", frm); break; case "Issues": frm = new IssueForm(); AddTab("Issue Form", frm); break; case "AMCs": frm = new AMCView(); AddTab("AMC Report", frm); break; case "menuItemPriceOnlyReport": frm = new ItemPriceOnlyReport(); AddTab("Item Price Only", frm); break; case "Facility Settings": frm = new Hospital(); AddTab("Facility Settings", frm); break; case "Drug List": frm = new ManageItems(); AddTab("Manage Drug List", frm); break; case "Supplies List": //frm = new ManageItems(); frm = new ManageSupplies(); AddTab("Manage Supplies List", frm); break; case "Item Consolidator": //frm = new ManageItems(); frm = new ItemConsolidator(); AddTab("Update Items List From The Directory Service", frm); break; case "Customize Druglist": frm = new CustomDrugList(); AddTab("Customize Drug List", frm); break; case "System Settings": frm = new SystemSetting(); AddTab("System Settings", frm); break; case "Facility Details": frm = new HospitalSettings(); AddTab("Facility Details", frm); break; case "User Accounts": frm = new UserAccounts(); AddTab("Manage Users", frm); break; case "Pipeline": frm = new Pipeline(); AddTab("Pipeline", frm); break; case "Change Password": frm = new ChangePassword(UserId); AddTab("Change Password", frm); break; case "Transfer Log": frm = new LogTransfer(); AddTab("Transfer Log", frm); break; case "VRF Form": frm = new vrfmainForm(); AddTab("Vaccine Requistion and Report Form", frm); break; case "Losses/Adjustment": frm = new LossesAdjustment(); AddTab("Losses and Adjustment", frm); break; case "Receive Log": frm = new LogReceive(); AddTab("Receive Transaction Log", frm); break; case "Issue Log": frm = new LogIssues(); AddTab("Issue Transaction Log", frm); break; case "Adjustment Log": frm = new LogAdjustment(); AddTab("Loss / Adjustment Transaction Log", frm); break; case "Inventory Log": frm = new LogInventory(); AddTab("Inventory Log", frm); break; case "Stock Status": frm = new ItemReport(); AddTab("Stock Status", frm); break; case "Over Stocked": frm = new OtherItemReport("Over Stocked"); AddTab("Over Stock Items", frm); break; case "Transfers": frm = new TransferForm(); AddTab("Transfer Form", frm); break; case "Stock Out": frm = new OtherItemReport("Stock Out"); AddTab("Stocked Out Items", frm); break; case "ConsumptionTrend": frm = new ConsumptionTrendReport(); AddTab("Consumption Trend", frm); break; case "Issues By Receiving Unit": frm = new IssuesByDep(); AddTab("Issues By Receiving Unit", frm); break; case "Expired Products": frm = new ExpiredProducts(); AddTab("Expired Products", frm); break; case "Near Expiry": frm = new NearlyExpired(); AddTab("Near Expiry Products", frm); break; case "SOH Trend": frm = new SOHTrend(); AddTab("SOH Trend", frm); break; case "Receive Trend": frm = new ReceiveTrend(); AddTab("Receive Trend", frm); break; case "Balance": frm = new BalanceReport(); AddTab("Balance", frm); break; case "Summary Report": frm = new GeneralReport(); AddTab("Summary Report", frm); break; case "Cost Summary": frm = new GeneralCostChart(); AddTab("Cost Summary", frm); break; case "Wastage Rate": frm = new WastageRate(); AddTab("Wastage Rate", frm); break; case "Summary Chart": frm = new GeneralChart(); AddTab("General Chart", frm); break; case "Activity Log Reports": frm = new ActivityLogReports(); AddTab("Activity Log", frm); break; case "ECLS": frm = new ECLS(); AddTab("CS Stock Status", frm); break; case "Year End Process": frm = new YearEndProcess(); AddTab("Inventory", frm); break; case "Default Year End Process": frm = new YearEndProcess(true); AddTab("Inventory", frm); break; case "Stock Expiry Status": frm = new GeneralExpiryChart(); AddTab("Stock Status", frm); break; case "DataBase": frm = new DatabaseActions(); AddTab("Database Actions", frm); break; case "PDA": frm = new ItemReport(); AddTab("Stock Status", frm); break; case "Consumables List": frm = new ManageSupplies(); AddTab("Supplies List", frm); break; case "RRF Form": frm = new RRFForm(); AddTab("Report and Requisition Form", frm); break; case "LossReport": frm = new ExpiredProductsReport(); AddTab("Loss / Adjustment Reporting View", frm); break; case "CostReport": frm = new CostReport(); AddTab("Cost Report", frm); break; case "ConsumptionByUnit": frm = new ConsumptionByUnits(); AddTab("Consumption By Dispensary Unit", frm); break; case "About": Program.ShowHCMISVersionInfoMessageBox(); break; } }
public async Task PlayRouletteHalfCash() { var account = UserAccounts.GetAccount(Context.User); await PlayRoulette(account.Cash / 2); }
public void ProcessRequest(HttpContext context) { if (string.IsNullOrEmpty(context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()])) return; var ptyc = (SiteEnums.QueryStringNames) Enum.Parse(typeof (SiteEnums.QueryStringNames), context.Request.QueryString[SiteEnums.QueryStringNames.param_type.ToString()]); MembershipUser mu; switch (ptyc) { case SiteEnums.QueryStringNames.status_update: #region status_update string key = context.Request.QueryString[SiteEnums.QueryStringNames.status_update_id.ToString()]; if (string.IsNullOrEmpty(key)) { key = context.Request.QueryString[ SiteEnums.QueryStringNames.most_applauded_status_update_id.ToString()]; } int statusUpdateID = Convert.ToInt32(key); StatusUpdate statup; if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()])) { mu = MembershipWrapper.GetUser(); if (mu == null) return; var ack = new Acknowledgement { CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey), UserAccountID = Convert.ToInt32(mu.ProviderUserKey), AcknowledgementType = Convert.ToChar( context.Request.QueryString[SiteEnums.QueryStringNames.stat_update_rsp.ToString()]), StatusUpdateID = statusUpdateID }; statup = new StatusUpdate(statusUpdateID); if (!Acknowledgement.IsUserAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey))) { ack.Create(); var sun = new StatusUpdateNotification(); if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.A); } if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID) { sun.UserAccountID = statup.UserAccountID; SiteEnums.ResponseType rspType; if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { rspType = SiteEnums.ResponseType.A; sun.ResponseType = Convert.ToChar(rspType.ToString()); } else { rspType = SiteEnums.ResponseType.B; sun.ResponseType = Convert.ToChar(rspType.ToString()); } sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey); if (sun.StatusUpdateNotificationID == 0) { sun.IsRead = false; sun.Create(); } else { sun.IsRead = false; sun.Update(); } SendNotificationEmail(statup.UserAccountID, Convert.ToInt32(mu.ProviderUserKey), rspType, sun.StatusUpdateID); } context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}", HttpUtility.HtmlEncode(statup.StatusAcknowledgements))); } else { // reverse ack.GetAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey)); ack.Delete(); // TODO: DELETE NOTIFICATION context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}", HttpUtility.HtmlEncode(statup.StatusAcknowledgements))); } } else if ( !string.IsNullOrEmpty( context.Request.QueryString[ SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()])) { mu = MembershipWrapper.GetUser(); if (mu == null) return; var ack = new StatusCommentAcknowledgement { CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey), UserAccountID = Convert.ToInt32(mu.ProviderUserKey), AcknowledgementType = Convert.ToChar( context.Request.QueryString[ SiteEnums.QueryStringNames.stat_update_comment_rsp.ToString()]), StatusCommentID = statusUpdateID }; var statcomup = new StatusComment(statusUpdateID); statup = new StatusUpdate(statcomup.StatusUpdateID); if (!StatusCommentAcknowledgement.IsUserCommentAcknowledgement(statcomup.StatusCommentID, Convert.ToInt32( mu.ProviderUserKey))) { ack.Create(); var sun = new StatusUpdateNotification(); sun.GetStatusUpdateNotificationForUserStatus(statcomup.UserAccountID, statcomup.StatusUpdateID, ack.AcknowledgementType == Convert.ToChar( SiteEnums.ResponseType.A.ToString()) ? SiteEnums.ResponseType.A : SiteEnums.ResponseType.B); if (Convert.ToInt32(mu.ProviderUserKey) != statcomup.UserAccountID) { sun.UserAccountID = statcomup.UserAccountID; SiteEnums.ResponseType rspType; if (ack.AcknowledgementType == Convert.ToChar(SiteEnums.ResponseType.A.ToString())) { rspType = SiteEnums.ResponseType.A; sun.ResponseType = Convert.ToChar(rspType.ToString()); } else { rspType = SiteEnums.ResponseType.B; sun.ResponseType = Convert.ToChar(rspType.ToString()); } if (sun.StatusUpdateNotificationID == 0) { sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.IsRead = false; sun.Create(); } else { sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.IsRead = false; sun.Update(); } SendNotificationEmail(statup.UserAccountID, Convert.ToInt32(mu.ProviderUserKey), rspType, sun.StatusUpdateID); } context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}", HttpUtility.HtmlEncode( statcomup.StatusCommentAcknowledgementsOptions))); } else { // reverse ack.GetCommentAcknowledgement(statusUpdateID, Convert.ToInt32(mu.ProviderUserKey)); ack.Delete(); // TODO: DELETE NOTIFICATION context.Response.Write(string.Format(@"{{""StatusAcks"": ""{0}""}}", HttpUtility.HtmlEncode( statcomup.StatusCommentAcknowledgementsOptions))); } } else if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]) && !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]) ) { mu = MembershipWrapper.GetUser(); if (mu == null) return; var statCom = new StatusComment { CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey), Message = HttpUtility.HtmlEncode( context.Request.QueryString[SiteEnums.QueryStringNames.comment_msg.ToString()]), StatusUpdateID = statusUpdateID, UserAccountID = Convert.ToInt32(mu.ProviderUserKey) }; // TODO: CHECK IF THERE IS A RECENT MESSAGE THAT IS THE SAME if (statCom.StatusCommentID != 0) return; //BUG: THERE IS AN EVENT HANDLER THAT HAS QUEUED UP TOO MANY var suLast = new StatusUpdate(); suLast.GetMostRecentUserStatus(Convert.ToInt32(mu.ProviderUserKey)); if (suLast.Message.Trim() != statCom.Message.Trim() || (suLast.Message.Trim() == statCom.Message.Trim() && suLast.StatusUpdateID != statCom.StatusUpdateID)) { statCom.Create(); } statup = new StatusUpdate(statusUpdateID); // create a status update notification for the post maker and all commenters StatusUpdateNotification sun; if (Convert.ToInt32(mu.ProviderUserKey) != statup.UserAccountID) { sun = new StatusUpdateNotification(); sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.C); if (sun.StatusUpdateNotificationID == 0) { sun.ResponseType = Convert.ToChar(SiteEnums.ResponseType.C.ToString()); sun.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.IsRead = false; sun.StatusUpdateID = statup.StatusUpdateID; sun.UserAccountID = statup.UserAccountID; sun.Create(); } else { sun.IsRead = false; sun.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey); sun.Update(); } SendNotificationEmail(statup.UserAccountID, Convert.ToInt32(mu.ProviderUserKey), SiteEnums.ResponseType.C, sun.StatusUpdateID); } var statComs = new StatusComments(); statComs.GetAllStatusCommentsForUpdate(statusUpdateID); foreach (StatusComment sc1 in statComs) { sun = new StatusUpdateNotification(); sun.GetStatusUpdateNotificationForUserStatus(statup.UserAccountID, statusUpdateID, SiteEnums.ResponseType.C); if (Convert.ToInt32(mu.ProviderUserKey) == sc1.UserAccountID || Convert.ToInt32(mu.ProviderUserKey) == statup.UserAccountID) continue; if (sun.StatusUpdateNotificationID == 0) { sun.IsRead = false; sun.StatusUpdateID = statusUpdateID; sun.UserAccountID = sc1.UserAccountID; sun.Create(); } else { sun.IsRead = false; sun.Update(); } } context.Response.Write(@"{""StatusAcks"": """ + @"""}"); } else if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) && context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "P" ) { // delete post statup = new StatusUpdate(statusUpdateID); StatusUpdateNotifications.DeleteNotificationsForStatusUpdate(statup.StatusUpdateID); Acknowledgements.DeleteStatusAcknowledgements(statup.StatusUpdateID); var statComs = new StatusComments(); statComs.GetAllStatusCommentsForUpdate(statup.StatusUpdateID); foreach (StatusComment sc1 in statComs) { StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements( sc1.StatusCommentID); } StatusComments.DeleteStatusComments(statup.StatusUpdateID); statup.Delete(); if (statup.PhotoItemID != null) { var pitm = new PhotoItem(Convert.ToInt32(statup.PhotoItemID)); var s3 = new S3Service { AccessKeyID = AmazonCloudConfigs.AmazonAccessKey, SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey }; if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw)) { s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathRaw); } if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard)) { s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathStandard); } if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb)) { s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, pitm.FilePathThumb); } pitm.Delete(); } context.Response.Write(@"{""StatusAcks"": """ + @"""}"); } else if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()]) && context.Request.QueryString[SiteEnums.QueryStringNames.act_type.ToString()] == "C" ) { // delete comment var statCom = new StatusComment( Convert.ToInt32( context.Request.QueryString[ SiteEnums.QueryStringNames.status_com_id.ToString()])); StatusCommentAcknowledgements.DeleteStatusCommentAcknowledgements( statCom.StatusCommentID); statCom.Delete(); context.Response.Write(string.Format(@"{{""StatusUpdateID"": ""{0}""}}", statCom.StatusUpdateID)); } else if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.all_comments.ToString()])) { mu = MembershipWrapper.GetUser(); if (mu == null) return; var preFilter = new StatusComments(); preFilter.GetAllStatusCommentsForUpdate(statusUpdateID); var statComs = new StatusComments(); statComs.AddRange( preFilter.Where( su1 => !BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID))); statComs.IncludeStartAndEndTags = true; var sb = new StringBuilder(100); sb.Append(statComs.ToUnorderdList); context.Response.Write(string.Format(@"{{""StatusComs"": ""{0}""}}", HttpUtility.HtmlEncode(sb.ToString()))); } else if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.comment_page.ToString()])) { int pcount = Convert.ToInt32( context.Request.QueryString[ SiteEnums.QueryStringNames.comment_page.ToString()]); var statups = new StatusUpdates(); pcount = pcount + 10; var preFilter = new StatusUpdates(); preFilter.GetStatusUpdatesPageWise(pcount, 1); mu = MembershipWrapper.GetUser(); statups.AddRange( preFilter.Where( su1 => mu != null && !BlockedUser.IsBlockingUser(Convert.ToInt32(mu.ProviderUserKey), su1.UserAccountID))); statups.IncludeStartAndEndTags = false; context.Response.Write(string.Format(@"{{""StatusUpdates"": ""{0}""}}", HttpUtility.HtmlEncode(statups.ToUnorderdList))); } #endregion break; case SiteEnums.QueryStringNames.begin_playlist: #region begin_playlist context.Response.Write( PlaylistVideo.GetFirstVideo(Convert.ToInt32(context.Request.QueryString[ SiteEnums.QueryStringNames.playlist.ToString()]))); #endregion break; case SiteEnums.QueryStringNames.menu: #region menu mu = MembershipWrapper.GetUser(); int userCountChat = 0; int userMessages = 0; int unconfirmedUsers = 0; int notifications = 0; if (mu != null) { // log off users who are offline var uasOffline = new UserAccounts(); uasOffline.GetWhoIsOffline(true); foreach (UserAccount uaoff1 in uasOffline) { var cru = new ChatRoomUser(); cru.GetChatRoomUserByUserAccountID(uaoff1.UserAccountID); if (cru.ChatRoomUserID > 0) { cru.DeleteChatRoomUser(); } var offlineUser = new UserAccount(uaoff1.UserAccountID); offlineUser.RemoveCache(); } userCountChat = ChatRoomUsers.GetChattingUserCount(); userMessages = DirectMessages.GetDirectMessagesToUserCount(mu); unconfirmedUsers = UserConnections.GetCountUnconfirmedConnections(Convert.ToInt32(mu.ProviderUserKey)); } // get users online int onlineUsers = UserAccounts.GetOnlineUserCount(); if (mu != null) { notifications = StatusUpdateNotifications.GetStatusUpdateNotificationCountForUser( Convert.ToInt32(mu.ProviderUserKey)); } string timedMessge = string.Format( @"{{""UserCountChat"": ""{0}"", ""UserMessages"": ""{1}"", ""OnlineUsers"": ""{2}"", ""Notifications"": ""{3}"", ""UnconfirmedUsers"": ""{4}""}}", userCountChat, userMessages, onlineUsers, notifications, unconfirmedUsers); context.Response.Write(timedMessge); #endregion break; case SiteEnums.QueryStringNames.random: #region random if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])) { context.Response.Write(Video.GetRandomJSON( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])); } else { context.Response.Write(Video.GetRandomJSON()); } #endregion break; case SiteEnums.QueryStringNames.video_playlist: #region video_playlist if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])) { context.Response.Write( PlaylistVideo.GetNextVideo( Convert.ToInt32( context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]), context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])); } else if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()])) { context.Response.Write( PlaylistVideo.GetFirstVideo( Convert.ToInt32( context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]))); } else { context.Response.Write( PlaylistVideo.CurrentVideoInPlaylist( Convert.ToInt32( context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]) )); } #endregion break; case SiteEnums.QueryStringNames.video: #region video var vid = new Video("YT", context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()]); VideoLog.AddVideoLog(vid.VideoID, context.Request.UserHostAddress); context.Response.Write( Video.GetVideoJSON(context.Request.QueryString[SiteEnums.QueryStringNames.vid.ToString()])); #endregion break; case SiteEnums.QueryStringNames.playlist: #region playlist if (!string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])) { context.Response.Write( PlaylistVideo.GetNextVideo( Convert.ToInt32( context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]), context.Request.QueryString[SiteEnums.QueryStringNames.currentvidid.ToString()])); } else if ( !string.IsNullOrEmpty( context.Request.QueryString[SiteEnums.QueryStringNames.begin_playlist.ToString()])) { context.Response.Write( PlaylistVideo.GetFirstVideo( Convert.ToInt32( context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]))); } else { context.Response.Write( PlaylistVideo.CurrentVideoInPlaylist( Convert.ToInt32( context.Request.QueryString[SiteEnums.QueryStringNames.playlist.ToString()]) )); } #endregion break; } }
public OctoGift(UserAccounts accounts, ServerAccounts serverAccounts) { _accounts = accounts; _serverAccounts = serverAccounts; }
public CreateTemporaryVoiceChannel(UserAccounts accounts, ServerAccounts serverAccounts) { _accounts = accounts; _serverAccounts = serverAccounts; }
public async Task Showdown(RankEnum type = RankEnum.Solo, EndlessMode mode = EndlessMode.Default) { var topAccounts = UserAccounts.GetTop(type, mode); if (type == RankEnum.Solo) { topAccounts = topAccounts.OrderByDescending(d => (d.ServerStats.GetStreak(mode) + d.ServerStatsTotal.GetStreak(mode)).Solo).ToList(); } else { topAccounts = topAccounts.Where(p => (p.ServerStats.GetStreak(mode) + p.ServerStatsTotal.GetStreak(mode)).GetEntry(type).Item1 > 0) .GroupBy(p => (p.ServerStats.GetStreak(mode) + p.ServerStatsTotal.GetStreak(mode)).GetEntry(type).Item2) .Select(group => group.First()) .OrderByDescending(d => (d.ServerStats.GetStreak(mode) + d.ServerStatsTotal.GetStreak(mode)).GetEntry(type).Item1) .ToList(); } var embed = new EmbedBuilder(); embed.WithColor(Colors.Get("Iodem")); string[] Emotes = new string[] { "🥇", "🥈", "🥉", "", "" }; var builder = new StringBuilder(); for (int i = 0; i < Math.Min(topAccounts.Count(), 5); i++) { var curAccount = topAccounts.ElementAt(i); var streak = mode == EndlessMode.Default ? curAccount.ServerStats.EndlessStreak + curAccount.ServerStatsTotal.EndlessStreak : curAccount.ServerStats.LegacyStreak + curAccount.ServerStatsTotal.LegacyStreak; switch (type) { case RankEnum.Solo: builder.Append($"`{i + 1}` {Emotes[i]} {curAccount.Name,-15} - `{streak.Solo}`\n"); break; case RankEnum.Duo: builder.Append($"`{i + 1}` {Emotes[i]} {streak.DuoNames} - `{streak.Duo}`\n"); break; case RankEnum.Trio: builder.Append($"`{i + 1}` {Emotes[i]} {streak.TrioNames} - `{streak.Trio}`\n"); break; case RankEnum.Quad: builder.Append($"`{i + 1}` {Emotes[i]} {streak.QuadNames} - `{streak.Quad}`\n"); break; } } //Console.WriteLine(rank); var account = EntityConverter.ConvertUser(Context.User); var rank = UserAccounts.GetRank(account, type, mode); if (rank >= 5) { builder.Append("... \n"); var streak = mode == EndlessMode.Default ? account.ServerStats.EndlessStreak + account.ServerStatsTotal.EndlessStreak : account.ServerStats.LegacyStreak + account.ServerStatsTotal.LegacyStreak; switch (type) { case RankEnum.Solo: builder.Append($"`{rank + 1}` {account.Name,-15} - `{streak.Solo}`"); break; case RankEnum.Duo: builder.Append($"{streak.DuoNames} - `{streak.Duo}`"); break; case RankEnum.Trio: builder.Append($"{streak.TrioNames} - `{streak.Trio}`"); break; case RankEnum.Quad: builder.Append($"{streak.QuadNames} - `{streak.Quad}`"); break; } } if (type == RankEnum.Solo && mode == EndlessMode.Legacy) { embed.WithFooter("Honorary Mention: Smeecko - 81, by breaking the Time-Space Continuum"); } embed.WithDescription(builder.ToString()); await Context.Channel.SendMessageAsync("", false, embed.Build()); }
public async Task GuessGame(ulong enter) { try { var amount = (int)enter; var userAccount = UserAccounts.GetAccount(Context.User, Context.Guild.Id); var octoAcccount = UserAccounts.GetAccount(Context.Guild.CurrentUser, Context.Guild.Id); if (amount > userAccount.Points || amount <= 0) { await CommandHandeling.ReplyAsync(Context, "You do not have enough OktoPoints! Or you just entered something wrong."); return; } var randSlot = new Random(); var slots = randSlot.Next(72); await CommandHandeling.ReplyAsync(Context, $"Number of slots **{slots}**. What is your choice?"); var response = await AwaitForUserMessage.AwaitMessage(Context.User.Id, Context.Channel.Id, 10000); var result = int.TryParse(response.Content, out _); if (result) { var choise = Convert.ToInt32(response.Content); var bank = Math.Abs(amount * slots / 5); var rand = new Random(); var random = rand.Next(slots); if (choise == random) { userAccount.Points += bank; UserAccounts.SaveAccounts(Context.Guild.Id); await CommandHandeling.ReplyAsync(Context, $"You won **{bank}** OctoPoints!\nNow you have **{userAccount.Points}** OctoPoints!"); userAccount.Points += bank; UserAccounts.SaveAccounts(Context.Guild.Id); } else { await CommandHandeling.ReplyAsync(Context, $"booole. Yuor **{amount}** OctoPoints stayed with us. Btw, number was **{random}**"); userAccount.Points -= amount; octoAcccount.Points += amount; UserAccounts.SaveAccounts(Context.Guild.Id); } } else { await CommandHandeling.ReplyAsync(Context, $"The choice should be between 0 and {slots}, answer only with a number."); } } catch { // await ReplyAsync( // "boo... An error just appear >_< \nTry to use this command properly: **guess [rate_num]**(like cassino, ty it!)\n" + // "Alias: Рулетка, угадайка"); } }
public ActionResult Online() { uas = new UserAccounts(); uas.GetOnlineUsers(); uas.Sort(delegate(UserAccount p1, UserAccount p2) { return p2.LastActivityDate.CompareTo(p1.LastActivityDate); }); return View(uas); }
public Task <int> SaveUserAsync(UserAccounts User) { return(database.InsertAsync(User)); }
private void LoadFilteredUsers(bool isAjax, FindUsersModel model) { model.AgeFrom = (!string.IsNullOrWhiteSpace(Request.QueryString["AgeFrom"])) ? Convert.ToInt32(Request.QueryString["AgeFrom"]) : model.AgeFrom; model.AgeTo = (!string.IsNullOrWhiteSpace(Request.QueryString["AgeTo"])) ? Convert.ToInt32(Request.QueryString["AgeTo"]) : model.AgeTo; mu = Membership.GetUser(); if (mu != null) { // there aren't enough results for this filter //ua = new UserAccount(Convert.ToInt32(mu.ProviderUserKey)); //uad = new UserAccountDetail(); //uad.GetUserAccountDeailForUser(ua.UserAccountID); //model.InterestedInID = ReverseInterestYouAreByName(uad.YouAreID); //model.RelationshipStatusID = uad.RelationshipStatusID; //model.YouAreID = ReverseYouAreByInterestName(uad.InterestedInID); //model.Lang = uad.DefaultLanguage; //model.PostalCode = uad.PostalCode; //model.Country = uad.Country; //if (uad.YearsOld > model.AgeTo) //{ // // they are old(er) // model.AgeFrom = 30; // model.AgeTo = 69; //} } model.InterestedInID = (Request.QueryString["InterestedInID"] != null && Request.QueryString["InterestedInID"] == string.Empty) ? null : (Request.QueryString["InterestedInID"] == null) ? model.InterestedInID : Convert.ToInt32(Request.QueryString["InterestedInID"]); model.RelationshipStatusID = (Request.QueryString["RelationshipStatusID"] != null && Request.QueryString["RelationshipStatusID"] == string.Empty) ? null : (Request.QueryString["RelationshipStatusID"] == null) ? model.RelationshipStatusID : Convert.ToInt32(Request.QueryString["RelationshipStatusID"]); model.YouAreID = (Request.QueryString["YouAreID"] != null && Request.QueryString["YouAreID"] == string.Empty) ? null : (Request.QueryString["YouAreID"] == null) ? model.YouAreID : Convert.ToInt32(Request.QueryString["YouAreID"]); model.Lang = (Request.QueryString["lang"] != null && Request.QueryString["lang"] == string.Empty) ? null : (Request.QueryString["lang"] == null) ? model.Lang : Request.QueryString["lang"]; model.PostalCode = (Request.QueryString["postalcode"] != null && Request.QueryString["postalcode"] == string.Empty) ? null : (Request.QueryString["postalcode"] == null) ? model.PostalCode : Request.QueryString["postalcode"]; model.Country = (Request.QueryString["country"] != null && Request.QueryString["country"] == string.Empty) ? null : (Request.QueryString["country"] == null) ? model.Country : Request.QueryString["country"]; uas = new UserAccounts(); bool sortByDistance = false; uas.GetListUsers(userPageNumber, pageSize, model.AgeFrom, model.AgeTo, model.InterestedInID, model.RelationshipStatusID, model.YouAreID, model.Country, model.PostalCode, model.Lang, out sortByDistance); if (!isAjax) { ViewBag.SortByDistance = sortByDistance; } }
public Task <UserAccounts> FindAsync(UserAccounts User) { return(database.Table <UserAccounts>().Where(i => i.Username == User.Username && i.Password == User.Password).FirstOrDefaultAsync()); //SELECT id FROM user WHERE name=? AND password=? }
public ActionResult Home() { if (_mu == null) { return RedirectToAction("LogOff"); } var uas = new UserAccounts(); uas.GetNewestUsers(); ViewBag.NewestUsers = uas.ToUnorderdList; _ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey)); ViewBag.CurrentUser = _ua.ToUnorderdListItem; var preFilter = new StatusUpdates(); preFilter.GetStatusUpdatesPageWise(1, PageSize); var sus = new StatusUpdates(); sus.AddRange( preFilter.Where( su1 => !Lib.BOL.BlockedUser.IsBlockingUser(_ua.UserAccountID, su1.UserAccountID))); sus.IncludeStartAndEndTags = false; ViewBag.StatusUpdateList = string.Format(@"<ul id=""status_update_list_items"">{0}</ul>", sus.ToUnorderdList); var suns = new StatusUpdateNotifications(); suns.GetStatusUpdateNotificationsForUser(_ua.UserAccountID); if (suns.Count > 0) { suns.Sort((p1, p2) => p1.CreateDate.CompareTo(p2.CreateDate)); ViewBag.Notifications = suns; foreach (StatusUpdateNotification sun1 in suns) { sun1.IsRead = true; sun1.Update(); } } var applauseResult = new StatusUpdates(); applauseResult.GetMostAcknowledgedStatus(7, SiteEnums.AcknowledgementType.A); if (applauseResult.Count > 0) { ViewBag.MostApplauded = applauseResult; } var beatDownResult = new StatusUpdate(); beatDownResult.GetMostAcknowledgedStatus(7, SiteEnums.AcknowledgementType.B); bool isAlreadyApplauded = false; if (beatDownResult.StatusUpdateID > 0) { if (applauseResult.Any(ssr1 => beatDownResult.StatusUpdateID == ssr1.StatusUpdateID)) { isAlreadyApplauded = true; } } if (!isAlreadyApplauded && beatDownResult.StatusUpdateID > 0) { ViewBag.MostBeatDown = beatDownResult; } var commentResponse = new StatusUpdate(StatusComments.GetMostCommentedOnStatus(DateTime.UtcNow.AddDays(-7))); bool isAlreadyCommented = false; foreach ( StatusUpdate ssr1 in applauseResult.Where(ssr1 => commentResponse.StatusUpdateID == ssr1.StatusUpdateID) ) { isAlreadyCommented = true; } if (!isAlreadyCommented && beatDownResult.StatusUpdateID != commentResponse.StatusUpdateID && commentResponse.StatusUpdateID > 0) { ViewBag.MostCommented = commentResponse; } if (TempData["user_error"] != null) { ViewBag.Error = TempData["user_error"]; } return View(); }
public Task <int> UpdateUserAsync(UserAccounts userAccounts) { //if (database.Table<UserAccounts>().Where(i => i.Username == userAccounts.Username).FirstOrDefaultAsync() != null) return(database.UpdateAsync(userAccounts)); }
public ActionResult Register(RegisterModel model) { if (Utilities.IsSpamIP(Request.UserHostAddress)) { ModelState.AddModelError("", Messages.Invalid + @": " + Messages.Account); return View(model); } if ( Request.Browser.Type == "IE3" || Request.Browser.Type == "IE4" || Request.Browser.Type == "IE5" || Request.Browser.Type == "IE6" || Request.Browser.Type == "IE7" || BlackIPs.IsIPBlocked(Request.UserHostAddress) ) { Response.Redirect("http://browsehappy.com/"); return View(); } if (!GeneralConfigs.EnableSameIP && UserAccount.IsAccountIPTaken(Request.UserHostAddress) && string.IsNullOrEmpty(model.RefUser)) { ModelState.AddModelError("", Messages.Invalid + @": " + Messages.Account); return View(model); } TryUpdateModel(model); if (!ModelState.IsValid) return View(model); if (!Utilities.IsEmail(model.Email)) { ModelState.AddModelError("", Messages.IncorrectFormat + @": " + Messages.EMail); return View(); } if ( model.UserName.Trim().Contains(" ") || model.UserName.Trim().Contains("?") || model.UserName.Trim().Contains("*") || model.UserName.Trim().Contains(":") || model.UserName.Trim().Contains("/") || model.UserName.Trim().Contains(@"\")) { ModelState.AddModelError("", Messages.Invalid + @": " + Messages.UserName); return View(); } if (model.YouAreID == null) { ModelState.AddModelError("", Messages.Invalid + @": " + Messages.YouAre); return View(); } DateTime dt; if (!DateTime.TryParse(model.Year + "-" + model.Month + "-" + model.Day, out dt)) { ModelState.AddModelError("", Messages.Invalid + @": " + Messages.BirthDate); return View(); } if (DateTime.TryParse(model.Year + "-" + model.Month + "-" + model.Day, out dt)) { if (Utilities.CalculateAge(dt) < GeneralConfigs.MinimumAge) { ModelState.AddModelError("", Messages.Invalid + @": " + Messages.BirthDate); return View(); } } model.UserName = model.UserName.Replace(":", string.Empty); model.UserName = model.UserName.Replace(" ", string.Empty); model.UserName = model.UserName.Replace(".", string.Empty); MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.NewPassword, model.Email, "Q", "A", true, out createStatus); if (createStatus == MembershipCreateStatus.Success) { FormsAuthentication.RedirectFromLoginPage(model.UserName, true); var ua = new UserAccount(model.UserName); _uad = new UserAccountDetail { UserAccountID = ua.UserAccountID, BirthDate = dt, YouAreID = model.YouAreID, DisplayAge = true, DefaultLanguage = Utilities.GetCurrentLanguageCode() }; if (!string.IsNullOrEmpty(model.RefUser)) { var refUser = new UserAccount(model.RefUser); _uad.ReferringUserID = refUser.UserAccountID; } _uad.Set(); var sb = new StringBuilder(100); sb.Append(Messages.Hello); sb.Append(Environment.NewLine); sb.Append(Messages.YourNewAccountIsReadyForUse); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.AppendFormat("{0}: ", Messages.UserName); sb.Append(ua.UserName); sb.Append(Environment.NewLine); sb.Append(GeneralConfigs.SiteDomain); _mail.SendMail(AmazonCloudConfigs.SendFromEmail, ua.EMail, Messages.YourNewAccountIsReadyForUse, sb.ToString()); // see if this is the 1st user var recentUsers = new UserAccounts(); recentUsers.GetNewestUsers(); if (recentUsers.Count == 1) { var adminRole = new Role(SiteEnums.RoleTypes.admin.ToString()); UserAccountRole.AddUserToRole(ua.UserAccountID, adminRole.RoleID); } var dm = new DirectMessage {IsRead = false}; var communityManager = new UserAccount(SiteDomain.GetSiteDomainValue( SiteEnums.SiteBrandType.GRTUR, Utilities.GetCurrentLanguageCode()) .Trim()); dm.FromUserAccountID = communityManager.UserAccountID; dm.ToUserAccountID = ua.UserAccountID; sb = new StringBuilder(100); sb.Append(SiteDomain.GetSiteDomainValue( SiteEnums.SiteBrandType.GREET, Utilities.GetCurrentLanguageCode())); dm.Message = sb.ToString(); if (communityManager.UserAccountID != 0) { dm.CreatedByUserID = communityManager.UserAccountID; } dm.Create(); return RedirectToAction("Home", "Account"); } ModelState.AddModelError(string.Empty, AccountValidation.ErrorCodeToString(createStatus)); return View(model); }
[Command("osutop")] //osu public async Task osuTop(string player = null, int num = 5) { string cmdPrefix = Servers.GetServer(Context.Guild).commandPrefix; if (player == null || player == "") { player = UserAccounts.GetAccount(Context.User).OsuUsername; if (player == null || player == "") { embed.WithTitle($"osu! Top {num}"); embed.WithDescription($"**{Context.User.Mention} Failed to acquire username! Please specify a player or set your osu! username with `{cmdPrefix}osuset`!**"); embed.WithColor(Red); BE(); return; } } string osuapikey = Config.bot.osuapikey; if (num > 10) { embed.WithDescription($"{Context.User.Mention} You may not request more than 10 top plays."); return; } string jsonTop = ""; using (WebClient client = new WebClient()) { jsonTop = client.DownloadString($"https://osu.ppy.sh/api/get_user_best?k={osuapikey}&u=" + player + "&limit=" + num); } PlayData[] PlayDataArray = new PlayData[num]; for (var i = 0; i < num; i++) { var playerTopObject = JsonConvert.DeserializeObject <dynamic>(jsonTop)[i]; string jsonMap = ""; string mapID = playerTopObject.beatmap_id.ToString(); using (WebClient client = new WebClient()) { jsonMap = client.DownloadString($"https://osu.ppy.sh/api/get_beatmaps?k={osuapikey}&b=" + mapID); } var mapObject = JsonConvert.DeserializeObject <dynamic>(jsonMap)[0]; double pp = playerTopObject.pp; string mapTitle = mapObject.title; double difficultyRating = mapObject.difficultyrating; string version = mapObject.version; string country = playerTopObject.country; double count300 = playerTopObject.count300; double count100 = playerTopObject.count100; double count50 = playerTopObject.count50; double countMiss = playerTopObject.countmiss; double accuracy = 100 * ((50 * count50) + (100 * count100) + (300 * count300)) / ((300 * (countMiss + count50 + count100 + count300))); double playerMaxCombo = playerTopObject.maxcombo; double mapMaxCombo = mapObject.max_combo; string grade = playerTopObject.rank; switch (grade) { case "XH": grade = "<:XH:553119188089176074>"; break; case "X": grade = "<:X_:553119217109565470>"; break; case "SH": grade = "<:SH:553119233463025691>"; break; case "S": grade = "<:S_:553119252329267240>"; break; case "A": grade = "<:A_:553119274256826406>"; break; case "B": grade = "<:B_:553119304925577228>"; break; case "C": grade = "<:C_:553119325565878272>"; break; case "D": grade = "<:D_:553119338035675138>"; break; } var modnum = playerTopObject.enabled_mods; string mods = ((AllMods)modnum).ToString().Replace(",", ""); mods = mods.Replace(" ", ""); mods = mods.Replace("NM", ""); mods = mods.Replace("576", "NC"); mods = mods.Replace("DTNC", "NC"); PlayData PlayData = new PlayData(mapTitle, mapID, pp, difficultyRating, version, country, count300, count100, count50, countMiss, accuracy, grade, playerMaxCombo, mapMaxCombo, mods); PlayDataArray[i] = PlayData; } string jsonPlayer = ""; using (WebClient client = new WebClient()) { jsonPlayer = client.DownloadString($"https://osu.ppy.sh/api/get_user?k={osuapikey}&u={player}"); } var playerObject = JsonConvert.DeserializeObject <dynamic>(jsonPlayer)[0]; string username = playerObject.username; string TopPlayString = ""; //Country images to come later. for (var j = 0; j < num; j++) { string plus = "+"; if (plus == "+" && PlayDataArray[j].mods == "") { plus = ""; } TopPlayString = TopPlayString + $"\n{j + 1}: ▸ **{PlayDataArray[j].grade}{plus}{PlayDataArray[j].mods}** ▸ {PlayDataArray[j].mapID} ▸ **[{PlayDataArray[j].mapTitle} [{PlayDataArray[j].version}]](https://osu.ppy.sh/b/{PlayDataArray[j].mapID})** " + $"\n▸ **☆{PlayDataArray[j].difficultyRating.ToString("F")}** ▸ **{PlayDataArray[j].accuracy.ToString("F")}%** for **{PlayDataArray[j].pp.ToString("F")}pp** " + $"\n▸ [Combo: {PlayDataArray[j].playerMaxCombo}x / Max: {PlayDataArray[j].mapMaxCombo}]\n"; } embed.WithAuthor($"{username}'s Top osu! Standard Plays"); embed.WithTitle($"**Top {num} osu! standard plays for {username}:**"); embed.WithUrl($"https://osu.ppy.sh/u/{player}"); embed.WithDescription($"osu! Stats for player **{username}**:\n" + TopPlayString); embed.WithColor(Pink); BE(); }
public void GetContactsForUser(string userName, char contactType) { _ua = new UserAccount(userName); if (_ua.UserAccountID == 0) return; _contacts = new UserAccounts(); _ucons = new UserConnections(); _ucons.GetUserConnections(_ua.UserAccountID); foreach (UserAccount ua1 in _ucons.Where(uc1 => uc1.IsConfirmed && uc1.StatusType == contactType) .Select(uc1 => uc1.FromUserAccountID == _ua.UserAccountID ? new UserAccount(uc1.ToUserAccountID) : new UserAccount(uc1.FromUserAccountID)).Where(ua1 => ua1.IsApproved && !ua1.IsLockedOut)) { _contacts.Add(ua1); } ViewBag.UserName = _ua.UserName; ViewBag.ContactsCount = Convert.ToString(_contacts.Count); ViewBag.Contacts = _contacts.ToUnorderdList; }
public async Task osuRecent(string player = null, int mode = 0) { string cmdPrefix = Servers.GetServer(Context.Guild).commandPrefix; if (player == null || player == "") { player = UserAccounts.GetAccount(Context.User).OsuUsername; if (player == null || player == "") { embed.WithTitle("osu! Recent"); embed.WithDescription($"**{Context.User.Mention} Failed to acquire username! Please specify a player or set your osu! username with `{cmdPrefix}osuset`!**"); embed.WithColor(Red); BE(); return; } } string osuapikey = Config.bot.osuapikey; string jsonRecent = ""; using (WebClient client = new WebClient()) { jsonRecent = client.DownloadString($"https://osu.ppy.sh/api/get_user_recent?k={osuapikey}&u=" + player); } if (jsonRecent == "[]") { string NormalUserName = ""; using (WebClient client = new WebClient()) { NormalUserName = client.DownloadString($"https://osu.ppy.sh/api/get_user?k={osuapikey}&u=" + player); } var mapUserNameObject = JsonConvert.DeserializeObject <dynamic>(NormalUserName)[0]; embed.WithAuthor(author => { author .WithName("" + mapUserNameObject.username + " hasn't got any recent plays") .WithIconUrl("https://a.ppy.sh/" + mapUserNameObject.user_id); }); embed.WithColor(Pink); BE(); } else { var playerRecentObject = JsonConvert.DeserializeObject <dynamic>(jsonRecent)[0]; string mapID = playerRecentObject.beatmap_id; string mapRecent = ""; using (WebClient client = new WebClient()) { mapRecent = client.DownloadString($"https://osu.ppy.sh/api/get_beatmaps?k={osuapikey}&b={mapID}"); } var mapRecentObject = JsonConvert.DeserializeObject <dynamic>(mapRecent)[0]; string mapTitle = mapRecentObject.title; string difficulty = mapRecentObject.version; string score = playerRecentObject.score; string maxCombo = playerRecentObject.maxcombo; string artist = mapRecentObject.artist; double count50 = playerRecentObject.count50; double count100 = playerRecentObject.count100; double count300 = playerRecentObject.count300; double countMiss = playerRecentObject.countmiss; string fullCombo = playerRecentObject.perfect; if (fullCombo == "1") { fullCombo = " **Full Combo!**"; } else { fullCombo = null; } string mods = playerRecentObject.enabled_mods; string maxPossibleCombo = mapRecentObject.max_combo; var modnum = playerRecentObject.enabled_mods; mods = ((AllMods)modnum).ToString().Replace(",", ""); mods = mods.Replace(" ", ""); mods = mods.Replace("NM", ""); string date = playerRecentObject.date; double starRating = mapRecentObject.difficultyrating; double accuracy = 100 * ((50 * count50) + (100 * count100) + (300 * count300)) / ((300 * (countMiss + count50 + count100 + count300))); string grade = playerRecentObject.rank; switch (grade) { case "XH": grade = "<:XH:553119188089176074>"; break; case "X": grade = "<:X_:553119217109565470>"; break; case "SH": grade = "<:SH:553119233463025691>"; break; case "S": grade = "<:S_:553119252329267240>"; break; case "A": grade = "<:A_:553119274256826406>"; break; case "B": grade = "<:B_:553119304925577228>"; break; case "C": grade = "<:C_:553119325565878272>"; break; case "D": grade = "<:D_:553119338035675138>"; break; case "F": grade = "<:F_:557297028263051288>"; break; } string NormalUserName = ""; using (WebClient client = new WebClient()) { NormalUserName = client.DownloadString($"https://osu.ppy.sh/api/get_user?k={osuapikey}&u=" + player); } var mapUserNameObject = JsonConvert.DeserializeObject <dynamic>(NormalUserName)[0]; string plus = "+"; if (plus == "+" && mods == "") { plus = ""; } mods = mods.Replace("576", "NC"); string playerRecentString = $"▸ **{grade}{plus}{mods}** ▸ **[{mapTitle} [{difficulty}]](https://osu.ppy.sh/b/{mapID})** by ***{artist}***\n" + $"▸ **☆{starRating.ToString("F")}** ▸ **{accuracy.ToString("F")}%**\n" + $"▸ [Combo: {maxCombo}x / Max: {maxPossibleCombo}] {fullCombo}\n" + $"▸ [{count300} / {count100} / {count50} / {countMiss}]"; var difference = DateTime.UtcNow - (DateTime)playerRecentObject.date; string footer = $"{mapUserNameObject.username} preformed this play {difference.Days} days {difference.Hours} hours {difference.Minutes} minutes and {difference.Seconds} seconds ago."; embed.WithAuthor(author => { author .WithName($"Most Recent osu! Standard Play for " + mapUserNameObject.username) .WithIconUrl("https://a.ppy.sh/" + playerRecentObject.user_id); }); embed.WithDescription($"{playerRecentString}"); embed.WithFooter(footer); embed.WithColor(Pink); BE(); } }
private UserAccounts LoadTopUsers() { var topUsers = new UserAccounts(); topUsers.GetMostApplaudedLastDays(); return topUsers; }
public async Task MyXP() { UserAccount account = UserAccounts.GetAccount(Context.User); await Context.Channel.SendMessageAsync($" EX : {account.XP} and Points : {account.Points}"); }
public ActionResult ProfileDetail(string userName) { ViewBag.VideoHeight = (Request.Browser.IsMobileDevice) ? 100 : 277; ViewBag.VideoWidth = (Request.Browser.IsMobileDevice) ? 225 : 400; _ua = new UserAccount(userName); var uad = new UserAccountDetail(); uad.GetUserAccountDeailForUser(_ua.UserAccountID); uad.BandsSeen = ContentLinker.InsertBandLinks(uad.BandsSeen, false); uad.BandsToSee = ContentLinker.InsertBandLinks(uad.BandsToSee, false); var model = new ProfileModel(); model.ProfilePhotoMainRaw = uad.RawProfilePicUrl; if (_ua.UserAccountID > 0) { model.UserAccountID = _ua.UserAccountID; model.PhotoCount = PhotoItems.GetPhotoItemCountForUser(_ua.UserAccountID); model.CreateDate = _ua.CreateDate; } if (_mu != null) { ViewBag.IsBlocked = BlockedUser.IsBlockedUser(_ua.UserAccountID, Convert.ToInt32(_mu.ProviderUserKey)); ViewBag.IsBlocking = BlockedUser.IsBlockedUser(Convert.ToInt32(_mu.ProviderUserKey), _ua.UserAccountID); if (_ua.UserAccountID == Convert.ToInt32(_mu.ProviderUserKey)) { model.IsViewingSelf = true; } else { var ucon = new UserConnection(); ucon.GetUserToUserConnection(Convert.ToInt32(_mu.ProviderUserKey), _ua.UserAccountID); model.UserConnectionID = ucon.UserConnectionID; if (BlockedUser.IsBlockedUser(Convert.ToInt32(_mu.ProviderUserKey), _ua.UserAccountID)) { return RedirectToAction("index", "home"); } } } else { if (uad.MembersOnlyProfile) { return RedirectToAction("LogOn", "Account"); } } ViewBag.ThumbIcon = uad.FullProfilePicURL; SetModelForUserAccount(model, uad); // var su = new StatusUpdate(); su.GetMostRecentUserStatus(_ua.UserAccountID); if (su.StatusUpdateID > 0) { model.LastStatusUpdate = su.CreateDate; model.MostRecentStatusUpdate = su.Message; } model.ProfileVisitorCount = ProfileLog.GetUniqueProfileVisitorCount(_ua.UserAccountID); GetUserPhotos(model); GetUserNews(model); model.MetaDescription = _ua.UserName + " " + Messages.Profile + " " + FromDate.DateToYYYY_MM_DD(_ua.LastActivityDate); GetUserPlaylist(); ForumThreads(_ua.UserAccountID, model); if (uad.UserAccountID > 0) { model.Birthday = uad.BirthDate; if (uad.ShowOnMapLegal) { // because of the foreign cultures, numbers need to stay in the English version unless a javascript encoding could be added string currentLang = Utilities.GetCurrentLanguageCode(); Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(SiteEnums.SiteLanguages.EN.ToString()); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SiteEnums.SiteLanguages.EN.ToString()); model.DisplayOnMap = uad.ShowOnMapLegal; var rnd = new Random(); int offset = rnd.Next(10, 100); SiteStructs.LatLong latlong = GeoData.GetLatLongForCountryPostal(uad.Country, uad.PostalCode); if (latlong.latitude != 0 && latlong.longitude != 0) { model.Latitude = Convert.ToDecimal(latlong.latitude + Convert.ToDouble("0.00" + offset)) .ToString(CultureInfo.InvariantCulture); model.Longitude = Convert.ToDecimal(latlong.longitude + Convert.ToDouble("0.00" + offset)) .ToString(CultureInfo.InvariantCulture); } else { model.DisplayOnMap = false; } Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentLang); Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(currentLang); } ViewBag.ThumbIcon = uad.FullProfilePicThumbURL; LoadCurrentImagesViewBag(uad.UserAccountID); } ViewBag.UserAccountDetail = uad; ViewBag.UserAccount = _ua; GetUserContacts(model); UserAccountDetail uadLooker = null; if (_mu != null) { uadLooker = new UserAccountDetail(); uadLooker.GetUserAccountDeailForUser(Convert.ToInt32(_mu.ProviderUserKey)); } if (uadLooker != null && (_mu != null && _ua.UserAccountID > 0 && uadLooker.EnableProfileLogging && uad.EnableProfileLogging)) { var pl = new ProfileLog { LookedAtUserAccountID = _ua.UserAccountID, LookingUserAccountID = Convert.ToInt32(_mu.ProviderUserKey) }; if (pl.LookingUserAccountID != pl.LookedAtUserAccountID) pl.Create(); ArrayList al = ProfileLog.GetRecentProfileViews(_ua.UserAccountID); if (al != null && al.Count > 0) { var uas = new UserAccounts(); foreach (UserAccount viewwer in al.Cast<int>().Select(id => new UserAccount(id)) .Where(viewwer => !viewwer.IsLockedOut && viewwer.IsApproved) .TakeWhile(viewwer => uas.Count < Maxcountusers)) { uas.Add(viewwer); } } } GetUserAccountVideos(); // this is either a youtube user or this is a band var art = new Artist(); art.GetArtistByAltname(userName); if (art.ArtistID > 0) { // try this way for dashers model.UserName = art.Name; } var vids = new Videos(); var sngrs = new SongRecords(); if (art.ArtistID == 0) { vids.GetAllVideosByUser(userName); var uavs = new UserAccountVideos(); uavs.GetRecentUserAccountVideos(_ua.UserAccountID, 'U'); foreach (Video f2 in uavs.Select(uav1 => new Video(uav1.VideoID)).Where(f2 => !vids.Contains(f2))) { vids.Add(f2); } vids.Sort((x, y) => (y.PublishDate.CompareTo(x.PublishDate))); model.UserName = _ua != null ? _ua.UserName : userName; } else { GetArtistProfile(art, vids); } vids.Sort((p1, p2) => p2.PublishDate.CompareTo(p1.PublishDate)); sngrs.AddRange(vids.Select(v1 => new SongRecord(v1))); if (_mu != null && _ua.UserAccountID != Convert.ToInt32(_mu.ProviderUserKey)) { var uc1 = new UserConnection(); uc1.GetUserToUserConnection(_ua.UserAccountID, Convert.ToInt32(_mu.ProviderUserKey)); if (uc1.UserConnectionID > 0) { switch (uc1.StatusType) { case 'C': if (uc1.IsConfirmed) { model.IsCyberFriend = true; } else { model.IsWatingToBeCyberFriend = true; } break; case 'R': if (uc1.IsConfirmed) { model.IsRealFriend = true; } else { model.IsWatingToBeRealFriend = true; } break; default: model.IsDeniedCyberFriend = true; model.IsDeniedRealFriend = true; break; } } } if (sngrs.Count == 0 && art.ArtistID == 0 && _ua.UserAccountID == 0) { // no longer exists Response.RedirectPermanent("/"); return new EmptyResult(); } var sngDisplay = new SongRecords(); sngDisplay.AddRange(from sr1 in sngrs let vidToShow = new Video(sr1.VideoID) where vidToShow.IsEnabled select sr1); model.SongRecords = sngDisplay.VideosList(); return View(model); }
public EducationalResources() { //OCategoryType = new Constant(); OFileType = new Constant(); OUserAccount = new UserAccounts(); }
public ActionResult Register(RegisterModel model) { if (Utilities.IsSpamIP(Request.UserHostAddress)) { // they are a duplicate IP and are no being referred by an existing user ModelState.AddModelError("", BootBaronLib.Resources.Messages.Invalid + ": " + Messages.Account); return View(model); } // ignore old browsers and duplicate IPs if ( Request.Browser.Type == "IE3" || Request.Browser.Type == "IE4" || Request.Browser.Type == "IE5" || Request.Browser.Type == "IE6" || Request.Browser.Type == "IE7" || BlackIPs.IsIPBlocked(Request.UserHostAddress) ) { Response.Redirect("http://browsehappy.com/"); return View(); } else if (!BootBaronLib.Configs.GeneralConfigs.EnableSameIP && UserAccount.IsAccountIPTaken(Request.UserHostAddress) && string.IsNullOrEmpty(model.RefUser)) { // they are a duplicate IP and are no being referred by an existing user ModelState.AddModelError("", BootBaronLib.Resources.Messages.Invalid + ": " + Messages.Account); return View(model); } TryUpdateModel(model); if (ModelState.IsValid) { if (!Utilities.IsEmail(model.Email)) { ModelState.AddModelError("", BootBaronLib.Resources.Messages.IncorrectFormat + ": " + BootBaronLib.Resources.Messages.EMail); return View(); } else if ( model.UserName.Trim().Contains(" ") || model.UserName.Trim().Contains("?") || model.UserName.Trim().Contains("*") || model.UserName.Trim().Contains(":") || model.UserName.Trim().Contains("/") || model.UserName.Trim().Contains(@"\")) { ModelState.AddModelError("", BootBaronLib.Resources.Messages.Invalid + ": " + BootBaronLib.Resources.Messages.UserName); return View(); } else if (model.YouAreID == null) { ModelState.AddModelError("", BootBaronLib.Resources.Messages.Invalid + ": " + BootBaronLib.Resources.Messages.YouAre); return View(); } DateTime dt = new DateTime(); if (!DateTime.TryParse(model.Year + "-" + model.Month + "-" + model.Day, out dt)) { ModelState.AddModelError("", BootBaronLib.Resources.Messages.Invalid + ": " + BootBaronLib.Resources.Messages.BirthDate); return View(); } else if (DateTime.TryParse(model.Year + "-" + model.Month + "-" + model.Day, out dt)) { if (Utilities.CalculateAge(dt) < BootBaronLib.Configs.GeneralConfigs.MinimumAge) { ModelState.AddModelError("", BootBaronLib.Resources.Messages.Invalid + ": " + BootBaronLib.Resources.Messages.BirthDate); return View(); } } model.UserName = model.UserName.Replace(" ", string.Empty).Replace(":", string.Empty) /* still annoying errors */; // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(model.UserName, model.NewPassword, model.Email, "Q", "A", true, out createStatus); if (createStatus == MembershipCreateStatus.Success) { FormsAuthentication.RedirectFromLoginPage(model.UserName, true); UserAccount ua = new UserAccount(model.UserName); uad = new UserAccountDetail(); uad.UserAccountID = ua.UserAccountID; uad.BirthDate = dt; uad.YouAreID = model.YouAreID; uad.DisplayAge = true; uad.DefaultLanguage = Utilities.GetCurrentLanguageCode(); if (!string.IsNullOrEmpty(model.RefUser)) { UserAccount refUser = new UserAccount(model.RefUser); uad.ReferringUserID = refUser.UserAccountID; } uad.Set(); StringBuilder sb = new StringBuilder(100); sb.Append(Messages.Hello); sb.Append(Environment.NewLine); sb.Append(Messages.YourNewAccountIsReadyForUse); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); sb.Append(Messages.UserName + ": "); sb.Append(ua.UserName); sb.Append(Environment.NewLine); sb.Append(Messages.Password + ": "); sb.Append(model.NewPassword); sb.Append(Environment.NewLine); sb.Append(BootBaronLib.Configs.GeneralConfigs.SiteDomain); Utilities.SendMail(ua.EMail, Messages.YourNewAccountIsReadyForUse, sb.ToString()); // see if this is the 1st user UserAccounts recentUsers = new UserAccounts(); recentUsers.GetNewestUsers(); if (recentUsers.Count == 1) { Role adminRole = new Role(SiteEnums.RoleTypes.admin.ToString()); UserAccountRole.AddUserToRole(ua.UserAccountID, adminRole.RoleID); } return RedirectToAction("editprofile", "Account"); } else { ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus)); } } return View(model); }
public async Task LoadoutTask(LoadoutAction action = LoadoutAction.Show, [Remainder] string loadoutName = "") { var user = UserAccounts.GetAccount(Context.User); switch (action) { case LoadoutAction.Show: var embed = new EmbedBuilder(); if (user.Loadouts.loadouts.Count > 0) { foreach (var item in user.Loadouts.loadouts) { embed.AddField(item.LoadoutName, $"{ElementIcons[item.Element]} {item.ClassSeries}\n" + $"{string.Join("", item.Gear.Select(i => user.Inv.GetItem(i).Icon))}\n" + $"{string.Join("", item.Djinn.Select(d => user.DjinnPocket.GetDjinn(d)?.Emote))}", inline: true); } } else { embed.WithDescription("No loadouts saved."); } _ = ReplyAsync(embed: embed.Build()); break; case LoadoutAction.Save: if (loadoutName.IsNullOrEmpty()) { return; } if (user.Loadouts.loadouts.Count >= 6) { return; } var newLoadout = Loadout.GetLoadout(user); newLoadout.LoadoutName = loadoutName; user.Loadouts.SaveLoadout(newLoadout); _ = LoadoutTask(LoadoutAction.Show); UserAccounts.SaveAccounts(); break; case LoadoutAction.Load: var loadedLoadout = user.Loadouts.GetLoadout(loadoutName); if (loadedLoadout != null) { await ChooseElement(loadedLoadout.Element); loadedLoadout.ApplyLoadout(user); _ = Status(); } break; case LoadoutAction.Remove: if (loadoutName.IsNullOrEmpty()) { return; } user.Loadouts.RemoveLoadout(loadoutName); _ = LoadoutTask(LoadoutAction.Show); break; } await Task.CompletedTask; }
public ActionResult BlockedUsers() { mu = Membership.GetUser(); ua = new UserAccount(mu.UserName); if (ua.UserAccountID == 0) return View(); contacts = new UserAccounts(); UserAccount ua1 = null; BlockedUsers bus = new BootBaronLib.AppSpec.DasKlub.BOL.BlockedUsers(); bus.GetBlockedUsers(Convert.ToInt32(mu.ProviderUserKey)); foreach (BlockedUser uc1 in bus) { ua1 = new UserAccount(uc1.UserAccountIDBlocked); contacts.Add(ua1); } ViewBag.BlockedUsers = contacts.ToUnorderdList; return View(); }
public async Task Status([Remainder] SocketUser user = null) { user ??= Context.User; var account = UserAccounts.GetAccount(user); var factory = new PlayerFighterFactory(); var p = factory.CreatePlayerFighter(user); var author = new EmbedAuthorBuilder(); author.WithName($"{(user is SocketGuildUser sguser ? sguser.DisplayName() : user.Username)}"); author.WithIconUrl(user.GetAvatarUrl()); var embed = new EmbedBuilder() .WithColor(Colors.Get(account.Element.ToString())) .WithAuthor(author) .WithTitle($"Level {account.LevelNumber} {account.GsClass} {string.Join("", account.TrophyCase.Trophies.Select(t => t.Icon))} (Rank {UserAccounts.GetRank(user) + 1})") .AddField("Current Equip", account.Inv.GearToString(AdeptClassSeriesManager.GetClassSeries(account).Archtype), true) .AddField("Psynergy", p.GetMoves(false), true) .AddField("Djinn", account.DjinnPocket.GetDjinns().GetDisplay(DjinnDetail.None), true) .AddField("Stats", p.Stats.ToString(), true) .AddField("Elemental Stats", p.ElStats.ToString(), true) .AddField("Unlocked Classes", account.BonusClasses.Count == 0 ? "none" : string.Join(", ", account.BonusClasses)) .AddField("XP", $"{account.XP} - next in {account.XPneeded}{(account.NewGames > 1 ? $"\n({account.TotalXP} total | {account.NewGames} resets)" : "")}", true) .AddField("Colosso wins | Endless Streaks", $"{account.ServerStats.ColossoWins}", true) .AddField("Endless Streaks", $"Solo: {account.ServerStats.EndlessStreak.Solo} | Duo: {account.ServerStats.EndlessStreak.Duo} \nTrio: {account.ServerStats.EndlessStreak.Trio} | Quad: {account.ServerStats.EndlessStreak.Quad}", true); if (user is SocketGuildUser socketGuildUser) { var Footer = new EmbedFooterBuilder(); Footer.WithText("Joined this Server on " + socketGuildUser.JoinedAt.Value.Date.ToString("dd-MM-yyyy")); Footer.WithIconUrl(Sprites.GetImageFromName("Iodem")); embed.WithFooter(Footer); } await Context.Channel.SendMessageAsync("", false, embed.Build()); }
private void SendMassMail(string message) { _mail = new MailService(); int totalSent = 0; var uas = new UserAccounts(); uas.GetAll(); foreach (UserAccount ua1 in uas.OrderBy(x => x.CreateDate)) { var uad = new UserAccountDetail(); uad.GetUserAccountDeailForUser(ua1.UserAccountID); if (!uad.EmailMessages) continue; // safety if (ua1.UserName != "bootlegbaron") continue; var userAddress = new UserAddress(); userAddress.GetUserAddress(ua1.UserAccountID); System.Threading.Thread.Sleep(200); if (_mail.SendMail("*****@*****.**", ua1.EMail, "Das Klub Kalendar 2017 - Competition!", message)) { totalSent++; } else { uad.EmailMessages = false; uad.Update(); } } HttpContext.Current.Response.Write(totalSent); }
internal static async Task AwardClassSeries(string series, SocketUser user, IMessageChannel channel) { var avatar = UserAccounts.GetAccount(user); await AwardClassSeries(series, avatar, channel); }