public void Add(TimeSpan? time, BoardInfo scan) { int? parent; double changeCost; FindParent(scan, out parent, out changeCost); if (changeCost == 0 && parent == Game.Replay.Actions.Count - 1) return; if (time != null) Replay.SetEndTime((TimeSpan)time); if (parent == null) { Replay.AddAction(new CreateBoardAction(scan.Width, scan.Height)); parent = Replay.Actions.Count - 1; } else { Replay.AddAction(new SelectStateAction((int)parent)); } FillImages(); BoardInfo old = Images[(int)parent]; Debug.Assert(old.Width == scan.Width && old.Height == scan.Height); foreach (GameAction action in StateDelta.Delta(BoardToGameState(old), BoardToGameState(scan))) { Replay.AddAction(action); } }
public void SetNormalColorToAllTiles(BoardInfo boardInfo) { foreach (BoardPoint point in boardInfo.AllBoardPoint) { SetNormalColorToTile(point.col, point.row); } }
public void MakeBoard(BoardInfo boardInfo) { foreach (BoardPoint point in boardInfo.AllBoardPoint) { SetTile(point.col, point.row); } }
public Hinter(BoardInfo board) { for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) for (int k = 0; k < 2; k++) { forms[i, j, k] = createHintForm(board, i, j, k == 1); } }
public static GameState BoardToGameState(BoardInfo board) { GameState gameState = new GameState(board.Width, board.Height); for (int y = 0; y < board.Height; y++) for (int x = 0; x < board.Width; x++) { gameState.Stones[x, y] = board.Board[x, y].StoneColor; gameState.Labels[x, y] = board.Board[x, y].Label; gameState.Territory[x, y] = board.Board[x, y].SmallStoneColor; } return gameState; }
public void SetNormalOrValidColorToAllTiles(GameState gameState, BoardInfo boardInfo) { // 全てのタイルカラーをNormalにする SetNormalColorToAllTiles(boardInfo); // 有効なタイルカラーを変更する BoardValues turnPlayerBoardValue = getPlayerConstValues.GetTurnPlayerBoardValue(gameState); List<BoardPoint> validPointList = boardInfo.GetValidPointList(turnPlayerBoardValue); foreach (BoardPoint point in validPointList) { SetValidColorToTile(point.col, point.row); } }
protected void Page_Load(object sender, EventArgs e) { boardObj = BoardInfoProvider.GetBoardInfo(QueryHelper.GetInteger("boardid", 0)); if (boardObj != null) { groupId = boardObj.BoardGroupID; // Check whether edited board belongs to any group if (groupId == 0) { EditedObject = null; } } boardEdit.OnCheckPermissions += new CMSAdminControl.CheckPermissionsEventHandler(boardEdit_OnCheckPermissions); }
private static HintForm createHintForm(BoardInfo board, int x, int y, bool vertical) { var hint = new HintForm(); CoordinateActors xActors = new CoordinateActors { dimensionSelector = sz => sz.Width, formExtentAssigner = coord => hint.Width = coord, formStartAssigner = coord => hint.Left = coord }; CoordinateActors yActors = new CoordinateActors { dimensionSelector = sz => sz.Height, formExtentAssigner = coord => hint.Height = coord, formStartAssigner = coord => hint.Top = coord }; CoordinateActors len = vertical ? yActors : xActors; CoordinateActors wid = vertical ? xActors : yActors; var corner = board.getCellCorner(x, y); var cellSize = board.getCellSize(x, y); int hintWidth = 1; int hintLength = len.dimensionSelector(cellSize); var center = board.getCellCenter(x, y); len.formStartAssigner(len.dimensionSelector(new Size(center)) + hintLength / 3); wid.formStartAssigner(wid.dimensionSelector(new Size(center)) - hintWidth / 2); hint.StartPosition = FormStartPosition.Manual; hint.Width = 1; hint.Height = 1; hint.Show(); len.formExtentAssigner(hintLength / 3); wid.formExtentAssigner(hintWidth); hint.Hide(); return hint; }
protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); this.mBoardId = QueryHelper.GetInteger("boardId", 0); boardObj = BoardInfoProvider.GetBoardInfo(this.mBoardId); if (boardObj != null) { this.mGroupId = boardObj.BoardGroupID; // Check whether edited board belongs to any group if (this.mGroupId == 0) { EditedObject = null; } } }
public BoardInfo ProcessImage(BoardParameters bp, Pixels pix) { BoardInfo boardInfo = null; boardInfo = new BoardInfo(bp.FieldWidth, bp.FieldHeight); int halfSize = (int)(bp.BlockSize / 2) + 1; int[,] circleRadiusData = CalculateRadii((dx, dy) => (int)Math.Sqrt(dx * dx + dy * dy), halfSize); int[,] squareRadiusData = CalculateRadii((dx, dy) => (int)Math.Max(Math.Abs(dx), Math.Abs(dy)), halfSize); for (int y = 0; y < bp.FieldHeight; y++) for (int x = 0; x < bp.FieldWidth; x++) { int px = (int)Math.Round(bp.LinedBoardRect.Left + bp.BlockSize * x); int py = (int)Math.Round(bp.LinedBoardRect.Top + bp.BlockSize * y); RawColor[] circles = RadiusColor(pix, new Point(px, py), circleRadiusData, 2 * halfSize ); RawColor[] squares = RadiusColor(pix, new Point(px, py), squareRadiusData, 2 * halfSize ); PointInfo info = new PointInfo(); info.StoneColor = GetStoneColor(circles, bp.BlockSize); info.SmallStoneColor = GetSmallStoneColor(circles, bp.BlockSize); if (info.SmallStoneColor == info.StoneColor)//Small stone is part of the real stone info.SmallStoneColor = StoneColor.None; if (GetCircleMarker(circles, bp.BlockSize, info.StoneColor)) { if (info.SmallStoneColor != StoneColor.Black)//Can't distinguish circle from small stone info.Marker = Marker.Circle; } if (GetSquareMarker(squares, bp.BlockSize, info.StoneColor)) info.Marker = Marker.Square; boardInfo.Board[x, y] = info; } //MirrorBoardInfo(boardInfo); return boardInfo; }
/// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e) { if (this.BoardID == 0) { this.BoardID = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("BoardID").ToType <int>(); } if (HttpContext.Current != null) { this.BoardSettings = this.PageContext.BoardSettings.BoardID.Equals(this.BoardID) ? this.PageContext.BoardSettings : new LoadBoardSettings(this.BoardID); } else { this.BoardSettings = new LoadBoardSettings(this.BoardID); } this.Get <StartupInitializeDb>().Run(); var token = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("token"); if (token.IsNotSet() || !token.Equals(this.BoardSettings.WebServiceToken)) { if (this.ShowErrors) { this.OutputError( "Invalid Web Service Token. Please go into your host settings and save them committing a unique web service token to the database."); } this.Get <HttpResponseBase>().End(); return; } if (Config.ForceScriptName.IsNotSet()) { // fail... ForceScriptName required for Digest. if (this.ShowErrors) { this.OutputError( @"Cannot generate digest unless YAF.ForceScriptName AppSetting is specified in your app.config (default). Please specify the full page name for YAF.NET -- usually ""default.aspx""."); } this.Get <HttpResponseBase>().End(); return; } if (this.CurrentUserID == 0) { this.CurrentUserID = this.Get <HttpRequestBase>().QueryString.GetFirstOrDefault("UserID").ToType <int>(); } // get topic hours... this.topicHours = -this.BoardSettings.DigestSendEveryXHours; this.forumData = this.Get <DataBroker>().GetSimpleForumTopic( this.BoardID, this.CurrentUserID, System.DateTime.Now.AddHours(this.topicHours), 9999); if (!this.NewTopics.Any() && !this.ActiveTopics.Any()) { if (this.ShowErrors) { this.OutputError($"No topics for the last {this.BoardSettings.DigestSendEveryXHours} hours."); this.Get <HttpResponseBase>().Write(this.GetDebug()); } this.Get <HttpResponseBase>().End(); return; } this.languageFile = UserHelper.GetUserLanguageFile( this.CurrentUserID); var theme = UserHelper.GetUserThemeFile( this.CurrentUserID, this.BoardSettings.AllowUserTheme, this.BoardSettings.Theme); var subject = string.Format(this.GetText("SUBJECT"), this.BoardSettings.Name); this.YafHead.Controls.Add( ControlHelper.MakeCssIncludeControl( BoardInfo.GetURLToContentThemes(theme.CombineWith("bootstrap-forum.min.css")))); if (subject.IsSet()) { this.YafHead.Title = subject; } }
public static BoardInfo ParseBoardInfo(string url, string name) { Match match = ThreadUrlPattern.Match(url); if (match.Success) { BoardInfo info = new BoardInfo(match.Groups["host"].Value, match.Groups["path"].Value, name); return info; } return null; }
/// <summary> /// Log activity posting /// </summary> /// <param name="bsi">Board subscription info object</param> /// <param name="bi">Message board info</param> private void LogCommentActivity(BoardMessageInfo bmi, BoardInfo bi) { string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode != ViewModeEnum.LiveSite) || (bmi == null) || (bi == null) || !bi.BoardLogActivity || !ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) || !ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) || !ActivitySettingsHelper.MessageBoardPostsEnabled(siteName)) { return; } int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); Dictionary<string, object> contactData = new Dictionary<string, object>(); contactData.Add("ContactEmail", bmi.MessageEmail); contactData.Add("ContactWebSite", bmi.MessageURL); contactData.Add("ContactLastName", bmi.MessageUserName); ModuleCommands.OnlineMarketingUpdateContactFromExternalSource(contactData, false, contactId); TreeNode currentDoc = CMSContext.CurrentDocument; var data = new ActivityData() { ContactID = contactId, SiteID = CMSContext.CurrentSiteID, Type = PredefinedActivityType.MESSAGE_BOARD_COMMENT, TitleData = bi.BoardDisplayName, ItemID = bmi.MessageBoardID, URL = URLHelper.CurrentRelativePath, ItemDetailID = bmi.MessageID, NodeID = (currentDoc != null ? currentDoc.NodeID : 0), Culture = (currentDoc != null ? currentDoc.DocumentCulture : null), Campaign = CMSContext.Campaign }; ActivityLogProvider.LogActivity(data); }
private void FirstLoad() { // this will help on positioning. BoardInfo thisBoard; thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.BoardCategory = BoardInfo.EnumBoardCategory.FarLeft; _saveRoot.BoardList.Add(thisBoard); thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.BoardCategory = BoardInfo.EnumBoardCategory.FarRight; // always holding 2 tiles. _saveRoot.BoardList.Add(thisBoard); thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = 0; // should be 0 based. thisBoard.ColumnStart = 1; // first column is for holding the last one. thisBoard.HowManyColumns = 12; _saveRoot.BoardList.Add(thisBoard); thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = 1; thisBoard.ColumnStart = 3; thisBoard.HowManyColumns = 8; _saveRoot.BoardList.Add(thisBoard); thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = 2; thisBoard.ColumnStart = 2; thisBoard.HowManyColumns = 10; _saveRoot.BoardList.Add(thisBoard); int x; for (x = 3; x <= 4; x++) { thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = x; thisBoard.ColumnStart = 1; thisBoard.HowManyColumns = 12; _saveRoot.BoardList.Add(thisBoard); } thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = 5; thisBoard.ColumnStart = 2; thisBoard.HowManyColumns = 10; _saveRoot.BoardList.Add(thisBoard); thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = 6; thisBoard.ColumnStart = 3; thisBoard.HowManyColumns = 8; _saveRoot.BoardList.Add(thisBoard); thisBoard = new BoardInfo(); thisBoard.Floor = 1; thisBoard.RowStart = 7; thisBoard.ColumnStart = 1; thisBoard.HowManyColumns = 12; _saveRoot.BoardList.Add(thisBoard); int manys; manys = 6; int row; int column; row = 1; column = 4; int tempRow; int y; for (x = 2; x <= 4; x++) { tempRow = row; var loopTo = manys; for (y = 1; y <= loopTo; y++) { thisBoard = new BoardInfo(); thisBoard.RowStart = tempRow; thisBoard.ColumnStart = column; thisBoard.HowManyColumns = manys; thisBoard.Floor = x; _saveRoot.BoardList.Add(thisBoard); tempRow += 1; } row += 1; column += 1; manys -= 2; } thisBoard = new BoardInfo(); thisBoard.Floor = 5; // might as well thisBoard.BoardCategory = BoardInfo.EnumBoardCategory.VeryTop; _saveRoot.BoardList.Add(thisBoard); }
/// <summary> /// Registers the jQuery script library. /// </summary> private static void RegisterJQuery() { if (BoardContext.Current.PageElements.PageElementExists("jquery")) { return; } var registerJQuery = true; const string Key = "JQuery-Javascripts"; // check to see if DotNetAge is around and has registered jQuery for us... if (HttpContext.Current.Items[Key] != null) { if (HttpContext.Current.Items[Key] is StringCollection collection && collection.Contains("jquery")) { registerJQuery = false; } } else if (Config.IsDotNetNuke) { // latest version of DNN should register jQuery for us... registerJQuery = false; } if (registerJQuery) { string jqueryUrl; // Check if override file is set ? if (Config.JQueryOverrideFile.IsSet()) { jqueryUrl = !Config.JQueryOverrideFile.StartsWith("http") && !Config.JQueryOverrideFile.StartsWith("//") ? BoardInfo.GetURLToScripts(Config.JQueryOverrideFile) : Config.JQueryOverrideFile; } else { jqueryUrl = BoardInfo.GetURLToScripts($"jquery-{Config.JQueryVersion}.min.js"); } // load jQuery // element.Controls.Add(ControlHelper.MakeJsIncludeControl(jqueryUrl)); ScriptManager.ScriptResourceMapping.AddDefinition( "jquery", new ScriptResourceDefinition { Path = jqueryUrl, DebugPath = BoardInfo.GetURLToScripts($"jquery-{Config.JQueryVersion}.js"), CdnPath = $"//ajax.aspnetcdn.com/ajax/jQuery/jquery-{Config.JQueryVersion}.min.js", CdnDebugPath = $"//ajax.aspnetcdn.com/ajax/jQuery/jquery-{Config.JQueryVersion}.js", CdnSupportsSecureConnection = true /*, * LoadSuccessExpression = "window.jQuery"*/ }); BoardContext.Current.PageElements.AddScriptReference("jquery"); } BoardContext.Current.PageElements.AddPageElement("jquery"); }
/// <summary> /// Initializes breadcrumb items /// </summary> private void InitializeBreadcrumbs() { ucBreadcrumbs.Items.Clear(); ucBreadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("Group_General.Boards.Boards.BackToList"), OnClientClick = ControlsHelper.GetPostBackEventReference(lnkBackHidden) + "; return false;" }); if (BoardID > 0) { board = BoardInfoProvider.GetBoardInfo(BoardID); if (board != null) { ucBreadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = board.BoardDisplayName, }); } } }
/// <summary> /// Initializes all the nested controls. /// </summary> private void SetupControls() { this.tabElem.TabControlIdPrefix = "boards"; this.tabElem.OnTabClicked += new EventHandler(tabElem_OnTabChanged); this.lnkEditBack.Text = GetString("Group_General.Boards.Boards.BackToList"); this.lnkEditBack.Click += new EventHandler(lnkEditBack_Click); // Register for the security events this.boardList.OnCheckPermissions += new CheckPermissionsEventHandler(boardList_OnCheckPermissions); this.boardEdit.OnCheckPermissions += new CheckPermissionsEventHandler(boardEdit_OnCheckPermissions); this.boardModerators.OnCheckPermissions += new CheckPermissionsEventHandler(boardModerators_OnCheckPermissions); this.boardSecurity.OnCheckPermissions += new CheckPermissionsEventHandler(boardSecurity_OnCheckPermissions); // Setup controls this.boardList.IsLiveSite = this.IsLiveSite; this.boardList.GroupID = this.GroupID; this.boardList.OnAction += new CommandEventHandler(boardList_OnAction); this.boardMessages.IsLiveSite = this.IsLiveSite; this.boardMessages.OnCheckPermissions += new CheckPermissionsEventHandler(boardMessages_OnCheckPermissions); this.boardMessages.BoardID = this.BoardID; this.boardMessages.GroupID = this.GroupID; this.boardMessages.EditPageUrl = (this.GroupID > 0) ? "~/CMSModules/Groups/CMSPages/Message_Edit.aspx" : "~/CMSModules/MessageBoards/CMSPages/Message_Edit.aspx"; this.boardEdit.IsLiveSite = this.IsLiveSite; this.boardEdit.BoardID = this.BoardID; this.boardEdit.DisplayMode = this.DisplayMode; this.boardModerators.IsLiveSite = this.IsLiveSite; this.boardModerators.BoardID = this.BoardID; this.boardSecurity.IsLiveSite = this.IsLiveSite; this.boardSecurity.BoardID = this.BoardID; this.boardSecurity.GroupID = this.GroupID; this.boardSubscriptions.IsLiveSite = this.IsLiveSite; this.boardSubscriptions.BoardID = this.BoardID; this.boardSubscriptions.GroupID = this.GroupID; // Initialize tab control string[,] tabs = new string[5, 4]; tabs[0, 0] = GetString("Group_General.Boards.Boards.Messages"); tabs[1, 0] = GetString("Group_General.Boards.Boards.Edit"); tabs[2, 0] = GetString("Group_General.Boards.Boards.Moderators"); tabs[3, 0] = GetString("Group_General.Boards.Boards.Security"); tabs[4, 0] = GetString("Group_General.Boards.Boards.SubsList"); this.tabElem.Tabs = tabs; // Initialize breadcrubms if (this.BoardID > 0) { board = BoardInfoProvider.GetBoardInfo(this.BoardID); if (board != null) { this.lblEditBack.Text = breadCrumbsSeparator + HTMLHelper.HTMLEncode(board.BoardDisplayName); } } }
public GuildLetterDialog() { Index = 671; Library = Libraries.Title; Size = new Size(236, 300); Movable = true; Sort = true; Location = new Point(100, 100); CloseButton = new MirButton { HoverIndex = 361, Index = 360, Location = new Point(Size.Width - 27, 3), Library = Libraries.Prguse2, Parent = this, PressedIndex = 362, Sound = SoundList.ButtonA }; CloseButton.Click += (o, e) => { Hide(); }; RecipientNameLabel = new MirLabel { Text = "", Parent = this, Font = new Font(Settings.FontName, 8f), ForeColour = Color.White, Location = new Point(70, 33), Size = new Size(150, 15), NotControl = true }; MessageTextBox = new MirTextBox { ForeColour = Color.White, Parent = this, Font = new Font(Settings.FontName, 8f), Location = new Point(15, 92), Size = new Size(202, 165) }; MessageTextBox.MultiLine(); SendButton = new MirButton { Index = 190, HoverIndex = 191, PressedIndex = 192, Parent = this, Library = Libraries.Title, Sound = SoundList.ButtonA, Location = new Point(30, 265) }; SendButton.Click += (o, e) => { BoardInfo info = new BoardInfo(); info.Name = RecipientNameLabel.Text; info.Text = MessageTextBox.Text; Network.Enqueue(new SendGuildHouseBoard { Mode = 0, Info = info }); Hide(); }; CancelButton = new MirButton { Index = 193, HoverIndex = 194, PressedIndex = 195, Parent = this, Library = Libraries.Title, Sound = SoundList.ButtonA, Location = new Point(135, 265) }; CancelButton.Click += (o, e) => { Hide(); }; }
/// <summary> /// Función para aprender mediante QLearning. /// </summary> /// <param name="boardInfo">Tablero de juego</param> /// <returns></returns> private IEnumerator Learn(BoardInfo boardInfo) { if (subTitle) { subTitle.text = String.Format(cultureInfo, "Número de episodios: {0:n0}", numberOfEpisodes); } if (loadingPanel) { loadingPanel.SetActive(true); } yield return(null); CellInfo nextState, currentState; // Estado actual y próximo Locomotion.MoveDirection direction; // Dirección proximo movimiento float Q, r; // Valor Q y recompensa qtable = new QTable(boardInfo); // Nueva tabla Q float maxQValue = float.MinValue; // valor máximo Q en toda la tabla float totalQValue = 0f; // Suma de todos los valores Q de la tabla var epsilon = this.epsilon; // Epsilon clone for (episode = 0; episode < numberOfEpisodes; episode++) // Episodios { // Elección de una celda de inicio aleatoria para el episodio currentState = boardInfo.CellInfos[ Random.Range(0, boardInfo.NumColumns), Random.Range(0, boardInfo.NumRows) ]; bool endOfEpisode = false; do { // Elige una nueva dirección de forma aleatoria o mediante los valores Q del estado actual // en función de epsilon, el ratio de aprendizaje-exploracion if (Random.Range(0.0f, 1.0f) < epsilon) { // Elegimos una dirección aleatoria direction = (Locomotion.MoveDirection)Random.Range(0, 4); } else { // Elegimos la mejor posición según la tabla Q direction = (Locomotion.MoveDirection)qtable.GetHighestQDirection(currentState); } // Valor Q actual para la posición (estado) actual y la nueva dirección (accion) a tomar Q = qtable[currentState, direction]; // Calculamos recompensa para la próxima posición (estado) nextState = currentState.WalkableNeighbours(boardInfo)[(int)direction]; r = GetReward(nextState); // Máximo valor de Q para el próximo estado float nextQMax = nextState != null?qtable.GetHighestQValue(nextState) : 0; // Actualizamos tabla Q float QValue = (1 - alpha) * Q + alpha * (r + gamma * nextQMax); qtable[currentState, direction] = QValue; totalQValue += QValue; maxQValue = QValue > maxQValue ? QValue : maxQValue; // Nos desplazamos al siguiente estado currentState = nextState; // Condición de parada, hemos ido a una celda no navegable o hemos llegado al final if (r == -1 || r == 100) { endOfEpisode = true; } } while (!endOfEpisode); // Reducimos epsilon, para cada vez explorar menos y usar mas lo aprendido if (epsilon >= epsilonMinimumValue) { epsilon *= epsilonDecayRate; } // Actualizamos avance float pct = (episode + 1.0f) / numberOfEpisodes; if (progressBar != null) { progressBar.value = pct; } if (progressText != null) { progressText.text = (int)(pct * 100) + "%"; } if (iterationsText != null) { iterationsText.text = "Episodios: " + (episode + 1); } if (episode % 100 == 0) { yield return(null); } } if (loadingPanel) { loadingPanel.SetActive(false); } qtable.SaveToCsv("qtable.csv"); }
/// <summary> /// Gets and bulk updates message boards. Called when the "Get and bulk update boards" button is pressed. /// Expects the CreateMessageBoard method to be run first. /// </summary> private bool GetAndBulkUpdateMessageBoards() { // Prepare the parameters string where = "BoardName LIKE N'MyNewBoard%'"; // Get the data DataSet boards = BoardInfoProvider.GetMessageBoards(where, null); if (!DataHelper.DataSourceIsEmpty(boards)) { // Loop through the individual items foreach (DataRow boardDr in boards.Tables[0].Rows) { // Create object from DataRow BoardInfo modifyBoard = new BoardInfo(boardDr); // Update the property modifyBoard.BoardDisplayName = modifyBoard.BoardDisplayName.ToUpper(); // Update the message board BoardInfoProvider.SetBoardInfo(modifyBoard); } return true; } return false; }
/// <summary> /// Creates message board. Called when the "Create board" button is pressed. /// </summary> private bool CreateMessageBoard() { // Get the tree structure TreeProvider tree = new TreeProvider(CMSContext.CurrentUser); // Get the root document TreeNode root = tree.SelectSingleNode(CMSContext.CurrentSiteName, "/", null, true); if (root != null) { // Create new message board object BoardInfo newBoard = new BoardInfo(); // Set the properties newBoard.BoardDisplayName = "My new board"; newBoard.BoardName = "MyNewBoard"; newBoard.BoardDescription = "MyNewBoard"; newBoard.BoardOpened = true; newBoard.BoardEnabled = true; newBoard.BoardAccess = 0; newBoard.BoardModerated = true; newBoard.BoardUseCaptcha = false; newBoard.BoardMessages = 0; newBoard.BoardEnableSubscriptions = true; newBoard.BoardSiteID = CMSContext.CurrentSiteID; newBoard.BoardDocumentID = root.DocumentID; // Create the message board BoardInfoProvider.SetBoardInfo(newBoard); return true; } return false; }
/// <summary> /// スレッドを開く /// </summary> /// <param name="th"></param> public override bool Open(ThreadHeader header) { if (header == null) { throw new ArgumentNullException("header"); } if (IsOpen) { throw new InvalidOperationException("既にストリームが開かれています"); } X2chKakoThreadHeader kakoheader = header as X2chKakoThreadHeader; bool retried = false; if (kakoheader != null) { kakoheader.GzipCompress = true; } Retry: // ネットワークストリームを初期化 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(header.DatUrl); req.Timeout = 30000; req.AllowAutoRedirect = false; req.Referer = header.Url; req.UserAgent = UserAgent; req.Headers.Add("Accept-Encoding", "gzip"); req.Headers.Add("Pragma", "no-cache"); req.Headers.Add("Cache-Control", "no-cache"); if (header.GotByteCount > 0) { req.AddRange(header.GotByteCount - 1); } if (header.ETag != String.Empty) { req.Headers.Add("If-None-Match", header.ETag); } _res = (HttpWebResponse)req.GetResponse(); baseStream = _res.GetResponseStream(); headerInfo = header; // OK if (_res.StatusCode == HttpStatusCode.OK || _res.StatusCode == HttpStatusCode.PartialContent) { bool encGzip = _res.ContentEncoding.EndsWith("gzip"); // Gzipを使用する場合はすべて読み込む if (encGzip) { using (GZipStream gzipInp = new GZipStream(_res.GetResponseStream(), CompressionMode.Decompress)) baseStream = FileUtility.CreateMemoryStream(gzipInp); baseStream.Position = 0; length = (int)baseStream.Length; } else { length = aboneCheck ? (int)_res.ContentLength - 1 : (int)_res.ContentLength; } headerInfo.LastModified = _res.LastModified; headerInfo.ETag = _res.Headers["ETag"]; index = header.GotResCount + 1; position = 0; isOpen = true; } else if (!retried) { _res.Close(); _res = null; if (kakoheader != null) { kakoheader.GzipCompress = !kakoheader.GzipCompress; } retried = true; goto Retry; } else if (_res.StatusCode == HttpStatusCode.Found) { if (retryServers != null && retryCount < retryServers.Length) { BoardInfo retryBoard = retryServers[retryCount++]; _res.Close(); _res = null; if (retryBoard != null) { throw new X2chRetryKakologException(retryBoard); } } } // 過去ログなのでdat落ちに設定 //0324 headerInfo.Pastlog = true; retryCount = 0; return(isOpen); }
public virtual int ChooseNextClientCell(BoardInfo clientBoard, List <int> currentShip, ClientStatistics statistics) { //if no current ship just fire random cell if (currentShip.Count == 0) { //TODO: This is a try to get most frequently used cells from statistics. Comment it for now. //if (statistics != null) //{ // int? cellIndex = GetStatisticalCellIndex(clientBoard.Board, statistics); // if (cellIndex.HasValue) // return cellIndex.Value; //} //try to guess next cell from most unexpplored space int?cell = GetCellIndexFromLongestSpace(clientBoard.Board); if (cell.HasValue) { return(cell.Value); } return(GetRandomCellIndex(clientBoard.Board)); } //if only one cell of ship is marked - try to find if it is horizontal or vertical else if (currentShip.Count == 1) { int i = currentShip[0]; //add some random decision wheter to try vertical attack first bool isVerticalTryFirst = _random.Next(100) >= 50; int j; if (isVerticalTryFirst) { if (TryAttackVertical(clientBoard.Board, i, out j)) { return(j); } if (TryAttackHorizontal(clientBoard.Board, i, out j)) { return(j); } } else { if (TryAttackHorizontal(clientBoard.Board, i, out j)) { return(j); } if (TryAttackVertical(clientBoard.Board, i, out j)) { return(j); } } throw new InvalidOperationException("Either Vertical or Horizontal attack should be possible, as if we have ship not fully destroyed, it shoud be there."); } //we have more than one cell marked in this ship, so we know if it is horizontal or vertical else { int j; currentShip.Sort(); int i = currentShip.Last(); int k = currentShip.Skip(currentShip.Count - 2).Take(1).First(); if (Math.Abs(i - k) == 10) //vertical { if (TryAttackVertical(clientBoard.Board, currentShip.Last(), out j)) { return(j); } if (TryAttackVertical(clientBoard.Board, currentShip.First(), out j)) { return(j); } throw new InvalidOperationException("Vertical attack should be possible. check board"); } else //horizontal { if (TryAttackHorizontal(clientBoard.Board, currentShip.Last(), out j)) { return(j); } if (TryAttackHorizontal(clientBoard.Board, currentShip.First(), out j)) { return(j); } throw new InvalidOperationException("Horizontal attack should be possible. check board"); } } }
/// <summary> /// Binds the data. /// </summary> private void BindData() { var board = this.GetRepository <Board>().GetById(this.PageContext.PageBoardID); using (var dt = new DataTable("Files")) { dt.Columns.Add("FileName", typeof(string)); dt.Columns.Add("Description", typeof(string)); var dr = dt.NewRow(); dr["FileName"] = BoardInfo.GetURLToContent("images/spacer.gif"); // use spacer.gif for Description Entry dr["Description"] = this.GetText("BOARD_LOGO_SELECT"); dt.Rows.Add(dr); var dir = new DirectoryInfo( this.Get <HttpRequestBase>() .MapPath($"{BoardInfo.ForumServerFileRoot}{BoardFolders.Current.Logos}")); var files = dir.GetFiles("*.*"); dt.AddImageFiles(files, BoardFolders.Current.Logos); this.BoardLogo.DataSource = dt; this.BoardLogo.DataValueField = "FileName"; this.BoardLogo.DataTextField = "Description"; this.BoardLogo.DataBind(); } this.Name.Text = board.Name; var boardSettings = this.Get <BoardSettings>(); this.CdvVersion.Text = boardSettings.CdvVersion.ToString(); // create list boxes by populating data sources from Data class var themeData = StaticDataHelper.Themes(); if (themeData.Any()) { this.Theme.DataSource = themeData; this.Theme.DataBind(); } this.Culture.DataSource = StaticDataHelper.Cultures().OrderBy(x => x.CultureNativeName); this.Culture.DataTextField = "CultureNativeName"; this.Culture.DataValueField = "CultureTag"; this.Culture.DataBind(); this.ShowTopic.DataSource = StaticDataHelper.TopicTimes(); this.ShowTopic.DataTextField = "Name"; this.ShowTopic.DataValueField = "Value"; this.ShowTopic.DataBind(); // population default notification setting options... var items = EnumHelper.EnumToDictionary <UserNotificationSetting>(); if (!boardSettings.AllowNotificationAllPostsAllTopics) { // remove it... items.Remove(UserNotificationSetting.AllTopics.ToInt()); } var notificationItems = items.Select( x => new ListItem( HtmlHelper.StripHtml(this.GetText("SUBSCRIPTIONS", x.Value)), x.Key.ToString())) .ToArray(); this.DefaultNotificationSetting.Items.AddRange(notificationItems); // Get first default full culture from a language file tag. var langFileCulture = StaticDataHelper.CultureDefaultFromFile(boardSettings.Language) ?? "en-US"; if (boardSettings.Theme.Contains(".xml")) { SetSelectedOnList(ref this.Theme, "yaf"); } else { SetSelectedOnList(ref this.Theme, boardSettings.Theme); } SetSelectedOnList(ref this.Culture, boardSettings.Culture); if (this.Culture.SelectedIndex == 0) { // If 2-letter language code is the same we return Culture, else we return a default full culture from language file SetSelectedOnList( ref this.Culture, langFileCulture.Substring(0, 2) == boardSettings.Culture ? boardSettings.Culture : langFileCulture); } SetSelectedOnList(ref this.ShowTopic, boardSettings.ShowTopicsDefault.ToString()); SetSelectedOnList( ref this.DefaultNotificationSetting, boardSettings.DefaultNotificationSetting.ToInt().ToString()); this.NotificationOnUserRegisterEmailList.Text = boardSettings.NotificationOnUserRegisterEmailList; this.EmailModeratorsOnModeratedPost.Checked = boardSettings.EmailModeratorsOnModeratedPost; this.EmailModeratorsOnReportedPost.Checked = boardSettings.EmailModeratorsOnReportedPost; this.AllowDigestEmail.Checked = boardSettings.AllowDigestEmail; this.DefaultSendDigestEmail.Checked = boardSettings.DefaultSendDigestEmail; this.ForumEmail.Text = boardSettings.ForumEmail; this.ForumBaseUrlMask.Text = boardSettings.BaseUrlMask; var item = this.BoardLogo.Items.FindByText(boardSettings.ForumLogo); if (item != null) { item.Selected = true; } this.CopyrightRemovalKey.Text = boardSettings.CopyrightRemovalDomainKey; this.DigestSendEveryXHours.Text = boardSettings.DigestSendEveryXHours.ToString(); // Copyright Link-back Algorithm // Please keep if you haven't purchased a removal or commercial license. this.CopyrightHolder.Visible = true; }
public static void Main() { Console.OutputEncoding = Encoding.UTF8; // credentials.json = {"email": "*****@*****.**", "password": "******"} var json = File.ReadAllText(@"credentials.json"); var credentials = JsonSerializer.Deserialize <Credential>(json); var api = new R6Api(credentials.Email, credentials.Password); var guids = new[] { Guid.Parse("00000000-0000-0000-0000-000000000000"), Guid.Parse("11111111-1111-1111-1111-111111111111"), Guid.Parse("22222222-2222-2222-2222-222222222222"), Guid.Parse("33333333-3333-3333-3333-333333333333"), Guid.Parse("44444444-4444-4444-4444-444444444444") }; var username = "******"; var platform = Platform.PC; Profile profile = api.Profile.GetProfileAsync(username, platform).Result; var uuid = profile.ProfileId; PlayerProgression playerProgression = api.PlayerProgression.GetPlayerProgressionAsync(uuid, platform).Result; var playerLevel = playerProgression.Level; // As of season 18, regional board (ranked and casual) statistics have merged and cross regions now BoardInfo playerRanked = api.Player.GetRankedAsync(uuid, platform).Result; var playerMMR = playerRanked.MMR; // get casual queue stats // var playerCasual = api.Player.GetCasualAsync(uuid, platform); // get season 17 ranked stats for EMEA // var playerRankedSeason17 = api.Player.GetRankedAsync(uuid, platform, Region.EMEA, 17); var seasons = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; PlayersSkillRecords playerSkillRecords = api.PlayersSkillRecordsEndpoint .GetPlayerSkillRecordsAsync(uuid, platform, Region.EMEA, seasons) .Result; var recordMMR = playerSkillRecords.SeasonsPlayerSkillRecords.Last() .RegionsPlayerSkillRecords.First() .BoardsPlayerSkillRecords.First() .PlayerSkillRecords.First() .MMR; var queues = api.PlayerStatisticsEndpoint.GetQueueStatisticsAsync(uuid, platform).Result; // Time played in ranked since recorded history (in seconds) var rankedPlaytimeInfinite = queues["rankedpvp_timeplayed:infinite"]; var gamemodes = Gamemode.All | Gamemode.Ranked | Gamemode.Unranked | Gamemode.Casual; var from = new DateTime(2020, 06, 16); // Narrative is weekly, therefore it is better thing to use UtcNow // over specific dates unless you need a specific period // var to = new DateTime(2020, 06, 16); var to = DateTime.UtcNow; var summary = api.GetSummaryAsync(uuid, gamemodes, platform, from, to).Result; var summaryKills = summary.Platforms["PC"] .Gamemodes["all"] .TeamRoles["all"].Last() .Kills; var operators = api.GetOperatorAsync(uuid, gamemodes, platform, TeamRole.Attacker | TeamRole.Defender, from, to).Result; var zofiaRankedWins = operators.Platforms["PC"] .Gamemodes["ranked"] .TeamRoles["attacker"] .Where(x => x.StatsDetail == "Zofia").First() .RoundsWon; var maps = api.GetMapAsync(uuid, gamemodes, platform, TeamRole.All | TeamRole.Attacker | TeamRole.Defender, from, to).Result; var kanalDefenderTeamKills = maps.Platforms["PC"] .Gamemodes["casual"] .TeamRoles["defender"] .Where(m => m.StatsDetail == "KANAL").First() .TeamKills; var weapons = api.GetWeaponAsync(uuid, gamemodes, platform, TeamRole.All, from, to).Result; var allSpear308HeadshotAccuracy = weapons.Platforms["PC"] .Gamemodes["all"] .TeamRoles["all"] .WeaponSlots .PrimaryWeapons .WeaponTypes .Where(t => t.WeaponTypeType == "Assault Rifles").First() .Weapons .Where(w => w.WeaponName == "SPEAR .308").First() .HeadshotAccuracy; var trends = api.GetTrendAsync(uuid, gamemodes, from, to, TeamRole.All | TeamRole.Attacker | TeamRole.Defender, TrendType.Weeks).Result; var rankedAttackKDRTrend = trends.Platforms["PC"] .Gamemodes["ranked"] .TeamRoles["attacker"].Last() .KillDeathRatio; var seasonal = api.GetSeasonalAsync(uuid, gamemodes, platform).Result; var rankedY4S4MinutesPlayed = seasonal.Platforms["PC"] .Gamemodes["ranked"] .TeamRoles["all"] .Where(s => s.SeasonYear == "Y4") .Where(s => s.SeasonNumber == "S4").First() .MinutesPlayed; var narrative = api.GetNarrativeAsync(uuid, from, to).Result; var bestMatchScoreAnyWeek = narrative.Profiles[uuid.ToString()] .Years.First() .Value.Weeks.First() .Value.BestMatchFullStatistics .Score; }
public void SyncHero(BoardInfo board, AbstractHero h1, AbstractHero h2) { InitializeBoard(board); InstantiateHeroes(h1, h2); InstantiateCreature(); }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator().NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat")).Result; // Try to subscribe new subscriber if (result == "") { // Try to create a new board BoardInfo boardInfo = null; if (BoardID == 0) { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board BoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(BoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(BoardID, BoardProperties.BoardModerators); } if (BoardID > 0) { // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("(SubscriptionApproved <> 0) AND (SubscriptionBoardID=" + BoardID + ") AND (SubscriptionEmail='" + SqlHelperClass.GetSafeQueryString(email, false) + "')", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = BoardID; bsi.SubscriptionEmail = email; if ((CMSContext.CurrentUser != null) && !CMSContext.CurrentUser.IsPublic()) { bsi.SubscriptionUserID = CMSContext.CurrentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); // Clear form txtEmail.Text = ""; if (boardInfo == null) { boardInfo = BoardInfoProvider.GetBoardInfo(BoardID); } // If subscribed, log activity if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); LogActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(CMSContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + string.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { result = GetString("board.subscription.emailexists"); } } } if (result != String.Empty) { ShowError(result); } }
/// <summary> /// Handles the PreRender event of the ForumPage control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> private void CurrentForumPage_PreRender([NotNull] object sender, [NotNull] EventArgs e) { var head = this.ForumControl.Page.Header ?? this.CurrentForumPage.FindControlRecursiveBothAs <HtmlHead>("YafHead"); if (head == null) { return; } // Link tags var appleTouchIcon = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/apple-touch-icon.png") }; appleTouchIcon.Attributes.Add("rel", "apple-touch-icon"); appleTouchIcon.Attributes.Add("sizes", "180x180"); head.Controls.Add(appleTouchIcon); var icon32 = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/favicon-32x32.png") }; icon32.Attributes.Add("rel", "icon"); icon32.Attributes.Add("sizes", "32x32"); head.Controls.Add(icon32); var icon16 = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/favicon-16x16.png") }; icon16.Attributes.Add("rel", "icon"); icon16.Attributes.Add("sizes", "16x16"); head.Controls.Add(icon16); var manifest = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/site.webmanifest") }; manifest.Attributes.Add("rel", "manifest"); head.Controls.Add(manifest); var maskIcon = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/safari-pinned-tab.svg") }; maskIcon.Attributes.Add("rel", "mask-icon"); maskIcon.Attributes.Add("color", "#5bbad5"); head.Controls.Add(maskIcon); var shortcutIcon = new HtmlLink { Href = BoardInfo.GetURLToContent("favicons/favicon.ico") }; shortcutIcon.Attributes.Add("rel", "shortcut icon"); head.Controls.Add(shortcutIcon); // Meta Tags head.Controls.Add(new HtmlMeta { Name = "msapplication-TileColor", Content = "#da532c" }); head.Controls.Add( new HtmlMeta { Name = "msapplication-config", Content = BoardInfo.GetURLToContent("favicons/browserconfig.xml") }); head.Controls.Add(new HtmlMeta { Name = "theme-color", Content = "#ffffff" }); }
public void receiveRoundUpdate(BoardInfo board) { receiveUpdate2(board); }
/// <summary> /// Reloads the data in the form. /// </summary> public override void ReloadData() { base.ReloadData(); SetupControls(); if ((mCurrentBoard == null) || (mCurrentBoard.BoardID != this.BoardID)) { // Get the board info this.mCurrentBoard = BoardInfoProvider.GetBoardInfo(this.BoardID); } EditedObject = mCurrentBoard; if (mCurrentBoard != null) { this.txtBoardCodeName.Text = mCurrentBoard.BoardName; this.txtBoardDisplayName.Text = mCurrentBoard.BoardDisplayName; this.txtBoardDescription.Text = mCurrentBoard.BoardDescription; this.txtUnsubscriptionUrl.Text = mCurrentBoard.BoardUnsubscriptionURL; this.txtBaseUrl.Text = mCurrentBoard.BoardBaseURL; this.chkBoardEnable.Checked = mCurrentBoard.BoardEnabled; this.chkBoardOpen.Checked = mCurrentBoard.BoardOpened; this.chkBoardRequireEmail.Checked = mCurrentBoard.BoardRequireEmails; this.chkSubscriptionsEnable.Checked = mCurrentBoard.BoardEnableSubscriptions; this.dtpBoardOpenFrom.SelectedDateTime = mCurrentBoard.BoardOpenedFrom; this.dtpBoardOpenTo.SelectedDateTime = mCurrentBoard.BoardOpenedTo; // Load the owner info string owner = ""; if (mCurrentBoard.BoardGroupID > 0) { owner = GetString("board.owner.group"); } else if (mCurrentBoard.BoardUserID > 0) { owner = GetString("general.user"); } else { owner = GetString("board.owner.document"); } this.lblBoardOwnerText.Text = owner; // Set base/unsubscription URL inheritance chkInheritBaseUrl.Checked = (mCurrentBoard.GetValue("BoardBaseUrl") == null); chkInheritUnsubUrl.Checked = (mCurrentBoard.GetValue("BoardUnsubscriptionUrl") == null); if (!chkInheritBaseUrl.Checked) { txtBaseUrl.Attributes.Remove("disabled"); } else { txtBaseUrl.Attributes.Add("disabled", "disabled"); } if (!chkInheritUnsubUrl.Checked) { txtUnsubscriptionUrl.Attributes.Remove("disabled"); } else { txtUnsubscriptionUrl.Attributes.Add("disabled", "disabled"); } // If the open date-time details should be displayed bool isChecked = this.chkBoardOpen.Checked; this.lblBoardOpenFrom.Attributes.Add("style", (isChecked) ? "display: block;" : "display: none;"); this.dtpBoardOpenFrom.Attributes.Add("style", (isChecked) ? "display: block;" : "display: none;"); this.lblBoardOpenTo.Attributes.Add("style", (isChecked) ? "display: block;" : "display: none;"); this.dtpBoardOpenTo.Attributes.Add("style", (isChecked) ? "display: block;" : "display: none;"); if (this.plcOnline.Visible) { this.chkLogActivity.Checked = this.mCurrentBoard.BoardLogActivity; } } }
/// <summary> /// Gets full path to the given theme file. /// </summary> /// <param name="filename"> /// Short name of theme file. /// </param> /// <returns> /// The build theme path. /// </returns> public string BuildThemePath([NotNull] string filename) { CodeContracts.VerifyNotNull(filename, "filename"); return(BoardInfo.GetURLToContentThemes(this.ThemeFile.CombineWith(filename))); }
protected void btnOk_Click(object sender, EventArgs e) { if (!CheckPermissions("cms.messageboards", CMSAdminControl.PERMISSION_MODIFY)) { return; } this.mCurrentBoard = BoardInfoProvider.GetBoardInfo(this.BoardID); if (this.mCurrentBoard != null) { string errMsg = ValidateForm(); // If the entries were valid if (string.IsNullOrEmpty(errMsg)) { // Get info on existing board try { // Update board information if (this.plcCodeName.Visible) { this.mCurrentBoard.BoardName = this.txtBoardCodeName.Text; } this.mCurrentBoard.BoardDisplayName = this.txtBoardDisplayName.Text; this.mCurrentBoard.BoardDescription = this.txtBoardDescription.Text; this.mCurrentBoard.BoardEnabled = this.chkBoardEnable.Checked; this.mCurrentBoard.BoardOpened = this.chkBoardOpen.Checked; this.mCurrentBoard.BoardOpenedFrom = this.dtpBoardOpenFrom.SelectedDateTime; this.mCurrentBoard.BoardOpenedTo = this.dtpBoardOpenTo.SelectedDateTime; if (!IsLiveSite) { this.mCurrentBoard.BoardUnsubscriptionURL = chkInheritUnsubUrl.Checked ? null : this.txtUnsubscriptionUrl.Text.Trim(); this.mCurrentBoard.BoardBaseURL = chkInheritBaseUrl.Checked ? null : this.txtBaseUrl.Text.Trim(); } this.mCurrentBoard.BoardRequireEmails = this.chkBoardRequireEmail.Checked; this.mCurrentBoard.BoardEnableSubscriptions = this.chkSubscriptionsEnable.Checked; if (plcOnline.Visible) { this.mCurrentBoard.BoardLogActivity = this.chkLogActivity.Checked; } // Save changes BoardInfoProvider.SetBoardInfo(this.mCurrentBoard); // Inform user on success this.lblInfo.Text = GetString("general.changessaved"); this.lblInfo.Visible = true; // Refresh tree if external parent if (this.ExternalParent) { ltlScript.Text = ScriptHelper.GetScript("window.parent.parent.frames['tree'].RefreshNode('" + this.mCurrentBoard.BoardDisplayName + "', '" + this.mCurrentBoard.BoardID + "')"); } // Refresh the fields initiaized with JavaScript ReloadData(); } catch (Exception ex) { this.lblError.Visible = true; this.lblError.Text = GetString("general.erroroccurred") + " " + ex.Message; } } else { // Inform user on error this.lblError.Visible = true; this.lblError.Text = errMsg; } } }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (this.CheckFloodProtection && this.IsLiveSite && FloodProtectionHelper.CheckFlooding(CMSContext.CurrentSiteName, CMSContext.CurrentUser)) { lblError.Visible = true; lblError.Text = GetString("General.FloodProtection"); return; } CurrentUserInfo currentUser = CMSContext.CurrentUser; BoardMessageInfo messageInfo = null; if (MessageID > 0) { // Get message info messageInfo = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = messageInfo.MessageBoardID; } else { // Create new info messageInfo = new BoardMessageInfo(); // User IP adress messageInfo.MessageUserInfo.IPAddress = Request.UserHostAddress; // User agent messageInfo.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info messageInfo.MessageEmail = txtEmail.Text.Trim(); messageInfo.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if ((url != "http://") && (url != "https://") && (url != "")) { if ((!url.ToLower().StartsWith("http://")) && (!url.ToLower().StartsWith("https://"))) { url = "http://" + url; } } else { url = ""; } messageInfo.MessageURL = url; messageInfo.MessageURL = messageInfo.MessageURL.ToLower().Replace("javascript", "_javascript"); messageInfo.MessageUserName = this.txtUserName.Text.Trim(); if (!currentUser.IsPublic()) { messageInfo.MessageUserID = currentUser.UserID; } messageInfo.MessageIsSpam = ValidationHelper.GetBoolean(this.chkSpam.Checked, false); if (this.BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { messageInfo.MessageRatingValue = ratingControl.CurrentRating; } BoardInfo boardInfo = null; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(this.BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board this.MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(this.MessageBoardID, this.BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(this.MessageBoardID, this.BoardProperties.BoardModerators); } if (boardInfo != null) { // If the very new message is inserted if (this.MessageID == 0) { // If creating message set inserted to now and assign to board messageInfo.MessageInserted = currentUser.DateTimeNow; messageInfo.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { messageInfo.MessageApprovedByUserID = currentUser.UserID; messageInfo.MessageApproved = true; } else { // Is board moderated ? messageInfo.MessageApprovedByUserID = 0; messageInfo.MessageApproved = !boardInfo.BoardModerated; } } else { if (this.chkApproved.Checked) { // Set current user as approver messageInfo.MessageApproved = true; messageInfo.MessageApprovedByUserID = currentUser.UserID; } else { messageInfo.MessageApproved = false; messageInfo.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(CMSContext.CurrentUser, CMSContext.CurrentSiteName)) { // Columns to check Dictionary<string, int> collumns = new Dictionary<string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check errorMessage = BadWordsHelper.CheckBadWords(messageInfo, collumns, "MessageApproved", "MessageApprovedByUserID", messageInfo.MessageText, currentUser.UserID); // Additionaly check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(messageInfo)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = messageInfo.MessageEmail; // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("SubscriptionBoardID=" + this.MessageBoardID + " AND SubscriptionEmail='" + SqlHelperClass.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = this.MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.SetBoardSubscriptionInfo(bsi); ClearForm(); LogSubscribingActivity(bsi, boardInfo); } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(messageInfo); LogCommentActivity(messageInfo, boardInfo); // If the board is moderated let the user know message is waiting for approval if (boardInfo.BoardModerated && (messageInfo.MessageApproved == false)) { this.lblInfo.Text = GetString("board.messageedit.waitingapproval"); this.lblInfo.Visible = true; } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(messageInfo); } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } } if (errorMessage != "") { lblError.Text = errorMessage; lblError.Visible = true; } else { // Regenerate new captcha captchaElem.GenerateNew(); } }
//Método para movimiento del personaje public int Search(BoardInfo board, CellInfo currentPos, CellInfo[] goals) { CreateNodesBoard(board, goals[0]); return(FindNextMovement(board, nodes[currentPos.ColumnId, currentPos.RowId], nodes[goals[0].ColumnId, goals[0].RowId])); }
/// <summary> /// Log activity (subscribing). /// </summary> /// <param name="bsi">Board subscription info object</param> /// <param name="bi">Message board info</param> private void LogSubscribingActivity(BoardSubscriptionInfo bsi, BoardInfo bi) { string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode != ViewModeEnum.LiveSite) || (bsi == null) || (bi == null) || !bi.BoardLogActivity || !ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) || !ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) || !ActivitySettingsHelper.MessageBoardSubscriptionEnabled(siteName)) { return; } TreeNode currentDoc = CMSContext.CurrentDocument; var data = new ActivityData() { ContactID = ModuleCommands.OnlineMarketingGetCurrentContactID(), SiteID = CMSContext.CurrentSiteID, Type = PredefinedActivityType.SUBSCRIPTION_MESSAGE_BOARD, TitleData = bi.BoardDisplayName, URL = URLHelper.CurrentRelativePath, NodeID = (currentDoc != null ? currentDoc.NodeID : 0), Culture = (currentDoc != null ? currentDoc.DocumentCulture : null), Campaign = CMSContext.Campaign }; ActivityLogProvider.LogActivity(data); }
/* * Metodo de búsqueda: Primero busca el enemigo mas cercano y lo asigna a una variable global. * Teniendo un enemigo como objetivo, asigna el nodo de inicio a la lista abierta para luego comenzar a expandir * los nodos vecinos hasta llegar al nivel 3 (gCos), verificando que no fueran visitados anteriormente, posteriormente * asigna los valores de la fórmula f(n) = g(n) + h(n), asigna la dirección que fue tomada * para llegar a ellos y como nodo padre el nodo que se esta expandiendo. Finalmente se agrega * a la lista abierta cada nodo no visitado, se elimina el actual y se ordena la lista abierta, para regresar el primer * noto que se encuentre en el nivel 3, ya que al estar ordenada la lista, es el mas cercano para realizar el movimiento. */ private int FindNextMovement(BoardInfo board, Node start, Node goal) { // Obtiene el enemigo mas cercano para la iteración en curso foreach (GameObject enem in board.Enemies) { if (enem != null) { float manhattanD = ManhatanDistance(start, enem.transform.position.x, enem.transform.position.y); if (manhattanD < enemyDist) { enemyDist = manhattanD; enemy = enem; } } } if (enemy == null) // cuando todos los enemigos han sido eliminados regresa 9999 { return(9999); } openList = new List <Node>(); openList.Add(start); start.gCost = 0.0f; start.fCost = enemyDist; Node node = null; while (openList.Count != 0) { node = openList[0]; // Si el nodo en curso tiene gCost 3, significa que esta en nivel 3 y regresa la función "CalculatePath" con este nodo if (node.gCost >= 3) { return(CalculatePath(node)); } // si el nodo actual tiene la misma posición que el enemigo, regresa la función "CalculatePath" con este nodo if (node.position[0] == (int)enemy.transform.position.x && node.position[1] == (int)enemy.transform.position.y) { return(CalculatePath(node)); } //Crea una lista para almacenar la posición y dirección tomada List <int[]> neighbours = GetNeighbours(node, board); for (int i = 0; i < neighbours.Count; i++) { int[] neighbourNode = neighbours[i]; int x = neighbourNode[0]; int y = neighbourNode[1]; if (!nodes[x, y].isVisited) { float neighbourHCost = ManhatanDistance(nodes[x, y], enemy.transform.position.x, enemy.transform.position.y); nodes[x, y].gCost += node.gCost; nodes[x, y].parent = node; nodes[x, y].direction = neighbourNode[2]; nodes[x, y].fCost = nodes[x, y].gCost + neighbourHCost; if (!openList.Contains(nodes[x, y])) { openList.Add(nodes[x, y]); openList.Sort(); } } } //Nodo se cambia a visitado node.isVisited = true; //se elimina de la lista abierta openList.Remove(node); openList.Sort(); } return(CalculatePath(node)); }
/// <summary> /// Add the given CSS to the page header within a style tag /// </summary> /// <param name="cssUrlContent">Content of the CSS URL.</param> public void RegisterCssIncludeContent(string cssUrlContent) { this.RegisterCssInclude( BoardContext.Current.CurrentForumPage.TopPageControl, BoardInfo.GetURLToContent(cssUrlContent)); }
/// <summary> /// Binds the data. /// </summary> private void BindData() { var user = this.PageContext.CurrentForumPage.IsAdminPage ? this.GetRepository <User>().GetById(this.currentUserId) : this.PageContext.User; this.DeleteAvatar.Visible = false; this.NoAvatar.Visible = false; this.AvatarUploadRow.Visible = this.PageContext.CurrentForumPage.IsAdminPage || this.PageContext.BoardSettings.AvatarUpload; this.AvatarOurs.Visible = this.PageContext.CurrentForumPage.IsAdminPage || this.PageContext.BoardSettings.AvatarGallery; if (this.AvatarOurs.Visible) { var avatars = new List <NamedParameter> { new(this.GetText("OURAVATAR"), BoardInfo.GetURLToContent("images/spacer.gif")) }; var dir = new DirectoryInfo( this.Get <HttpRequestBase>() .MapPath($"{BoardInfo.ForumServerFileRoot}{this.Get<BoardFolders>().Avatars}")); var files = dir.GetFiles("*.*").ToList(); avatars.AddImageFiles(files, this.Get <BoardFolders>().Avatars); if (avatars.Any()) { this.AvatarGallery.DataSource = avatars; this.AvatarGallery.DataValueField = "Value"; this.AvatarGallery.DataTextField = "Name"; this.AvatarGallery.DataBind(); } else { this.AvatarOurs.Visible = false; } } if (!user.AvatarImage.IsNullOrEmptyField()) { this.AvatarImg.ImageUrl = $"{BoardInfo.ForumClientFileRoot}resource.ashx?u={this.currentUserId}&v={DateTime.Now.Ticks}"; this.DeleteAvatar.Visible = true; } else if (user.Avatar.IsSet()) { if (!user.Avatar.StartsWith("/")) { return; } var item = this.AvatarGallery.Items.FindByValue(user.Avatar); if (item == null) { return; } this.AvatarImg.ImageUrl = user.Avatar; item.Selected = true; this.DeleteAvatar.Visible = true; } else if (this.PageContext.BoardSettings.AvatarGravatar) { var x = new MD5CryptoServiceProvider(); var bs = Encoding.UTF8.GetBytes(this.PageContext.MembershipUser.Email); bs = x.ComputeHash(bs); var s = new StringBuilder(); bs.ForEach(b => s.Append(b.ToString("x2").ToLower())); var emailHash = s.ToString(); var gravatarUrl = $"https://www.gravatar.com/avatar/{emailHash}.jpg?r={this.PageContext.BoardSettings.GravatarRating}"; this.AvatarImg.ImageUrl = gravatarUrl; this.NoAvatar.Text = "Gravatar Image"; this.NoAvatar.Visible = true; } else { this.AvatarImg.ImageUrl = "../images/noavatar.svg"; this.NoAvatar.Visible = true; } this.AvatarImg.Attributes.CssStyle.Add("max-width", this.PageContext.BoardSettings.AvatarWidth.ToString()); this.AvatarImg.Attributes.CssStyle.Add("max-height", this.PageContext.BoardSettings.AvatarHeight.ToString()); }
/// <summary> /// Initializes the control elements. /// </summary> private void SetupControl() { // If the control shouldn't proceed further if (BoardProperties.StopProcessing) { Visible = false; return; } else { btnLeaveMessage.Attributes.Add("onclick", "ShowSubscription(0, '" + hdnSelSubsTab.ClientID + "','" + pnlMsgEdit.ClientID + "','" + pnlMsgSubscription.ClientID + "'); return false; "); btnSubscribe.Attributes.Add("onclick", " ShowSubscription(1, '" + hdnSelSubsTab.ClientID + "','" + pnlMsgEdit.ClientID + "','" + pnlMsgSubscription.ClientID + "'); return false; "); // Show/hide appropriate control based on current selection form hidden field if (ValidationHelper.GetInteger(hdnSelSubsTab.Value, 0) == 0) { pnlMsgEdit.Style.Remove("display"); pnlMsgEdit.Style.Add("display", "block"); pnlMsgSubscription.Style.Remove("display"); pnlMsgSubscription.Style.Add("display", "none"); } else { pnlMsgSubscription.Style.Remove("display"); pnlMsgSubscription.Style.Add("display", "block"); pnlMsgEdit.Style.Remove("display"); pnlMsgEdit.Style.Add("display", "none"); } // Set the repeater rptBoardMessages.QueryName = "board.message.selectall"; rptBoardMessages.ZeroRowsText = HTMLHelper.HTMLEncode(NoMessagesText) + "<br /><br />"; rptBoardMessages.ItemDataBound += rptBoardMessages_ItemDataBound; rptBoardMessages.TransformationName = MessageTransformation; // Set the labels msgEdit.ResourcePrefix = FormResourcePrefix; lblLeaveMessage.ResourceString = "board.messageboard.leavemessage"; lblNewSubscription.ResourceString = "board.newsubscription"; btnSubscribe.Text = GetString("board.messageboard.subscribe"); btnLeaveMessage.Text = GetString("board.messageboard.leavemessage"); // Pass the properties down to the message edit control msgEdit.BoardProperties = BoardProperties; msgEdit.MessageBoardID = MessageBoardID; msgEdit.OnAfterMessageSaved += msgEdit_OnAfterMessageSaved; msgSubscription.BoardProperties = BoardProperties; plcBtnSubscribe.Visible = BoardProperties.BoardEnableSubscriptions; pnlMsgSubscription.Visible = BoardProperties.BoardEnableSubscriptions; // If the message board exist and is enabled bi = BoardInfoProvider.GetBoardInfo(MessageBoardID); if (bi != null) { // Get basic info on users permissions userVerified = BoardInfoProvider.IsUserAuthorizedToManageMessages(bi); if (bi.BoardEnabled) { // If the board is moderated remember it if (bi.BoardModerated) { BoardProperties.BoardModerated = true; } // Reload messages ReloadBoardMessages(); // If the message board is opened users can add the messages bool displayAddMessageForm = BoardInfoProvider.IsUserAuthorizedToAddMessages(bi); // Hide 'add message' form when anonymous read disabled and user is not authenticated displayAddMessageForm &= (BoardProperties.BoardEnableAnonymousRead || AuthenticationHelper.IsAuthenticated()); if (displayAddMessageForm) { // Display the 'add the message' control DisplayAddMessageForm(); } else { HideAddMessageForm(); } msgSubscription.BoardID = bi.BoardID; } else { // Hide the control Visible = false; } } else { // The repeater is not rendered, but the NoMessageText has to be visible. HideMessages(); zeroRowsText.Visible = true; zeroRowsText.Text = rptBoardMessages.ZeroRowsText; // Decide whether the 'Leave message' dialog should be displayed if (BoardInfoProvider.IsUserAuthorizedToAddMessages(BoardProperties)) { DisplayAddMessageForm(); } else { // Hide the dialog, but set message board ID in case that board closed just while entering HideAddMessageForm(); } } } }
/// <summary> /// 板を開く /// </summary> /// <param name="info"></param> public override bool Open(BoardInfo info) { if (info == null) { throw new ArgumentNullException("info"); } if (isOpen) { throw new InvalidOperationException("既にストリームが開かれています"); } Redirect: // 板の移転チェック bool trace = false; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(info.Url + "subject.txt"); req.Timeout = 30000; req.UserAgent = UserAgent; req.AllowAutoRedirect = false; req.Headers.Add("Accept-Encoding", "gzip"); req.Headers.Add("Pragma", "no-cache"); req.Headers.Add("Cache-Control", "no-cache"); _res = (HttpWebResponse)req.GetResponse(); //IAsyncResult ar = req.BeginGetResponse(null, null); //if (!ar.IsCompleted) //{ // if (canceled) // { // req.Abort(); // return false; // } // Thread.Sleep(100); //} //_res = (HttpWebResponse)req.EndGetResponse(ar); baseStream = _res.GetResponseStream(); boardinfo = info; // Subject.txtが取得できてContent-Lengthが0、 // またはStatusCodeがFoundの場合は板が移転したかも if (_res.StatusCode == HttpStatusCode.OK) { position = 0; length = (int)_res.ContentLength; isOpen = true; if (_res.ContentEncoding.EndsWith("gzip")) { using (GZipStream gzipInp = new GZipStream(baseStream, CompressionMode.Decompress)) baseStream = FileUtility.CreateMemoryStream(gzipInp); length = (int)baseStream.Length; } if (length == 0) { trace = true; } } else { if (_res.StatusCode == HttpStatusCode.Found) { trace = true; } _res.Close(); _res = null; } if (trace) { // 板移転の可能性 X2chServerTracer tracer = new X2chServerTracer(); if (tracer.Trace(boardinfo, true)) { BoardInfo newbrd = tracer.Result; OnServerChange(new ServerChangeEventArgs(boardinfo, newbrd, tracer.TraceList)); if (AutoRedirect) { info = newbrd; if (_res != null) { _res.Close(); } goto Redirect; } } } return(isOpen); }
public void MarkCellsAroundShip(BoardInfo clientBoard, ShipInfo ship) { int cell; if (ship.IsVertical) { cell = ship.Cells.First(); //if ship is not in the leftmost column if (cell % 10 > 0) { for (int i = 0; i < ship.Cells.Length; i++) { //mark cells from the left are empty cell = ship.Cells[i]; MarkCellAsEmptySafe(clientBoard.Board, cell - 1); } //corner (diagonal) cells on the left cell = ship.Cells.First(); MarkCellAsEmptySafe(clientBoard.Board, cell - 11); cell = ship.Cells.Last(); MarkCellAsEmptySafe(clientBoard.Board, cell + 9); } cell = ship.Cells.First(); //if ship is not in the rightmost column if ((cell + 1) % 10 > 0) { for (int i = 0; i < ship.Cells.Length; i++) { //mark cells from the left are empty cell = ship.Cells[i]; MarkCellAsEmptySafe(clientBoard.Board, cell + 1); } //corner (diagonal) cells on the right cell = ship.Cells.First(); MarkCellAsEmptySafe(clientBoard.Board, cell - 9); cell = ship.Cells.Last(); MarkCellAsEmptySafe(clientBoard.Board, cell + 11); } //cell above first cell cell = ship.Cells.First(); MarkCellAsEmptySafe(clientBoard.Board, cell - 10); //cell below last cell cell = ship.Cells.Last(); MarkCellAsEmptySafe(clientBoard.Board, cell + 10); } else { //if ship starts not in the left-most column, mark cells from the left are empty cell = ship.Cells.First(); if (cell % 10 > 0) { MarkCellAsEmptySafe(clientBoard.Board, cell - 11); MarkCellAsEmptySafe(clientBoard.Board, cell - 1); MarkCellAsEmptySafe(clientBoard.Board, cell + 9); } //if ship ends not in the right-most column, mark cells from the right are empty cell = ship.Cells.Last(); if ((cell + 1) % 10 > 0) { MarkCellAsEmptySafe(clientBoard.Board, cell - 9); MarkCellAsEmptySafe(clientBoard.Board, cell + 1); MarkCellAsEmptySafe(clientBoard.Board, cell + 11); } //for all cells mark cells from top and bottom for (int i = 0; i < ship.Cells.Length; i++) { cell = ship.Cells[i]; MarkCellAsEmptySafe(clientBoard.Board, cell - 10); MarkCellAsEmptySafe(clientBoard.Board, cell + 10); } } }
void msgEdit_OnAfterMessageSaved(BoardMessageInfo message) { if ((bi == null) && (message != null) && (message.MessageBoardID > 0)) { this.MessageBoardID = message.MessageBoardID; // Get updated board informnation bi = BoardInfoProvider.GetBoardInfo(message.MessageBoardID); userVerified = BoardInfoProvider.IsUserAuthorizedToManageMessages(bi); } this.rptBoardMessages.ClearCache(); ReloadData(); }
/// <summary> /// Displays specified control. /// </summary> /// <param name="selectedControl">Control to be displayed</param> /// <param name="reload">If True, ReloadData on child control is called</param> private void DisplayControl(SelectedControlEnum selectedControl, bool reload) { // First hide and stop all elements this.plcList.Visible = false; this.boardList.StopProcessing = true; this.plcTabs.Visible = true; this.plcTabsHeader.Visible = true; this.tabEdit.Visible = false; this.boardEdit.StopProcessing = true; this.tabMessages.Visible = false; this.boardMessages.StopProcessing = true; this.tabModerators.Visible = false; this.boardModerators.StopProcessing = true; this.tabSecurity.Visible = false; this.boardSecurity.StopProcessing = true; this.tabSubscriptions.Visible = false; this.boardSubscriptions.StopProcessing = true; // Set correct tab this.SelectedControl = selectedControl; this.pnlContent.CssClass = "TabBody"; // Enable currently selected element switch (selectedControl) { case SelectedControlEnum.Listing: this.pnlContent.CssClass = ""; this.plcTabs.Visible = false; this.plcTabsHeader.Visible = false; this.plcList.Visible = true; this.boardList.StopProcessing = false; if (reload) { this.boardList.ReloadData(); } break; case SelectedControlEnum.General: this.tabEdit.Visible = true; this.boardEdit.StopProcessing = false; if (reload) { this.boardEdit.ReloadData(); } break; case SelectedControlEnum.Messages: this.tabMessages.Visible = true; this.boardMessages.StopProcessing = false; if (reload) { this.boardMessages.IsLiveSite = this.IsLiveSite; this.boardMessages.BoardID = ValidationHelper.GetInteger(ViewState["BoardID"], 0); this.boardMessages.ReloadData(); } // Breadcrumbs if (board == null) { board = BoardInfoProvider.GetBoardInfo(this.BoardID); if (board != null) { this.lblEditBack.Text = breadCrumbsSeparator + HTMLHelper.HTMLEncode(board.BoardDisplayName); } } break; case SelectedControlEnum.Moderators: this.tabModerators.Visible = true; this.boardModerators.StopProcessing = false; if (reload) { this.boardModerators.ReloadData(true); } break; case SelectedControlEnum.Security: this.tabSecurity.Visible = true; this.boardSecurity.StopProcessing = false; if (reload) { this.boardSecurity.ReloadData(); } break; case SelectedControlEnum.Subscriptions: this.tabSubscriptions.Visible = true; this.boardSubscriptions.StopProcessing = false; if (reload) { this.boardSubscriptions.BoardID = this.BoardID; this.boardSubscriptions.ReloadData(); } break; } }
/// <summary> /// Log activity (subscribing) /// </summary> /// <param name="bsi"></param> private void LogActivity(BoardSubscriptionInfo bsi, BoardInfo bi) { string siteName = CMSContext.CurrentSiteName; if ((CMSContext.ViewMode != ViewModeEnum.LiveSite) || (bsi == null) || (bi == null) || !bi.BoardLogActivity || !ActivitySettingsHelper.ActivitiesEnabledAndModuleLoaded(siteName) || !ActivitySettingsHelper.ActivitiesEnabledForThisUser(CMSContext.CurrentUser) || !ActivitySettingsHelper.MessageBoardSubscriptionEnabled(siteName) ) { return; } TreeNode currentDoc = CMSContext.CurrentDocument; int contactId = ModuleCommands.OnlineMarketingGetCurrentContactID(); Dictionary<string, object> contactData = new Dictionary<string, object>(); contactData.Add("ContactEmail", bsi.SubscriptionEmail); ModuleCommands.OnlineMarketingUpdateContactFromExternalSource(contactData, false, contactId); var data = new ActivityData() { ContactID = contactId, SiteID = CMSContext.CurrentSiteID, Type = PredefinedActivityType.SUBSCRIPTION_MESSAGE_BOARD, TitleData = bi.BoardName, URL = URLHelper.CurrentRelativePath, NodeID = (currentDoc != null ? currentDoc.NodeID : 0), Culture = (currentDoc != null ? currentDoc.DocumentCulture : null), Campaign = CMSContext.Campaign }; ActivityLogProvider.LogActivity(data); }
private void buttonGo_Click(object sender, System.EventArgs e) { result = (BoardInfo)listBoxServ.SelectedItem; }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check if message board is opened if (!IsBoardOpen()) { return; } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == "") { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } var currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo messageInfo; if (MessageID > 0) { // Get message info messageInfo = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = messageInfo.MessageBoardID; } else { // Create new info messageInfo = new BoardMessageInfo(); // User IP address messageInfo.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent messageInfo.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info messageInfo.MessageEmail = TextHelper.LimitLength(txtEmail.Text.Trim(), txtEmail.MaxLength); messageInfo.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if (!String.IsNullOrEmpty(url)) { string protocol = URLHelper.GetProtocol(url); if (String.IsNullOrEmpty(protocol)) { url = "http://" + url; } } messageInfo.MessageURL = TextHelper.LimitLength(url, txtURL.MaxLength); messageInfo.MessageURL = messageInfo.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); messageInfo.MessageUserName = TextHelper.LimitLength(txtUserName.Text.Trim(), txtUserName.MaxLength); if ((messageInfo.MessageID <= 0) && (!currentUser.IsPublic())) { messageInfo.MessageUserID = currentUser.UserID; if (!plcUserName.Visible) { messageInfo.MessageUserName = GetDefaultUserName(); } } messageInfo.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { messageInfo.MessageRatingValue = ratingControl.CurrentRating; // Update document rating, remember rating in cookie TreeProvider.RememberRating(DocumentContext.CurrentDocument); } BoardInfo boardInfo; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { if (BoardInfoProvider.IsUserAuthorizedToAddMessages(boardInfo)) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board messageInfo.MessageInserted = DateTime.Now; messageInfo.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { messageInfo.MessageApprovedByUserID = currentUser.UserID; messageInfo.MessageApproved = true; } else { // Is board moderated ? messageInfo.MessageApprovedByUserID = 0; messageInfo.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver messageInfo.MessageApproved = true; messageInfo.MessageApprovedByUserID = currentUser.UserID; } else { messageInfo.MessageApproved = false; messageInfo.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary<string, int> collumns = new Dictionary<string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check bool validateUserName = plcUserName.Visible; errorMessage = BadWordsHelper.CheckBadWords(messageInfo, collumns, "MessageApproved", "MessageApprovedByUserID", messageInfo.MessageText, currentUser.UserID, () => ValidateMessage(messageInfo, validateUserName)); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(messageInfo, validateUserName)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = messageInfo.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); LogSubscribingActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + String.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(messageInfo); LogCommentActivity(messageInfo, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (messageInfo.MessageApproved == false) { ShowInformation(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(messageInfo); } // Hide message form if user has rated and empty rating is not allowed if (BoardProperties.CheckIfUserRated) { if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } else if (String.IsNullOrEmpty(errorMessage)) { errorMessage = ResHelper.GetString("general.actiondenied"); } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
/// <summary> /// Log activity (subscribing) /// </summary> private void LogActivity(BoardSubscriptionInfo bsi, BoardInfo bi) { Activity activity = new ActivitySubscriptionMessageBoard(bi, bsi, CMSContext.CurrentDocument, CMSContext.ActivityEnvironmentVariables); activity.Log(); }
/// <summary> /// Log activity (subscribing) /// </summary> private void LogActivity(BoardSubscriptionInfo bsi, BoardInfo bi) { Activity activity = new ActivitySubscriptionMessageBoard(bi, bsi, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); activity.Log(); }
/// <summary> /// Validates form entries. /// </summary> private string ValidateForm() { string errMsg = new Validator().NotEmpty(txtBoardDisplayName.Text.Trim(), rfvBoardDisplayName.ErrorMessage).Result; if (txtBoardCodeName.Visible && String.IsNullOrEmpty(errMsg)) { errMsg = new Validator().NotEmpty(txtBoardCodeName.Text.Trim(), rfvBoardCodeName.ErrorMessage).Result; if (!ValidationHelper.IsCodeName(txtBoardCodeName.Text.Trim())) { errMsg = GetString("general.errorcodenameinidentifierformat"); } } if (!dtpBoardOpenFrom.IsValidRange() || !dtpBoardOpenTo.IsValidRange()) { errMsg = GetString("general.errorinvaliddatetimerange"); } if (string.IsNullOrEmpty(errMsg)) { // Check if the board with given name doesn't exist for particular document BoardInfo bi = BoardInfoProvider.GetBoardInfo(txtBoardCodeName.Text.Trim(), Board.BoardDocumentID); if ((bi != null) && (bi.BoardID != BoardID)) { errMsg = GetString("general.codenameexists"); } if (errMsg == "") { // If the board is open check date-time settings if (chkBoardOpen.Checked) { //// Initialize default values DateTime from = DateTimeHelper.ZERO_TIME; DateTime to = DateTimeHelper.ZERO_TIME; bool wasWrongDateTime = true; //// Check if the date-time value is in valid format bool isValidDateTime = ((DateTime.TryParse(dtpBoardOpenFrom.DateTimeTextBox.Text, out from) || string.IsNullOrEmpty(dtpBoardOpenFrom.DateTimeTextBox.Text)) && (DateTime.TryParse(dtpBoardOpenTo.DateTimeTextBox.Text, out to) || string.IsNullOrEmpty(dtpBoardOpenTo.DateTimeTextBox.Text))); // Check if the date-time doesn't overleap if (isValidDateTime) { // If the date-time values are valid if ((from <= to) || ((from == DateTimeHelper.ZERO_TIME) || (to == DateTimeHelper.ZERO_TIME))) { wasWrongDateTime = false; } } if (wasWrongDateTime) { errMsg = GetString("board.edit.wrongtime"); } } } } return(errMsg); }
/// <summary> /// 指定した板を開きます。 /// </summary> /// <param name="board"></param> public abstract bool Open(BoardInfo board);
public async Task <HttpResponseMessage> UpdateUpload() { BoardInfo info = new BoardInfo(); // 요청이 multipart/form-data를 담고 있는지 확인 if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } //업로드 경로생성 string fullPath = ConfigurationManager.AppSettings["FilePath"].ToString(); var provider = new CustomMultipartFormDataStreamProvider(fullPath); List <Boardfile> list = new List <Boardfile>(); try { await Request.Content.ReadAsMultipartAsync(provider); //정보입력 info.boardId = Int32.Parse(provider.FormData.GetValues("boardId").SingleOrDefault()); info.userId = provider.FormData.GetValues("userId").SingleOrDefault(); info.boardTitle = provider.FormData.GetValues("boardTitle").SingleOrDefault(); info.boardContent = provider.FormData.GetValues("boardContent").SingleOrDefault(); //먼저 신규파일있을시 파일 info담기 for (int i = 0; i < provider.FileData.Count; i++) { Boardfile file = new Boardfile { fileName = provider.FileData[i].Headers.ContentDisposition.FileName.Replace("\"", string.Empty).ToString(), filePath = provider.FileData[i].LocalFileName, fileGuid = provider.FileData[i].LocalFileName.Substring(provider.FileData[i].LocalFileName.IndexOf("Upload") + 7) }; list.Add(file); } info.BoardFileList = list; } catch (Exception) { } // 기존 파일처리(삭제 데이터) //cnt = 기존 파일데이터 삭제 개수 int cnt = Int32.Parse(provider.FormData.GetValues("dFileCnt").SingleOrDefault()); //삭제 파일있을시 if (cnt > 0) { //FileId를 기준으로 삭제 for (int i = 0; i < cnt; i++) { int dFile = Int32.Parse(provider.FormData.GetValues("dFile" + (i + 1)).SingleOrDefault()); _BoardBiz.DeleteBoardFile(dFile); // DB,서버 동시삭제 } } //파일처리 END //업데이트 처리 //정보 업데이트(신규파일 등록 && 정보 업데이트) if ((_BoardBiz.UpdateBoardInfo(info)) && (_BoardBiz.RegisterBoardFile(list, info.boardId))) { return(Request.CreateResponse(HttpStatusCode.OK)); } return(Request.CreateResponse(HttpStatusCode.NotModified)); }
private void SetupControls() { // Get resource strings this.lblModerators.Text = GetString("board.moderators.title") + ResHelper.Colon; this.chkBoardModerated.Text = GetString("board.moderators.ismoderated"); this.userSelector.CurrentSelector.OnSelectionChanged += new EventHandler(CurrentSelector_OnSelectionChanged); board = BoardInfoProvider.GetBoardInfo(this.BoardID); if (this.BoardID > 0) { EditedObject = board; } if (board != null) { userSelector.BoardID = this.BoardID; userSelector.GroupID = board.BoardGroupID; userSelector.CurrentSelector.SelectionMode = SelectionModeEnum.Multiple; userSelector.ShowSiteFilter = false; userSelector.SiteID = CMSContext.CurrentSiteID; userSelector.CurrentValues = GetModerators(); userSelector.IsLiveSite = this.IsLiveSite; } }
/// <summary> /// Initializes the control elements. /// </summary> private void SetupControl() { // If the control shouldn't proceed further if (this.BoardProperties.StopProcessing) { this.Visible = false; return; } else { btnLeaveMessage.Attributes.Add("onclick", "ShowSubscription(0, '" + hdnSelSubsTab.ClientID + "','" + pnlMsgEdit.ClientID + "','" + pnlMsgSubscription.ClientID + "'); return false; "); btnSubscribe.Attributes.Add("onclick", " ShowSubscription(1, '" + hdnSelSubsTab.ClientID + "','" + pnlMsgEdit.ClientID + "','" + pnlMsgSubscription.ClientID + "'); return false; "); // Show/hide appropriate control based on current selection form hidden field if (ValidationHelper.GetInteger(hdnSelSubsTab.Value, 0) == 0) { pnlMsgEdit.Style.Remove("display"); pnlMsgEdit.Style.Add("display", "block"); pnlMsgSubscription.Style.Remove("display"); pnlMsgSubscription.Style.Add("display", "none"); } else { pnlMsgSubscription.Style.Remove("display"); pnlMsgSubscription.Style.Add("display", "block"); pnlMsgEdit.Style.Remove("display"); pnlMsgEdit.Style.Add("display", "none"); } // Set the repeater this.rptBoardMessages.QueryName = "board.message.selectall"; this.rptBoardMessages.ZeroRowsText = HTMLHelper.HTMLEncode(this.NoMessagesText) + "<br /><br />"; this.rptBoardMessages.ItemDataBound += new RepeaterItemEventHandler(rptBoardMessages_ItemDataBound); this.rptBoardMessages.TransformationName = this.MessageTransformation; // Set the labels this.lblLeaveMessage.ResourceString = "board.messageboard.leavemessage"; this.lblNewSubscription.ResourceString = "board.newsubscription"; this.btnSubscribe.Text = GetString("board.messageboard.subscribe"); this.btnLeaveMessage.Text = GetString("board.messageboard.leavemessage"); // Pass the properties down to the message edit control this.msgEdit.BoardProperties = this.BoardProperties; this.msgEdit.OnAfterMessageSaved += new OnAfterMessageSavedEventHandler(msgEdit_OnAfterMessageSaved); this.msgSubscription.BoardProperties = this.BoardProperties; this.plcBtnSubscribe.Visible = this.BoardProperties.BoardEnableSubscriptions; // If the message board exist and is enabled bi = BoardInfoProvider.GetBoardInfo(this.MessageBoardID); if (bi != null) { // Get basic info on users permissions userVerified = BoardInfoProvider.IsUserAuthorizedToManageMessages(bi); if (bi.BoardEnabled) { // If the board is moderated remember it if (bi.BoardModerated) { this.BoardProperties.BoardModerated = true; } // Reload messages ReloadBoardMessages(); // If the message board is opened users can add the messages bool displayAddMessageForm = BoardInfoProvider.IsUserAuthorizedToAddMessages(bi); // Hide 'add message' form when anonymous read disabled and user is not authenticated displayAddMessageForm &= (BoardProperties.BoardEnableAnonymousRead || CMSContext.CurrentUser.IsAuthenticated()); if (displayAddMessageForm) { // Display the 'add the message' control DisplayAddMessageForm(); } else { this.msgEdit.MessageBoardID = this.MessageBoardID; this.msgEdit.Visible = false; this.pnlMsgEdit.Visible = false; } msgSubscription.BoardID = bi.BoardID; } else { // Hide the control this.Visible = false; } } else { // Decide whether the 'Leave message' dialog should be displayed if (BoardInfoProvider.IsUserAuthorizedToAddMessages(this.BoardProperties)) { DisplayAddMessageForm(); } else { // Hide the dialog, but set message board ID in case that board closed just while entering this.pnlMsgEdit.Visible = false; this.msgEdit.StopProcessing = false; } } } }
public void Awake() { _info = G.BoardInfo; _maxOnBoard = _info.MaxTileOnBoard; }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned ip if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { lblError.Visible = true; lblError.Text = GetString("General.BannedIP"); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator().NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat")).Result; // Try to subscribe new subscriber if (result == "") { // Try to create a new board BoardInfo boardInfo = null; if (this.BoardID == 0) { // Create new message board according to webpart properties boardInfo = new BoardInfo(this.BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board this.BoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(this.BoardID, this.BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(this.BoardID, this.BoardProperties.BoardModerators); } if (this.BoardID > 0) { // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("SubscriptionBoardID=" + this.BoardID + " AND SubscriptionEmail='" + SqlHelperClass.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = this.BoardID; bsi.SubscriptionEmail = email; if ((CMSContext.CurrentUser != null) && !CMSContext.CurrentUser.IsPublic()) { bsi.SubscriptionUserID = CMSContext.CurrentUser.UserID; } BoardSubscriptionInfoProvider.SetBoardSubscriptionInfo(bsi); lblInfo.Visible = true; lblInfo.Text = GetString("board.subscription.beensubscribed"); // Clear form txtEmail.Text = ""; if (boardInfo == null) { boardInfo = BoardInfoProvider.GetBoardInfo(this.BoardID); } LogActivity(bsi, boardInfo); } else { result = GetString("board.subscription.emailexists"); } } } if (result != String.Empty) { lblError.Visible = true; lblError.Text = result; } }
protected void btnOk_Click(object sender, EventArgs e) { // Let the parent control now new message is being saved if (OnBeforeMessageSaved != null) { OnBeforeMessageSaved(); } // Check if message board is opened if (!IsBoardOpen()) { return; } // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Validate form string errorMessage = ValidateForm(); if (errorMessage == String.Empty) { // Check flooding when message being inserted through the LiveSite if (CheckFloodProtection && IsLiveSite && FloodProtectionHelper.CheckFlooding(SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(GetString("General.FloodProtection")); return; } var currentUser = MembershipContext.AuthenticatedUser; BoardMessageInfo message; if (MessageID > 0) { // Get message info message = BoardMessageInfoProvider.GetBoardMessageInfo(MessageID); MessageBoardID = message.MessageBoardID; } else { // Create new info message = new BoardMessageInfo(); // User IP address message.MessageUserInfo.IPAddress = RequestContext.UserHostAddress; // User agent message.MessageUserInfo.Agent = Request.UserAgent; } // Setup message info message.MessageEmail = txtEmail.Text.Trim(); message.MessageText = txtMessage.Text.Trim(); // Handle message URL string url = txtURL.Text.Trim(); if (!String.IsNullOrEmpty(url)) { string protocol = URLHelper.GetProtocol(url); if (String.IsNullOrEmpty(protocol)) { url = "http://" + url; } } message.MessageURL = TextHelper.LimitLength(url, txtURL.MaxLength); message.MessageURL = message.MessageURL.ToLowerCSafe().Replace("javascript", "_javascript"); message.MessageUserName = TextHelper.LimitLength(txtUserName.Text.Trim(), txtUserName.MaxLength); if ((message.MessageID <= 0) && (!currentUser.IsPublic())) { message.MessageUserID = currentUser.UserID; if (!plcUserName.Visible) { message.MessageUserName = GetDefaultUserName(); } } message.MessageIsSpam = ValidationHelper.GetBoolean(chkSpam.Checked, false); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { message.MessageRatingValue = ratingControl.CurrentRating; // Update document rating, remember rating in cookie TreeProvider.RememberRating(DocumentContext.CurrentDocument); } BoardInfo boardInfo; // If there is message board if (MessageBoardID > 0) { // Load message board boardInfo = Board; } else { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board MessageBoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(MessageBoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(MessageBoardID, BoardProperties.BoardModerators); } if (boardInfo != null) { if (BoardInfoProvider.IsUserAuthorizedToAddMessages(boardInfo)) { // If the very new message is inserted if (MessageID == 0) { // If creating message set inserted to now and assign to board message.MessageInserted = DateTime.Now; message.MessageBoardID = MessageBoardID; // Handle auto approve action bool isAuthorized = BoardInfoProvider.IsUserAuthorizedToManageMessages(boardInfo); if (isAuthorized) { message.MessageApprovedByUserID = currentUser.UserID; message.MessageApproved = true; } else { // Is board moderated ? message.MessageApprovedByUserID = 0; message.MessageApproved = !boardInfo.BoardModerated; } } else { if (chkApproved.Checked) { // Set current user as approver message.MessageApproved = true; message.MessageApprovedByUserID = currentUser.UserID; } else { message.MessageApproved = false; message.MessageApprovedByUserID = 0; } } if (!AdvancedMode) { if (!BadWordInfoProvider.CanUseBadWords(MembershipContext.AuthenticatedUser, SiteContext.CurrentSiteName)) { // Columns to check Dictionary <string, int> collumns = new Dictionary <string, int>(); collumns.Add("MessageText", 0); collumns.Add("MessageUserName", 250); // Perform bad words check bool validateUserName = plcUserName.Visible; errorMessage = BadWordsHelper.CheckBadWords(message, collumns, "MessageApproved", "MessageApprovedByUserID", message.MessageText, currentUser.UserID, () => ValidateMessage(message, validateUserName)); // Additionally check empty fields if (errorMessage == string.Empty) { if (!ValidateMessage(message, validateUserName)) { errorMessage = GetString("board.messageedit.emptybadword"); } } } } // Subscribe this user to message board if (chkSubscribe.Checked) { string email = message.MessageEmail; // Check for duplicate e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("((SubscriptionApproved = 1) OR (SubscriptionApproved IS NULL)) AND SubscriptionBoardID=" + MessageBoardID + " AND SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "'", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = MessageBoardID; bsi.SubscriptionEmail = email; if (!currentUser.IsPublic()) { bsi.SubscriptionUserID = currentUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); ClearForm(); if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); Service.Resolve <ICurrentContactMergeService>().UpdateCurrentContactEmail(bsi.SubscriptionEmail, MembershipContext.AuthenticatedUser); LogSubscribingActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + String.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { errorMessage = GetString("board.subscription.emailexists"); } } if (errorMessage == "") { try { // Save message info BoardMessageInfoProvider.SetBoardMessageInfo(message); Service.Resolve <ICurrentContactMergeService>().UpdateCurrentContactEmail(message.MessageEmail, MembershipContext.AuthenticatedUser); LogCommentActivity(message, boardInfo); if (BoardProperties.EnableContentRating && (ratingControl != null) && (ratingControl.GetCurrentRating() > 0)) { LogRatingActivity(ratingControl.CurrentRating); } // If the message is not approved let the user know message is waiting for approval if (message.MessageApproved == false) { ShowInformation(GetString("board.messageedit.waitingapproval")); } // Rise after message saved event if (OnAfterMessageSaved != null) { OnAfterMessageSaved(message); } // Hide message form if user has rated and empty rating is not allowed if (BoardProperties.CheckIfUserRated) { if (!BoardProperties.AllowEmptyRating && TreeProvider.HasRated(DocumentContext.CurrentDocument)) { pnlMessageEdit.Visible = false; lblAlreadyrated.Visible = true; } else { // Hide rating form if user has rated if (BoardProperties.EnableContentRating && (ratingControl != null) && ratingControl.GetCurrentRating() > 0) { plcRating.Visible = false; } } } // Clear form content ClearForm(); } catch (Exception ex) { errorMessage = ex.Message; } } } else if (String.IsNullOrEmpty(errorMessage)) { errorMessage = ResHelper.GetString("general.actiondenied"); } } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } }
/// <summary> /// Log activity posting /// </summary> /// <param name="bmi">Board subscription info object</param> /// <param name="bi">Message board info</param> private void LogCommentActivity(BoardMessageInfo bmi, BoardInfo bi) { Activity activity = new ActivityMessageBoardComment(bmi, bi, DocumentContext.CurrentDocument, AnalyticsContext.ActivityEnvironmentVariables); activity.Log(); }
/// <summary> /// Log activity (subscribing). /// </summary> /// <param name="bsi">Board subscription info object</param> /// <param name="bi">Message board info</param> private void LogSubscribingActivity(BoardSubscriptionInfo bsi, BoardInfo bi) { mMessageBoardActivityLogger.LogMessageBoardSubscriptionActivity(bi, bsi, DocumentContext.CurrentDocument); }
/// <summary> /// OK click handler. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check banned IP if (!BannedIPInfoProvider.IsAllowed(SiteContext.CurrentSiteName, BanControlEnum.AllNonComplete)) { ShowError(GetString("General.BannedIP")); return; } // Check input fields string email = txtEmail.Text.Trim(); string result = new Validator().NotEmpty(email, rfvEmailRequired.ErrorMessage) .IsEmail(email, GetString("general.correctemailformat")).Result; // Try to subscribe new subscriber if (result == "") { // Try to create a new board BoardInfo boardInfo = null; if (BoardID == 0) { // Create new message board according to webpart properties boardInfo = new BoardInfo(BoardProperties); BoardInfoProvider.SetBoardInfo(boardInfo); // Update information on current message board BoardID = boardInfo.BoardID; // Set board-role relationship BoardRoleInfoProvider.SetBoardRoles(BoardID, BoardProperties.BoardRoles); // Set moderators BoardModeratorInfoProvider.SetBoardModerators(BoardID, BoardProperties.BoardModerators); } if (BoardID > 0) { // Check for duplicit e-mails DataSet ds = BoardSubscriptionInfoProvider.GetSubscriptions("(SubscriptionApproved <> 0) AND (SubscriptionBoardID=" + BoardID + ") AND (SubscriptionEmail='" + SqlHelper.GetSafeQueryString(email, false) + "')", null); if (DataHelper.DataSourceIsEmpty(ds)) { BoardSubscriptionInfo bsi = new BoardSubscriptionInfo(); bsi.SubscriptionBoardID = BoardID; bsi.SubscriptionEmail = email; if ((MembershipContext.AuthenticatedUser != null) && !MembershipContext.AuthenticatedUser.IsPublic()) { bsi.SubscriptionUserID = MembershipContext.AuthenticatedUser.UserID; } BoardSubscriptionInfoProvider.Subscribe(bsi, DateTime.Now, true, true); // Clear form txtEmail.Text = ""; if (boardInfo == null) { boardInfo = BoardInfoProvider.GetBoardInfo(BoardID); } // If subscribed, log activity if (bsi.SubscriptionApproved) { ShowConfirmation(GetString("board.subscription.beensubscribed")); LogActivity(bsi, boardInfo); } else { string confirmation = GetString("general.subscribed.doubleoptin"); int optInInterval = BoardInfoProvider.DoubleOptInInterval(SiteContext.CurrentSiteName); if (optInInterval > 0) { confirmation += "<br />" + string.Format(GetString("general.subscription_timeintervalwarning"), optInInterval); } ShowConfirmation(confirmation); } } else { result = GetString("board.subscription.emailexists"); } } } if (result != String.Empty) { ShowError(result); } }
/// <summary> /// Log activity posting /// </summary> /// <param name="bmi">Board subscription info object</param> /// <param name="bi">Message board info</param> private void LogCommentActivity(BoardMessageInfo bmi, BoardInfo bi) { mMessageBoardActivityLogger.LogMessageBoardCommentActivity(bmi, bi, DocumentContext.CurrentDocument); }