public PostService(IPostRepository postRepository, ICommentService commentService, ILinkService linkService, ISmileyService smileyService, TextHelper textHelper) { Ensure.That(() => postRepository).IsNotNull(); Ensure.That(() => commentService).IsNotNull(); Ensure.That(() => linkService).IsNotNull(); Ensure.That(() => smileyService).IsNotNull(); Ensure.That(() => textHelper).IsNotNull(); this.postRepository = postRepository; this.commentService = commentService; this.linkService = linkService; this.smileyService = smileyService; this.textHelper = textHelper; }
/// <summary> /// This method returns the number of items imported /// </summary> /// <param name="text">The contents to be imported.</param> /// <param name="tableName">Only used in cases where more than one import takes place.</param> /// <param name="expectedCount">Number of expected columns in the csv file</param> /// <param name="callback">The method to call to update progress</param> /// <returns></returns> public static int ImportData(string text, string tableName, int expectedCount, ImportProgressCallback callback) { // initial value int savedCount = 0; // locals char[] delimiters = { ',' }; int count = 0; int totalCount = 0; int refreshRate = 5; List <Word> words = null; RawImport rawImport = null; // if the fileExists if (TextHelper.Exists(text)) { // Create a new instance of a 'Gateway' object. Gateway gateway = new Gateway(); // set the textLines List <TextLine> textLines = WordParser.GetTextLines(text.Trim()); // If the textLines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(textLines)) { // notify the callback to setup the Graph - table name is optional if you have more than one import callback(textLines.Count, "RawImport"); // change the RefreshRate if (textLines.Count > 1000) { // change this to whatever makes since for your app refreshRate = 25; } // set the totalCount totalCount = textLines.Count - 1; // Iterate the collection of TextLine objects foreach (TextLine textLine in textLines) { // Increment the value for count count++; // skip the first row if (count > 1) { // get the list of words words = WordParser.GetWords(textLine.Text, delimiters, true); // if the words collection has exactly the right amount if ((ListHelper.HasOneOrMoreItems(words)) && (words.Count == expectedCount)) { // Create a new instance of a 'RawImport' object. rawImport = new RawImport(); // Load the RawImport with the words SetRawImportProperties(ref rawImport, words); // save the rawImport object bool saved = gateway.SaveRawImport(ref rawImport); // if the value for saved is true if (saved) { // Increment the value for savedCount savedCount++; // refresh every x number of records if (savedCount % refreshRate == 0) { // update the graph (for a large project, you might want to update every 25, 50 or 100 records or so callback(savedCount, tableName); } } } } } } } // return value return(savedCount); }
/// <summary> /// This method returns the Connection String Line /// </summary> public TextLine GetConnectionStringLine() { // initial value TextLine connectionStringLine = null; // Set the ConnectionStringIndex ConnectionStringIndex = -1; // local int index = -1; // set the appConfig file location relative to bin\debug string appConfig = "../../App.config"; // if the file exists if (File.Exists(appConfig)) { // get the full path string fullPath = Path.GetFullPath(appConfig); // Set the AppConfigPath AppConfigPath = fullPath; // read the text of the AppConfig string appConfigText = File.ReadAllText(fullPath); // If the appConfigText string exists if (TextHelper.Exists(appConfigText)) { // get the textLines List <TextLine> textLines = WordParser.GetTextLines(appConfigText); // If the textLines collection exists and has one or more items if (ListHelper.HasOneOrMoreItems(textLines)) { // store the textLines so they can be updated in the next step AppConfigTextLines = textLines; // Iterate the collection of TextLine objects foreach (TextLine textLine in textLines) { // Increment the value for tempIndex index++; // if this is not a comment line if (!textLine.Text.Trim().StartsWith(HTMLCommentStart)) { // if this is the ConnectionStringLine if (textLine.Text.Trim().StartsWith(ConnectionStringStart)) { // get the textLine connectionStringLine = textLine; // Set the ConnectionStringIndex ConnectionStringIndex = index; // break out of this loop break; } else if (textLine.Text.Trim().StartsWith(SetupCompleteStart)) { // Set the SetupCompleteIndex SetupCompleteIndex = index; } } } } } } // return value return(connectionStringLine); }
private void FindFinished(FRResults results) { UserInterfaceManager.ProgressDialog.Show(); UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.UpdatingReferences")); MessageBar.Locked = true; var currentTarget = targets[currentTargetIndex]; string targetName = Path.GetFileNameWithoutExtension(currentTarget.OldFilePath); string oldType = (currentTarget.OldFileModel.Package + "." + targetName).Trim('.'); string newType = (currentTarget.NewPackage + "." + targetName).Trim('.'); foreach (KeyValuePair <string, List <SearchMatch> > entry in results) { List <SearchMatch> matches = entry.Value; if (matches.Count == 0 || entry.Key == currentTarget.OldFilePath || entry.Key == currentTarget.NewFilePath) { continue; } string file = entry.Key; UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.Updating") + " \"" + file + "\""); ScintillaControl sci; var actualMatches = new List <SearchMatch>(); foreach (SearchMatch match in entry.Value) { // we have to open/reopen the entry's file // there are issues with evaluating the declaration targets with non-open, non-current files // we have to do it each time as the process of checking the declaration source can change the currently open file! sci = AssociatedDocumentHelper.LoadDocument(file); // if the search result does point to the member source, store it if (RefactoringHelper.DoesMatchPointToTarget(sci, match, currentTargetResult, this.AssociatedDocumentHelper)) { actualMatches.Add(match); } } if (actualMatches.Count == 0) { continue; } int currLine = -1; sci = AssociatedDocumentHelper.LoadDocument(file); for (int i = actualMatches.Count - 1; i >= 0; i--) { var sm = actualMatches[i]; if (sm.LineText.Contains(oldType)) { sm.Index -= sci.MBSafeTextLength(oldType) - sci.MBSafeTextLength(targetName); sm.Value = oldType; RefactoringHelper.SelectMatch(sci, sm); sm.Column = sm.Index - sm.LineStart; sci.ReplaceSel(newType); sm.LineEnd = sci.SelectionEnd; sm.LineText = sci.GetLine(sm.Line - 1); sm.Value = newType; } else { if (currLine == -1) { currLine = sm.Line - 1; } actualMatches.RemoveAt(i); } } string directory = Path.GetDirectoryName(file); // Let's check if we need to add the import. Check the considerations at the start of the file // directory != currentTarget.OwnerPath -> renamed owner directory, so both files in the same place if (directory != Path.GetDirectoryName(currentTarget.NewFilePath) && directory != currentTarget.OwnerPath && ASContext.Context.CurrentModel.Imports.Search(targetName, FlagType.Class & FlagType.Function & FlagType.Namespace, 0) == null) { sci.GotoLine(currLine); ASGenerator.InsertImport(new MemberModel(targetName, newType, FlagType.Import, 0), false); int newLine = sci.LineFromPosition(sci.Text.IndexOf(newType)); var sm = new SearchMatch(); sm.Line = newLine + 1; sm.LineText = sci.GetLine(newLine); sm.Column = 0; sm.Length = sci.MBSafeTextLength(sm.LineText); sm.Value = sm.LineText; actualMatches.Insert(0, sm); } if (actualMatches.Count == 0) { continue; } if (!Results.ContainsKey(file)) { Results[file] = new List <SearchMatch>(); } Results[file].AddRange(actualMatches); //Do we want to open modified files? //if (sci.IsModify) AssociatedDocumentHelper.MarkDocumentToKeep(file); PluginBase.MainForm.CurrentDocument.Save(); } currentTargetIndex++; UserInterfaceManager.ProgressDialog.Hide(); MessageBar.Locked = false; UpdateReferencesNextTarget(); }
/// <summary> /// Processes the content. /// </summary> /// <param name="sb">StringBuilder to write</param> /// <param name="source">Source object</param> /// <param name="column">Column</param> /// <param name="content">Content</param> protected void ProcessContent(StringBuilder sb, object source, string column, ref string content) { bool standard = true; switch (column.ToLowerCSafe()) { // Document content case "documentcontent": EditableItems items = new EditableItems(); items.LoadContentXml(content); // Add regions foreach (DictionaryEntry region in items.EditableRegions) { sb.Append("<span class=\"VersionEditableRegionTitle\">" + (string)region.Key + "</span>"); string regionContent = HTMLHelper.ResolveUrls((string)region.Value, SystemContext.ApplicationPath); sb.Append("<span class=\"VersionEditableRegionText\">" + regionContent + "</span>"); } // Add web parts foreach (DictionaryEntry part in items.EditableWebParts) { sb.Append("<span class=\"VersionEditableWebPartTitle\">" + (string)part.Key + "</span>"); string regionContent = HTMLHelper.ResolveUrls((string)part.Value, SystemContext.ApplicationPath); sb.Append("<span class=\"VersionEditableWebPartText\">" + regionContent + "</span>"); } standard = false; break; // XML columns case "pagetemplatewebparts": case "webpartproperties": case "reportparameters": case "classformdefinition": case "classxmlschema": case "classformlayout": case "userdialogsconfiguration": content = HTMLHelper.ReformatHTML(content); break; // File columns case "metafilename": { Guid metaFileGuid = ValidationHelper.GetGuid(GetValueFromSource(source, "MetaFileGuid"), Guid.Empty); if (metaFileGuid != Guid.Empty) { string metaFileName = ValidationHelper.GetString(GetValueFromSource(source, "MetaFileName"), ""); content = "<a href=\"" + ResolveUrl(MetaFileInfoProvider.GetMetaFileUrl(metaFileGuid, metaFileName)) + "\" target=\"_blank\" >" + HTMLHelper.HTMLEncode(metaFileName) + "</a>"; sb.Append(content); standard = false; } } break; } // Standard rendering if (standard) { if (content.Length > 500) { content = TextHelper.EnsureMaximumLineLength(content, 50, "​", true); } else { content = HTMLHelper.HTMLEncode(content); } content = HTMLHelper.EnsureHtmlLineEndings(content); content = content.Replace("\t", " "); sb.Append("<div style=\"max-height: 300px; overflow: auto;\">" + content + "</div>"); } }
/// <summary> /// Gets a label as plain text by removing the accelerator key /// </summary> public static String GetLabelAsPlainText(String name, Boolean hasBOM) { String label = TextHelper.GetString(name).Replace("&", ""); return(hasBOM ? label + " (BOM)" : label); }
public bool FDBuild(Project project, bool runOutput, bool releaseMode, InstalledSDK sdk) { string directory = Environment.CurrentDirectory; Environment.CurrentDirectory = project.Directory; string fdBuildDir = Path.Combine(PathHelper.ToolDir, "fdbuild"); string fdBuildPath = Path.Combine(fdBuildDir, "fdbuild.exe"); string arguments = " -ipc " + ipcName; if (sdk != null) { if (!string.IsNullOrEmpty(sdk.Version)) { arguments += " -version \"" + sdk.Version.Replace(',', ';') + "\""; } if (!string.IsNullOrEmpty(project.CurrentSDK)) { arguments += " -compiler \"" + project.CurrentSDK + "\""; } } if (releaseMode) { arguments += " -notrace"; } arguments += " -library \"" + PathHelper.LibraryDir + "\""; foreach (string cp in PluginMain.Settings.GlobalClasspaths) { arguments += " -cp \"" + Environment.ExpandEnvironmentVariables(cp) + "\""; } if (project.TargetBuild != null) { arguments += " -target \"" + project.TargetBuild + "\""; } arguments = arguments.Replace("\\\"", "\""); // c# console args[] bugfix SetStatusBar(TextHelper.GetString("Info.BuildStarted")); pluginMain.UpdateUIStatus(ProjectManagerUIStatus.Building); // Apache Flex compat if (project.Language == "as3") { string playerglobalHome = Environment.ExpandEnvironmentVariables("%PLAYERGLOBAL_HOME%"); if (playerglobalHome.StartsWith("%")) { setPlayerglobalHomeEnv = true; } if (setPlayerglobalHomeEnv) { Environment.SetEnvironmentVariable("PLAYERGLOBAL_HOME", Path.Combine(project.CurrentSDK, "frameworks/libs/player")); } } // Lets expose current sdk Environment.SetEnvironmentVariable("FD_CUR_SDK", project.CurrentSDK ?? ""); // run FDBuild fdProcess.StartProcess(fdBuildPath, "\"" + project.ProjectPath + "\"" + arguments, project.Directory, delegate(bool success) { pluginMain.UpdateUIStatus(ProjectManagerUIStatus.NotBuilding); if (success) { SetStatusBar(TextHelper.GetString("Info.BuildSucceeded")); AddTrustFile(project); OnBuildComplete(project, runOutput); } else { SetStatusBar(TextHelper.GetString("Info.BuildFailed")); OnBuildFailed(project, runOutput); } Environment.CurrentDirectory = directory; }); return(true); }
public async Task DeleteForm(string ids) { long[] idArr = TextHelper.SplitToArray <long>(ids, ','); await this.BaseRepository().Delete <LogApiEntity>(idArr); }
public void ShowNextText(string name, string content, float speed) { viewController.UpdateNameText(name); textHelper.SetNextLine(TextHelper.ReplaceTextTags(content), speed); }
/// <summary> /// Creates group forum. /// </summary> /// <param name="group">Particular group info object</param> private void CreateGroupForum(GroupInfo group) { #region "Create forum group" // Get forum group code name string forumGroupCodeName = "Forums_group_" + group.GroupGUID; // Check if forum group with given name already exists if (ForumGroupInfoProvider.GetForumGroupInfo(forumGroupCodeName, CMSContext.CurrentSiteID) != null) { return; } // Create forum base URL string baseUrl = null; TreeNode groupDocument = TreeProvider.SelectSingleNode(group.GroupNodeGUID, CMSContext.CurrentDocumentCulture.CultureCode, CMSContext.CurrentSiteName); if (groupDocument != null) { baseUrl = CMSContext.GetUrl(groupDocument.NodeAliasPath + "/" + FORUM_DOCUMENT_ALIAS); } ForumGroupInfo forumGroupObj = new ForumGroupInfo(); string suffix = " forums"; forumGroupObj.GroupDisplayName = TextHelper.LimitLength(group.GroupDisplayName, 200 - suffix.Length, "") + suffix; forumGroupObj.GroupName = forumGroupCodeName; forumGroupObj.GroupOrder = 0; forumGroupObj.GroupEnableQuote = true; forumGroupObj.GroupGroupID = group.GroupID; forumGroupObj.GroupSiteID = CMSContext.CurrentSiteID; forumGroupObj.GroupBaseUrl = baseUrl; // Additional settings forumGroupObj.GroupEnableCodeSnippet = true; forumGroupObj.GroupEnableFontBold = true; forumGroupObj.GroupEnableFontColor = true; forumGroupObj.GroupEnableFontItalics = true; forumGroupObj.GroupEnableFontStrike = true; forumGroupObj.GroupEnableFontUnderline = true; forumGroupObj.GroupEnableQuote = true; forumGroupObj.GroupEnableURL = true; forumGroupObj.GroupEnableImage = true; // Set forum group info ForumGroupInfoProvider.SetForumGroupInfo(forumGroupObj); #endregion #region "Create forum" string codeName = "General_discussion_group_" + group.GroupGUID; // Check if forum with given name already exists if (ForumInfoProvider.GetForumInfo(codeName, CMSContext.CurrentSiteID, group.GroupID) != null) { return; } // Create new forum object ForumInfo forumObj = new ForumInfo(); forumObj.ForumSiteID = CMSContext.CurrentSiteID; forumObj.ForumIsLocked = false; forumObj.ForumOpen = true; forumObj.ForumDisplayEmails = false; forumObj.ForumRequireEmail = false; forumObj.ForumDisplayName = "General discussion"; forumObj.ForumName = codeName; forumObj.ForumGroupID = forumGroupObj.GroupID; forumObj.ForumModerated = false; forumObj.ForumAccess = 40000; forumObj.ForumPosts = 0; forumObj.ForumThreads = 0; forumObj.ForumPostsAbsolute = 0; forumObj.ForumThreadsAbsolute = 0; forumObj.ForumOrder = 0; forumObj.ForumUseCAPTCHA = false; forumObj.SetValue("ForumHTMLEditor", null); // Set security forumObj.AllowAccess = SecurityAccessEnum.GroupMembers; forumObj.AllowAttachFiles = SecurityAccessEnum.GroupMembers; forumObj.AllowMarkAsAnswer = SecurityAccessEnum.GroupMembers; forumObj.AllowPost = SecurityAccessEnum.GroupMembers; forumObj.AllowReply = SecurityAccessEnum.GroupMembers; forumObj.AllowSubscribe = SecurityAccessEnum.GroupMembers; if (ForumInfoProvider.LicenseVersionCheck(URLHelper.GetCurrentDomain(), FeatureEnum.Forums, VersionActionEnum.Insert)) { ForumInfoProvider.SetForumInfo(forumObj); } #endregion }
public ProjectMenu() { AllItems = new List <ToolStripItem>(); NewProject = new ToolStripMenuItem(TextHelper.GetString("Label.NewProject")); NewProject.Image = Icons.NewProject.Img; PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.NewProject", NewProject); //AllItems.Add(NewProject); OpenProject = new ToolStripMenuItem(TextHelper.GetString("Label.OpenProject")); PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.OpenProject", OpenProject); //AllItems.Add(OpenProject); ImportProject = new ToolStripMenuItem(TextHelper.GetString("Label.ImportProject")); PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.ImportProject", ImportProject); //AllItems.Add(ImportProject); CloseProject = new ToolStripMenuItem(TextHelper.GetString("Label.CloseProject")); PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.CloseProject", CloseProject); AllItems.Add(CloseProject); OpenResource = new ToolStripMenuItem(TextHelper.GetString("Label.OpenResource")); OpenResource.Image = PluginBase.MainForm.FindImage("209"); OpenResource.ShortcutKeys = Keys.Control | Keys.R; PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.OpenResource", OpenResource); AllItems.Add(OpenResource); TestMovie = new ToolStripMenuItem(TextHelper.GetString("Label.TestMovie")); TestMovie.Image = Icons.GreenCheck.Img; TestMovie.ShortcutKeys = Keys.F5; PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.TestMovie", TestMovie); AllItems.Add(TestMovie); RunProject = new ToolStripMenuItem(TextHelper.GetString("Label.RunProject")); PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.RunProject", RunProject); AllItems.Add(RunProject); BuildProject = new ToolStripMenuItem(TextHelper.GetString("Label.BuildProject")); BuildProject.Image = Icons.Gear.Img; BuildProject.ShortcutKeys = Keys.F8; PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.BuildProject", BuildProject); AllItems.Add(BuildProject); CleanProject = new ToolStripMenuItem(TextHelper.GetString("Label.CleanProject")); CleanProject.ShortcutKeys = Keys.Shift | Keys.F8; PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.CleanProject", CleanProject); AllItems.Add(CleanProject); Properties = new ToolStripMenuItem(TextHelper.GetString("Label.Properties")); Properties.Image = Icons.Options.Img; PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.Properties", Properties); AllItems.Add(Properties); base.Text = TextHelper.GetString("Label.Project"); base.DropDownItems.Add(NewProject); base.DropDownItems.Add(OpenProject); base.DropDownItems.Add(ImportProject); base.DropDownItems.Add(CloseProject); base.DropDownItems.Add(new ToolStripSeparator()); base.DropDownItems.Add(OpenResource); base.DropDownItems.Add(new ToolStripSeparator()); base.DropDownItems.Add(TestMovie); base.DropDownItems.Add(RunProject); base.DropDownItems.Add(BuildProject); base.DropDownItems.Add(CleanProject); base.DropDownItems.Add(new ToolStripSeparator()); base.DropDownItems.Add(Properties); }
public FDMenus(IMainForm mainForm) { // modify the file menu ToolStripMenuItem fileMenu = (ToolStripMenuItem)mainForm.FindMenuItem("FileMenu"); RecentProjects = new RecentProjectsMenu(); fileMenu.DropDownItems.Insert(5, RecentProjects); // modify the view menu ToolStripMenuItem viewMenu = (ToolStripMenuItem)mainForm.FindMenuItem("ViewMenu"); View = new ToolStripMenuItem(TextHelper.GetString("Label.MainMenuItem")); View.Image = Icons.Project.Img; viewMenu.DropDownItems.Add(View); PluginBase.MainForm.RegisterShortcutItem("ViewMenu.ShowProject", View); // modify the tools menu - add a nice GUI classpath editor ToolStripMenuItem toolsMenu = (ToolStripMenuItem)mainForm.FindMenuItem("ToolsMenu"); GlobalClasspaths = new ToolStripMenuItem(TextHelper.GetString("Label.GlobalClasspaths")); GlobalClasspaths.ShortcutKeys = Keys.F9 | Keys.Control; GlobalClasspaths.Image = Icons.Classpath.Img; toolsMenu.DropDownItems.Insert(toolsMenu.DropDownItems.Count - 4, GlobalClasspaths); PluginBase.MainForm.RegisterShortcutItem("ToolsMenu.GlobalClasspaths", GlobalClasspaths); ProjectMenu = new ProjectMenu(); MenuStrip mainMenu = mainForm.MenuStrip; mainMenu.Items.Insert(5, ProjectMenu); ToolStrip toolBar = mainForm.ToolStrip; toolBar.Items.Add(new ToolStripSeparator()); toolBar.Items.Add(RecentProjects.ToolbarSelector); BuildProject = new ToolStripButton(Icons.Gear.Img); BuildProject.Name = "BuildProject"; BuildProject.ToolTipText = TextHelper.GetStringWithoutMnemonics("Label.BuildProject"); PluginBase.MainForm.RegisterSecondaryItem("ProjectMenu.BuildProject", BuildProject); toolBar.Items.Add(BuildProject); TestMovie = new ToolStripButton(Icons.GreenCheck.Img); TestMovie.Name = "TestMovie"; TestMovie.ToolTipText = TextHelper.GetStringWithoutMnemonics("Label.TestMovie"); PluginBase.MainForm.RegisterSecondaryItem("ProjectMenu.TestMovie", TestMovie); toolBar.Items.Add(TestMovie); ConfigurationSelector = new ToolStripComboBoxEx(); ConfigurationSelector.Name = "ConfigurationSelector"; ConfigurationSelector.ToolTipText = TextHelper.GetString("ToolTip.SelectConfiguration"); ConfigurationSelector.Items.AddRange(new string[] { TextHelper.GetString("Info.Debug"), TextHelper.GetString("Info.Release") }); ConfigurationSelector.DropDownStyle = ComboBoxStyle.DropDownList; ConfigurationSelector.AutoSize = false; ConfigurationSelector.Enabled = false; ConfigurationSelector.Width = ScaleHelper.Scale(GetThemeWidth("ProjectManager.TargetBuildSelectorWidth", 85)); ConfigurationSelector.Margin = new Padding(1, 0, 0, 0); ConfigurationSelector.FlatStyle = PluginBase.MainForm.Settings.ComboBoxFlatStyle; ConfigurationSelector.Font = PluginBase.Settings.DefaultFont; toolBar.Items.Add(ConfigurationSelector); PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.ConfigurationSelectorToggle", Keys.Control | Keys.F5); PluginBase.MainForm.RegisterSecondaryItem("ProjectMenu.ConfigurationSelectorToggle", ConfigurationSelector); TargetBuildSelector = new ToolStripComboBoxEx(); TargetBuildSelector.Name = "TargetBuildSelector"; TargetBuildSelector.ToolTipText = TextHelper.GetString("ToolTip.TargetBuild"); TargetBuildSelector.AutoSize = false; TargetBuildSelector.Width = ScaleHelper.Scale(GetThemeWidth("ProjectManager.ConfigurationSelectorWidth", 120)); TargetBuildSelector.Margin = new Padding(1, 0, 0, 0); TargetBuildSelector.FlatStyle = PluginBase.MainForm.Settings.ComboBoxFlatStyle; TargetBuildSelector.Font = PluginBase.Settings.DefaultFont; toolBar.Items.Add(TargetBuildSelector); PluginBase.MainForm.RegisterShortcutItem("ProjectMenu.TargetBuildSelector", Keys.Control | Keys.F7); PluginBase.MainForm.RegisterSecondaryItem("ProjectMenu.TargetBuildSelector", TargetBuildSelector); EnableTargetBuildSelector(false); }
/// <summary> /// Renames the given the set of matched references /// </summary> private void OnFindAllReferencesCompleted(object sender, RefactorCompleteEventArgs <IDictionary <string, List <SearchMatch> > > eventArgs) { UserInterfaceManager.ProgressDialog.Show(); UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.UpdatingReferences")); MessageBar.Locked = true; var isParameterVar = (Target.Member?.Flags & FlagType.ParameterVar) > 0; foreach (var entry in eventArgs.Results) { UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.Updating") + " \"" + entry.Key + "\""); // re-open the document and replace all the text var doc = AssociatedDocumentHelper.LoadDocument(entry.Key); var sci = doc.SciControl; var targetMatches = entry.Value; if (isParameterVar) { var lineFrom = Target.Context.ContextFunction.LineFrom; var lineTo = Target.Context.ContextFunction.LineTo; var search = new FRSearch(NewName) { WholeWord = true, NoCase = false, SingleLine = true }; var matches = search.Matches(sci.Text, sci.PositionFromLine(lineFrom), lineFrom); matches.RemoveAll(it => it.Line <lineFrom || it.Line> lineTo); if (matches.Count != 0) { sci.BeginUndoAction(); try { for (var i = 0; i < matches.Count; i++) { var match = matches[i]; var expr = ASComplete.GetExpressionType(sci, sci.MBSafePosition(match.Index) + sci.MBSafeTextLength(match.Value)); if (expr.IsNull()) { continue; } var replacement = string.Empty; var flags = expr.Member.Flags; if ((flags & FlagType.Static) > 0) { var classNameWithDot = ASContext.Context.CurrentClass.Name + "."; if (!expr.Context.Value.StartsWith(classNameWithDot)) { replacement = classNameWithDot + NewName; } } else if ((flags & FlagType.LocalVar) == 0) { var decl = expr.Context.Value; if (!decl.StartsWith("this.") && !decl.StartsWith("super.")) { replacement = "this." + NewName; } } if (string.IsNullOrEmpty(replacement)) { continue; } RefactoringHelper.SelectMatch(sci, match); sci.EnsureVisible(sci.LineFromPosition(sci.MBSafePosition(match.Index))); sci.ReplaceSel(replacement); for (var j = 0; j < targetMatches.Count; j++) { var targetMatch = targetMatches[j]; if (targetMatch.Line <= match.Line) { continue; } FRSearch.PadIndexes(targetMatches, j, match.Value, replacement); if (targetMatch.Line == match.Line + 1) { targetMatch.LineText = sci.GetLine(match.Line); targetMatch.Column += replacement.Length - match.Value.Length; } break; } FRSearch.PadIndexes(matches, i + 1, match.Value, replacement); } } finally { sci.EndUndoAction(); } } } // replace matches in the current file with the new name RefactoringHelper.ReplaceMatches(targetMatches, sci, NewName); //Uncomment if we want to keep modified files //if (sci.IsModify) AssociatedDocumentHelper.MarkDocumentToKeep(entry.Key); doc.Save(); } if (newFileName != null) { RenameFile(eventArgs.Results); } Results = eventArgs.Results; AssociatedDocumentHelper.CloseTemporarilyOpenedDocuments(); if (OutputResults) { ReportResults(); } UserInterfaceManager.ProgressDialog.Hide(); MessageBar.Locked = false; FireOnRefactorComplete(); }
#pragma warning restore 0649 public void setControlScheme(MicrogameTraits.ControlScheme controlScheme) { //TODO re-enable command warnings? controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme); controlText.text = TextHelper.getLocalizedTextNoWarnings("control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme)); }
private void autoButton_Click(object sender, EventArgs e) { autoStart = !autoStart; autoButton.Image = PluginBase.MainForm.FindImage(autoStart ? "510" : "514"); autoButton.Text = TextHelper.GetString(autoStart ? "Label.AutoStartProfilerON" : "Label.AutoStartProfilerOFF"); }
/// <summary> /// Overrides OnPreRender method. /// </summary> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); // Apply filter if (!DataHelper.DataSourceIsEmpty(mGeneratedVariants)) { string query = string.Empty; foreach (int categoryId in VariantFilter.SelectedOptionIDs.Keys.ToList()) { // Build query from selected options Ids if (mGeneratedVariants.Tables[0].Columns[categoryId.ToString()] != null) { // Build query where column named categoryId satisfies conditions query = SqlHelper.AddWhereCondition(query, ("[" + categoryId + "] IN (" + TextHelper.Join(",", VariantFilter.SelectedOptionIDs[categoryId]) + ")")); query = SqlHelper.AddWhereCondition(query, ("[" + categoryId + "] IS NULL"), "OR"); } } if (query != string.Empty) { // Apply query, save result, clear dataTable and put result to daTable DataTable dataTable = mGeneratedVariants.Tables[0].Clone(); mGeneratedVariants.Tables[0].Select(query, "RowNumber").CopyToDataTable(dataTable, LoadOption.OverwriteChanges); mGeneratedVariants.Tables.Remove("VariantsDT"); mGeneratedVariants.Tables.Add(dataTable); } else { // No ids selected, clear grid mGeneratedVariants.Tables.Remove("VariantsDT"); } SetupVariants(false); } ManipulateFilter(); VariantGrid.Visible = (VariantGrid.RowsCount <= 500); lblSpecify.Visible = !VariantGrid.Visible; }
/// <summary> /// Prepares the layout of the web part. /// </summary> protected override void PrepareLayout() { StartLayout(); Append("<div"); // Width string width = Width; if (!string.IsNullOrEmpty(width)) { Append(" style=\"width: ", width, "\""); } if (IsDesign) { Append(" id=\"", ShortClientID, "_env\">"); Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">"); if (ViewModeIsDesign()) { Append("<tr><td class=\"LayoutHeader\" colspan=\"2\">"); // Add header container AddHeaderContainer(); Append("</td></tr>"); } Append("<tr><td id=\"", ShortClientID, "_info\" style=\"width: 100%;\">"); } else { Append(">"); } // Add the tabs var acc = new CMSAccordion(); acc.ID = "acc"; AddControl(acc); if (IsDesign) { Append("</td>"); if (AllowDesignMode) { // Width resizer Append("<td class=\"HorizontalResizer\" onmousedown=\"" + GetHorizontalResizerScript("env", "Width", false, "info") + " return false;\"> </td>"); } Append("</tr>"); } // Pane headers string[] headers = TextHelper.EnsureLineEndings(PaneHeaders, "\n").Split('\n'); for (int i = 1; i <= Panes; i++) { // Create new pane var pane = new CMSAccordionPane(); pane.ID = "pane" + i; // Prepare the header string header = null; if (headers.Length >= i) { header = ResHelper.LocalizeString(headers[i - 1]); header = HTMLHelper.HTMLEncode(header); } if (String.IsNullOrEmpty(header)) { header = "Pane " + i; } pane.Header = new TextTransformationTemplate(header); acc.Panes.Add(pane); pane.WebPartZone = AddZone(ID + "_" + i, header, pane.ContentContainer); } // Setup the accordion if ((ActivePaneIndex >= 1) && (ActivePaneIndex <= acc.Panes.Count)) { acc.SelectedIndex = ActivePaneIndex - 1; } acc.ContentCssClass = ContentCSSClass; acc.HeaderCssClass = HeaderCSSClass; acc.HeaderSelectedCssClass = SelectedHeaderCSSClass; acc.FadeTransitions = FadeTransitions; acc.TransitionDuration = TransitionDuration; acc.RequireOpenedPane = RequireOpenedPane; // If no active pane is selected and doesn't require opened one, do not preselect any if (!acc.RequireOpenedPane && (ActivePaneIndex < 0)) { acc.SelectedIndex = -1; } if (IsDesign) { if (AllowDesignMode) { Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">"); // Pane actions Append("<div class=\"LayoutLeftActions\">"); AppendAddAction(ResHelper.GetString("Layout.AddPane"), "Panes"); if (Panes > 1) { AppendRemoveAction(ResHelper.GetString("Layout.RemoveLastPane"), "Panes"); } Append("</div></div></td></tr>"); } Append("</table>"); } Append("</div>"); FinishLayout(); }
/// <summary> /// Markdown blocks processing /// </summary> /// <param name="b"></param> /// <param name="recursionLevel"></param> protected List <string> BlockProcessing(MarkdownBlock b, int recursionLevel) { string forecolor = string.Empty; string backcolor = string.Empty; string underline = string.Empty; int maxWidth = client.screenWidth - recursionLevel * 2; List <string> Text = new List <string>(); switch (b.Type) { case MarkdownBlockType.Root: break; case MarkdownBlockType.Paragraph: string para = ""; foreach (var i in ((ParagraphBlock)b).Inlines) { para += ProcessInline(i); } Text.AddRange(TextHelper.WordWrap(para, maxWidth)); Text.Add(string.Empty); break; case MarkdownBlockType.Quote: break; case MarkdownBlockType.Code: forecolor = ANSI.GetStyleForeColor("Code_Color", mdStyles); backcolor = ANSI.GetStyleBackColor("Code_Back", mdStyles); List <string> rows = TextHelper.SplitString(((CodeBlock)b).Text); foreach (string s in rows) { Text.Add(backcolor + forecolor + ANSI.ClearCurrentLine + s + ANSI.WriteMode()); } Text.Add(ANSI.WriteMode()); break; case MarkdownBlockType.Header: HeaderBlock hb = (HeaderBlock)b; Text.AddRange(ANSI.Header(hb.ToString(), hb.HeaderLevel, maxWidth)); break; case MarkdownBlockType.List: ListBlock lb = (ListBlock)b; string indent = new string(' ', recursionLevel * 2); foreach (var li in lb.Items) { List <string> lir = new List <string>(); bool isFirst = true; foreach (var lib in li.Blocks) { lir.AddRange(BlockProcessing(lib, recursionLevel + 1)); } foreach (string s in lir) { Text.Add((isFirst ? "- " : " ") + s); isFirst = false; } } break; case MarkdownBlockType.ListItemBuilder: break; case MarkdownBlockType.HorizontalRule: Text.Add(TextHelper.HR('-', maxWidth)); break; case MarkdownBlockType.Table: TableBlock tb = (TableBlock)b; int colWidth = maxWidth / tb.ColumnDefinitions.Count; foreach (var tr in tb.Rows) { string trs = string.Empty; foreach (var tc in tr.Cells) { string tcs = string.Empty; foreach (var i in tc.Inlines) { tcs += ProcessInline(i); } trs += TextHelper.Truncate(tcs, colWidth - 1).PadRight(colWidth); } Text.Add(trs); } break; case MarkdownBlockType.LinkReference: break; case MarkdownBlockType.YamlHeader: break; default: break; } return(Text); }
/// <summary> /// Page_load event. /// </summary> protected void Page_Load(object sender, EventArgs e) { // Check permissions and UI elements var user = MembershipContext.AuthenticatedUser; if (user != null) { if (!user.IsAuthorizedPerUIElement("CMS.Users", "CmsDesk.Roles")) { RedirectToUIElementAccessDenied("CMS.Users", "CmsDesk.Roles"); } if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Roles", "Read")) { RedirectToAccessDenied("CMS.Roles", "Read"); } } ScriptHelper.RegisterJQuery(Page); // Get user id and site Id from query mUserId = QueryHelper.GetInteger("userid", 0); // Show content placeholder where site selector can be shown CurrentMaster.DisplaySiteSelectorPanel = true; if ((SiteID > 0) && !MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin)) { plcSites.Visible = false; CurrentMaster.DisplaySiteSelectorPanel = false; } if (mUserId > 0) { // Check that only global administrator can edit global administrator's accounts mUserInfo = UserInfo.Provider.Get(mUserId); CheckUserAvaibleOnSite(mUserInfo); EditedObject = mUserInfo; if (!CheckGlobalAdminEdit(mUserInfo)) { plcTable.Visible = false; ShowError(GetString("Administration-User_List.ErrorGlobalAdmin")); return; } // Set site selector siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.AllowEmpty = false; // Global roles only for global admin if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { siteSelector.AllowGlobal = true; } // Only sites assigned to user siteSelector.UserId = mUserId; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged; if (!RequestHelper.IsPostBack()) { mSiteId = SiteContext.CurrentSiteID; // If user is member of current site if (UserSiteInfo.Provider.Get(mUserId, mSiteId) != null) { // Force uniselector to preselect current site siteSelector.Value = mSiteId; } // Force to load data siteSelector.Reload(true); } // Get truly selected item mSiteId = ValidationHelper.GetInteger(siteSelector.Value, 0); } usRoles.OnSelectionChanged += usRoles_OnSelectionChanged; string siteIDWhere = (mSiteId <= 0) ? " SiteID IS NULL " : " SiteID =" + mSiteId; usRoles.WhereCondition = siteIDWhere; usRoles.SelectItemPageUrl = "~/CMSModules/Membership/Pages/Users/User_Edit_Add_Item_Dialog.aspx"; usRoles.ListingWhereCondition = siteIDWhere + " AND UserID=" + mUserId; usRoles.ReturnColumnName = "RoleID"; usRoles.DynamicColumnName = false; usRoles.GridName = "User_Role_List.xml"; usRoles.AdditionalColumns = "ValidTo"; usRoles.OnAdditionalDataBound += usMemberships_OnAdditionalDataBound; usRoles.DialogWindowHeight = 760; // Exclude generic roles string genericWhere = String.Empty; ArrayList genericRoles = RoleInfoProvider.GetGenericRoles(); if (genericRoles.Count != 0) { foreach (string role in genericRoles) { genericWhere += "'" + SqlHelper.EscapeQuotes(role) + "',"; } genericWhere = genericWhere.TrimEnd(','); usRoles.WhereCondition += " AND ( RoleName NOT IN (" + genericWhere + ") )"; } // Get the active roles for this site var roleIds = new IDQuery <RoleInfo>().Where(siteIDWhere).Column("RoleID"); var data = UserRoleInfo.Provider.Get().WhereEquals("UserID", mUserId).And().WhereIn("RoleID", roleIds).Columns("RoleID").TypedResult; if (data.Any()) { mCurrentValues = TextHelper.Join(";", data.Select(i => i.RoleID)); } // If not postback or site selection changed if (!RequestHelper.IsPostBack() || (mSiteId != Convert.ToInt32(ViewState["rolesOldSiteId"]))) { // Set values usRoles.Value = mCurrentValues; } // Store selected site id ViewState["rolesOldSiteId"] = mSiteId; string script = "function setNewDateTime(date) {$cmsj('#" + hdnDate.ClientID + "').val(date);}"; ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "key", ScriptHelper.GetScript(script)); string eventTarget = Request[postEventSourceID]; string eventArgument = Request[postEventArgumentID]; if (eventTarget == ucCalendar.DateTimeTextBox.UniqueID) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Users", "ManageUserRoles")) { RedirectToAccessDenied("CMS.Users", "Manage user roles"); } int id = ValidationHelper.GetInteger(hdnDate.Value, 0); if (id != 0) { DateTime dt = ValidationHelper.GetDateTime(eventArgument, DateTimeHelper.ZERO_TIME); UserRoleInfo uri = UserRoleInfo.Provider.Get(mUserId, id); if (uri != null) { uri.ValidTo = dt; UserRoleInfo.Provider.Set(uri); // Invalidate user UserInfoProvider.InvalidateUser(mUserId); ShowChangesSaved(); } } } }
public bool Build(Project project, bool runOutput, bool releaseMode) { // save modified files mainForm.CallCommand("SaveAllModified", null); string compiler = null; InstalledSDK sdk = null; if (project.IsCompilable) { sdk = GetProjectSDK(project); compiler = GetCompilerPath(project, sdk); } project.TraceEnabled = !releaseMode; if (project.OutputType == OutputType.OtherIDE) { // compile using associated IDE string error; string command = project.GetOtherIDE(runOutput, releaseMode, out error); if (error != null) { ErrorManager.ShowInfo(TextHelper.GetString(error)); } else { if (command == "FlashIDE") { RunFlashIDE(project, runOutput, releaseMode); } else { Hashtable data = new Hashtable(); data["command"] = command; data["project"] = project; data["runOutput"] = runOutput; data["releaseMode"] = releaseMode; DataEvent de = new DataEvent(EventType.Command, "ProjectManager.RunWithAssociatedIDE", data); EventManager.DispatchEvent(project, de); if (de.Handled) { return(true); } } } return(false); } else if (project.OutputType == OutputType.CustomBuild) { // validate commands not empty if (project.PreBuildEvent.Trim().Length == 0 && project.PostBuildEvent.Trim().Length == 0) { String info = TextHelper.GetString("Info.NoOutputAndNoBuild"); TraceManager.Add(info); } } else if (project.IsCompilable) { // ask the project to validate itself string error; project.ValidateBuild(out error); if (error != null) { ErrorManager.ShowInfo(TextHelper.GetString(error)); return(false); } if (project.OutputPath.Length == 0) { String info = TextHelper.GetString("Info.SpecifyValidOutputSWF"); ErrorManager.ShowInfo(info); return(false); } if (compiler == null || (!Directory.Exists(compiler) && !File.Exists(compiler))) { string info = TextHelper.GetString("Info.CheckSDKSettings"); MessageBox.Show(info, TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OK); return(false); } } // close running AIR projector if (project.MovieOptions.Platform.StartsWith("AIR")) { foreach (Process proc in Process.GetProcessesByName("adl")) { try { proc.Kill(); proc.WaitForExit(10 * 1000); } catch { } } } return(FDBuild(project, runOutput, releaseMode, sdk)); }
// <Summary> // This method is used to export a StoredProcedure object to xml. // </Summary> public string ExportStoredProcedure(StoredProcedure storedProcedure, int indent = 0) { // initial value string storedProcedureXml = ""; // locals string indentString = TextHelper.Indent(indent); string indentString2 = TextHelper.Indent(indent + 2); // If the storedProcedure object exists if (NullHelper.Exists(storedProcedure)) { // Create a StringBuilder StringBuilder sb = new StringBuilder(); // Append the indentString sb.Append(indentString); // Write the open storedProcedure node sb.Append("<StoredProcedure>" + Environment.NewLine); // Write out each property // Write out the value for DoesNotHaveParameters sb.Append(indentString2); sb.Append("<DoesNotHaveParameters>" + storedProcedure.DoesNotHaveParameters + "</DoesNotHaveParameters>" + Environment.NewLine); // Write out the value for Parameters // Create the ParametersWriter ParametersWriter parametersWriter = new ParametersWriter(); // Export the Parameters collection to xml string storedProcedureParameterXml = parametersWriter.ExportList(storedProcedure.Parameters, indent + 2); sb.Append(storedProcedureParameterXml); sb.Append(Environment.NewLine); // Write out the value for ProcedureName sb.Append(indentString2); sb.Append("<ProcedureName>" + storedProcedure.ProcedureName + "</ProcedureName>" + Environment.NewLine); // Write out the value for ReturnSetSchema // Create the ReturnSetSchemaWriter ReturnSetSchemaWriter returnSetSchemaWriter = new ReturnSetSchemaWriter(); // Export the ReturnSetSchemas collection to xml string dataFieldXml = returnSetSchemaWriter.ExportList(storedProcedure.ReturnSetSchema, indent + 2); sb.Append(dataFieldXml); sb.Append(Environment.NewLine); // Write out the value for StoredProcedureType sb.Append(indentString2); sb.Append("<StoredProcedureType>" + storedProcedure.StoredProcedureType + "</StoredProcedureType>" + Environment.NewLine); // Write out the value for Text // I accidently overwrote this line making the video: // The xml has to be formatted if the procedure text contains any greater than or less than symbos or ampersands: string encodedText = XmlPatternHelper.Encode(storedProcedure.Text); sb.Append(indentString2); sb.Append("<Text>" + encodedText + "</Text>" + Environment.NewLine); // Append the indentString sb.Append(indentString); // Write out the close storedProcedure node sb.Append("</StoredProcedure>" + Environment.NewLine); // set the return value storedProcedureXml = sb.ToString(); } // return value return(storedProcedureXml); }
public override string Desc(Player player, string sett) { var names = SplitHelper.Separator(sett).Select(s => L.b.researches[s].Name()); return(S.T("reqResearch", TextHelper.CommaSep(names.ToArray()))); }
/// <summary> /// Prepares the layout of the web part. /// </summary> protected override void PrepareLayout() { StartLayout(); Append("<div"); // Width string width = Width; if (!string.IsNullOrEmpty(width)) { Append(" style=\"width: ", width, "\""); } if (IsDesign) { Append(" id=\"", ShortClientID, "_env\">"); Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">"); switch (ViewMode) { case ViewModeEnum.Design: case ViewModeEnum.DesignDisabled: { Append("<tr><td class=\"LayoutHeader\" colspan=\"2\">"); // Add header container AddHeaderContainer(); Append("</td></tr>"); } break; } Append("<tr><td style=\"width: 100%;\">"); } else { Append(">"); } // Add the tabs tabs = new TabContainer(); tabs.ID = "tabs"; AddControl(tabs); if (IsDesign) { Append("</td>"); // Resizers if (AllowDesignMode) { // Width resizer Append("<td class=\"HorizontalResizer\" onmousedown=\"", GetHorizontalResizerScript("env", "Width", false, "tabs_body"), " return false;\"> </td></tr>"); // Height resizer Append("<tr><td class=\"VerticalResizer\" onmousedown=\"", GetVerticalResizerScript("tabs_body", "Height"), " return false;\"> </td>"); Append("<td class=\"BothResizer\" onmousedown=\"", GetHorizontalResizerScript("env", "Width", false, "tabs_body"), " ", GetVerticalResizerScript("tabs_body", "Height"), " return false;\"> </td>"); } Append("</tr>"); } // Tab headers string[] headers = TextHelper.EnsureLineEndings(TabHeaders, "\n").Split('\n'); if ((ActiveTabIndex >= 1) && (ActiveTabIndex <= Tabs)) { tabs.ActiveTabIndex = ActiveTabIndex - 1; } bool hideEmpty = HideEmptyTabs; for (int i = 1; i <= Tabs; i++) { // Create new tab CMSTabPanel tab = new CMSTabPanel(); tab.ID = "tab" + i; // Prepare the header string header = null; if (headers.Length >= i) { header = ResHelper.LocalizeString(headers[i - 1]); header = HTMLHelper.HTMLEncode(header); } if (String.IsNullOrEmpty(header)) { header = "Tab " + i; } tab.HeaderText = header; tab.HideIfZoneEmpty = hideEmpty; tabs.Tabs.Add(tab); tab.WebPartZone = AddZone(ID + "_" + i, header, tab); } // Setup the tabs tabs.ScrollBars = ControlsHelper.GetScrollbarsEnum(Scrollbars); if (!String.IsNullOrEmpty(TabsCSSClass)) { tabs.CssClass = TabsCSSClass; } tabs.TabStripPlacement = GetTabStripPlacement(TabStripPlacement); if (!String.IsNullOrEmpty(Height)) { tabs.Height = new Unit(Height); } if (IsDesign) { // Footer if (AllowDesignMode) { Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">"); Append("<div class=\"LayoutLeftActions\">"); // Pane actions AppendAddAction(ResHelper.GetString("Layout.AddTab"), "Tabs"); if (Tabs > 1) { AppendRemoveAction(ResHelper.GetString("Layout.RemoveTab"), "Tabs"); } Append("</div></div></td></tr>"); } Append("</table>"); } Append("</div>"); FinishLayout(); }
private void UpdateReferencesNextTarget() { if (currentTargetIndex < targets.Count) { var currentTarget = targets[currentTargetIndex]; FileModel oldFileModel = currentTarget.OldFileModel; FRSearch search; string oldType; if (string.IsNullOrEmpty(oldFileModel.Package)) { search = new FRSearch("package"); search.WholeWord = true; oldType = Path.GetFileNameWithoutExtension(currentTarget.OldFilePath); } else { search = new FRSearch("package\\s+(" + oldFileModel.Package + ")"); oldType = oldFileModel.Package + "." + Path.GetFileNameWithoutExtension(currentTarget.OldFilePath); } search.IsRegex = true; search.Filter = SearchFilter.None; oldType = oldType.Trim('.'); MessageBar.Locked = true; string newFilePath = currentTarget.NewFilePath; ScintillaControl sci = AssociatedDocumentHelper.LoadDocument(currentTarget.TmpFilePath ?? newFilePath); List <SearchMatch> matches = search.Matches(sci.Text); string packageReplacement = "package"; if (currentTarget.NewPackage != "") { packageReplacement += " " + currentTarget.NewPackage; } RefactoringHelper.ReplaceMatches(matches, sci, packageReplacement); int offset = "package ".Length; foreach (SearchMatch match in matches) { match.Column += offset; match.LineText = sci.GetLine(match.Line - 1); match.Value = currentTarget.NewPackage; } if (matches.Count > 0) { if (!Results.ContainsKey(newFilePath)) { Results[newFilePath] = new List <SearchMatch>(); } Results[newFilePath].AddRange(matches); } //Do we want to open modified files? //if (sci.IsModify) AssociatedDocumentHelper.MarkDocumentToKeep(file); PluginBase.MainForm.CurrentDocument.Save(); MessageBar.Locked = false; UserInterfaceManager.ProgressDialog.Show(); UserInterfaceManager.ProgressDialog.SetTitle(TextHelper.GetString("Info.FindingReferences")); UserInterfaceManager.ProgressDialog.UpdateStatusMessage(TextHelper.GetString("Info.SearchingFiles")); currentTargetResult = RefactoringHelper.GetRefactorTargetFromFile(oldFileModel.FileName, AssociatedDocumentHelper); if (currentTargetResult != null) { RefactoringHelper.FindTargetInFiles(currentTargetResult, UserInterfaceManager.ProgressDialog.UpdateProgress, FindFinished, true, true); } else { currentTargetIndex++; UserInterfaceManager.ProgressDialog.Hide(); UpdateReferencesNextTarget(); } } else { MoveRefactoredFiles(); ReopenInitialFiles(); FireOnRefactorComplete(); } }
/// <summary> /// Prepares the layout of the web part. /// </summary> protected override void PrepareLayout() { StartLayout(true); // Pane headers string[] headers = TextHelper.EnsureLineEndings(PaneHeaders, "\n").Split('\n'); for (int i = 1; i <= Panes; i++) { // Create new pane AccordionPane pane = new AccordionPane(); pane.ID = "pane" + i; // Prepare the header string header = null; if (headers.Length >= i) { header = ResHelper.LocalizeString(headers[i - 1]); } if (String.IsNullOrEmpty(header)) { header = "Pane " + i; } string title = header; if (IsDesign) { header = EditableWebPartProperty.GetHTMLCode(null, this, "PaneHeaders", i, EditablePropertyTypeEnum.TextBox, header, null, null, null, true); } else { header = EditableWebPartProperty.ApplyReplacements(HttpUtility.HtmlEncode(header), false); } pane.Header = new TextTransformationTemplate(header); acc.Panes.Add(pane); var zone = AddZone(ID + "_" + i, title, pane.ContentContainer); zone.Wireframe = true; } // Setup the accordion if ((ActivePaneIndex >= 1) && (ActivePaneIndex <= acc.Panes.Count)) { acc.SelectedIndex = ActivePaneIndex - 1; } // If no active pane is selected and doesn't require opened one, do not preselect any if (!acc.RequireOpenedPane && (ActivePaneIndex < 0)) { acc.SelectedIndex = -1; } // Wireframe design acc.CssClass = "WireframeAccordion"; acc.ContentCssClass = "WireframeAccordionContent"; acc.HeaderCssClass = "WireframeAccordionHeader"; acc.HeaderSelectedCssClass = "WireframeAccordionSelectedHeader"; acc.RequireOpenedPane = RequireOpenedPane; acc.AutoSize = AutoSize.None; // Set width / height string width = Width; if (!String.IsNullOrEmpty(width)) { acc.Width = new Unit(width); } if (IsDesign && AllowDesignMode) { // Pane actions if (Panes > 1) { AppendRemoveAction(GetString("Layout.RemoveLastPane"), "Panes", "CMSModules/CMS_PortalEngine/Wireframes/Remove.png", null); Append(" "); } AppendAddAction(GetString("Layout.AddPane"), "Panes", "CMSModules/CMS_PortalEngine/Wireframes/Add.png", null); resElem.ResizedElementID = acc.ClientID; } // Render the actions string actions = FinishLayout(false); if (!String.IsNullOrEmpty(actions)) { pnlActions.Visible = true; ltlActions.Text = actions; } }
// <Summary> // This method is used to export a DataTable object to xml. // </Summary> public string ExportDataTable(DataTable dataTable, int indent = 0) { // initial value string dataTableXml = ""; // locals string indentString = TextHelper.Indent(indent); string indentString2 = TextHelper.Indent(indent + 2); // If the dataTable object exists if (NullHelper.Exists(dataTable)) { // Create a StringBuilder StringBuilder sb = new StringBuilder(); // Append the indentString sb.Append(indentString); // Write the open dataTable node sb.Append("<DataTable>" + Environment.NewLine); // Write out each property // (Manually added Name to the top so you do not have to scroll down to find the name // Write out the value for Name sb.Append(indentString2); sb.Append("<Name>" + dataTable.Name + "</Name>" + Environment.NewLine); // Write out the value for CheckConstraints // Create the CheckConstraintsWriter CheckConstraintsWriter checkConstraintsWriter = new CheckConstraintsWriter(); // Export the CheckConstraints collection to xml string checkConstraintXml = checkConstraintsWriter.ExportList(dataTable.CheckConstraints, indent + 2); sb.Append(checkConstraintXml); sb.Append(Environment.NewLine); // Write out the value for Fields // Create the FieldsWriter FieldsWriter fieldsWriter = new FieldsWriter(); // Export the Fields collection to xml string dataFieldXml = fieldsWriter.ExportList(dataTable.Fields, indent + 2); sb.Append(dataFieldXml); sb.Append(Environment.NewLine); // Write out the value for ForeignKeys // Create the foreignKeyWriter ForeignKeysWriter foreignKeyWriter = new ForeignKeysWriter(); // Write out the value for ForeignKeys string foreignKeyXml = foreignKeyWriter.ExportList(dataTable.ForeignKeys, indent + 2); sb.Append(foreignKeyXml); sb.Append(Environment.NewLine); // Write out the value for Indexes // Create the IndexesWriter IndexesWriter indexesWriter = new IndexesWriter(); // Export the Indexes collection to xml string dataIndexXml = indexesWriter.ExportList(dataTable.Indexes, indent + 2); sb.Append(dataIndexXml); sb.Append(Environment.NewLine); // Write out the value for IsView sb.Append(indentString2); sb.Append("<IsView>" + dataTable.IsView + "</IsView>" + Environment.NewLine); // Write out the value for SchemaName sb.Append(indentString2); sb.Append("<SchemaName>" + dataTable.SchemaName + "</SchemaName>" + Environment.NewLine); // Append the indentString sb.Append(indentString); // Write out the close dataTable node sb.Append("</DataTable>" + Environment.NewLine); // set the return value dataTableXml = sb.ToString(); } // return value return(dataTableXml); }
public void ExtractStringLiterals_NullArg() { var result = TextHelper.ExtractStringLiterals(null); Assert.IsEmpty(result); }
/// <summary> /// This method returns the Connection String /// </summary> public bool InstallConnectionString(TextLine connectionStringLine) { // initial value bool installed = false; // locals string newText = ""; string encryptedConnectionString = ""; TextLine useEncryptionTextLine = null; // verify the AppConfigPath was found if ((HasAppConfigPath) && (File.Exists(AppConfigPath))) { // if the AppConfigTextLinex collection exists and the ConnectionStringIndex is set and in range if ((ListHelper.HasOneOrMoreItems(AppConfigTextLines)) && (HasConnectionStringIndex) && (ConnectionStringIndex < AppConfigTextLines.Count)) { // If the connectionStringLine object exists if ((NullHelper.Exists(connectionStringLine)) && (TextHelper.Exists(ConnectionString))) { // if UseEncryption is true if (UseEncryptionCheckBox.Checked) { // get the textLine for useEncryption (this also sets the useEncryptionIndex useEncryptionTextLine = GetUseEncryptionTextLine(UseCustomKeyCheckBox.Checked); // if use custom encryption key if ((UseCustomKeyCheckBox.Checked) && (EncryptionKeyControl.HasText)) { // get the encryptionKey value string encryptionKey = EncryptionKeyControl.Text; // Encrypt the ConnectrionString using the EncryptionKey provided by user encryptedConnectionString = CryptographyHelper.EncryptString(ConnectionString, encryptionKey); } else { // Encrypt the ConnectrionString using the default EncryptionKey encryptedConnectionString = CryptographyHelper.EncryptString(ConnectionString); } // Get the nextText newText = " <add key=\"ConnectionString\" value=\"" + encryptedConnectionString + "\" />"; } else { // Get the nextText newText = " <add key=\"ConnectionString\" value=\"" + ConnectionString + "\" />"; } // If the UseEncryptionIndex value is set if (UseEncryptionIndex > 0) { // Change the text from false to true in UseEncryptionIndex Line AppConfigTextLines[UseEncryptionIndex].Text = " " + UseEncryptionStart + "\"" + "true" + "\"" + " />"; } // If the EncryptionKeyIndex value is set if (EncryptionKeyIndex > 0) { // local string encryptedEncryptionKey = CryptographyHelper.EncryptString(EncryptionKeyControl.Text); // Change the text from false to true in UseEncryptionIndex Line AppConfigTextLines[EncryptionKeyIndex].Text = " " + EncryptionKeyStart + "\"" + encryptedEncryptionKey + "\"" + " />"; } // Replace out all false values for true // Change the text to true in SetupComplete Line AppConfigTextLines[SetupCompleteIndex].Text = " " + SetupCompleteStart + "\"" + "true" + "\"" + " />"; // set the text for this line AppConfigTextLines[ConnectionStringIndex].Text = newText; // Get the text string updatedAppConfigText = WriteOutAppConfigText(); // if the text exist if (TextHelper.Exists(updatedAppConfigText)) { // Delete the AppConfig file File.Delete(AppConfigPath); // write out the app.config text File.AppendAllText(AppConfigPath, updatedAppConfigText); // success UserCancelled = false; // just in case this is visible after a Test still this.CopiedImage.Visible = false; // Show the Installed Image this.InstalledImage.Visible = true; // Change the text to finished this.CancelButton.Text = "Finished"; // Start the timer (this form will close in 5 seconds if the user doesn't close it sooner) InstalledTimer.Enabled = true; } } } } // return value return(installed); }
public void ExtractStringLiterals_EmptyArg() { var result = TextHelper.ExtractStringLiterals(string.Empty); Assert.IsEmpty(result); }
/// <summary> /// Displays data in table. /// </summary> /// <param name="ds">Dataset with data</param> protected void DisplayData(DataSet ds) { if (!DataHelper.DataSourceIsEmpty(ds)) { // Prepare list of tables SortedDictionary <string, DataTable> tables = new SortedDictionary <string, DataTable>(); foreach (DataTable dt in ds.Tables) { if (!DataHelper.DataSourceIsEmpty(dt)) { tables.Add(GetString("ObjectType." + dt.TableName), dt); } } // Generate the tables foreach (DataTable dt in tables.Values) { pnlContent.Controls.Add(new LiteralControl("<h3>" + GetString("ObjectType." + dt.TableName) + "</h3>")); if (dt.Columns.Count >= 6) { StringBuilder sb; // Write all rows foreach (DataRow dr in dt.Rows) { sb = new StringBuilder(); sb.Append("<table class=\"table table-hover\">"); // Add header sb.AppendFormat("<thead><tr class=\"unigrid-head\"><th>{0}</th><th class=\"main-column-100\">{1}</th></tr></thead><tbody>", GetString("General.FieldName"), GetString("General.Value")); // Add values foreach (DataColumn dc in dt.Columns) { sb.AppendFormat("<tr><td><strong>{0}</strong></td><td class=\"wrap-normal\">", dc.ColumnName); string content = null; // Binary columns if ((dc.DataType == typeof(byte[])) && (dr[dc.ColumnName] != DBNull.Value)) { content = "<binary data>"; } else { content = ValidationHelper.GetString(dr[dc.ColumnName], String.Empty); } bool standard = true; switch (dc.ColumnName.ToLowerCSafe()) { // Document content case "documentcontent": EditableItems items = new EditableItems(); items.LoadContentXml(ValidationHelper.GetString(dr[dc.ColumnName], String.Empty)); // Add regions foreach (DictionaryEntry region in items.EditableRegions) { sb.Append("<span class=\"VersionEditableRegionTitle\">" + (string)region.Key + "</span>"); string regionContent = HTMLHelper.ResolveUrls((string)region.Value, SystemContext.ApplicationPath); sb.Append("<span class=\"VersionEditableRegionText\">" + regionContent + "</span>"); } // Add web parts foreach (DictionaryEntry part in items.EditableWebParts) { sb.Append("<span class=\"VersionEditableWebPartTitle\">" + (string)part.Key + "</span>"); string regionContent = HTMLHelper.ResolveUrls((string)part.Value, SystemContext.ApplicationPath); sb.Append("<span class=\"VersionEditableWebPartText\">" + regionContent + "</span>"); } standard = false; break; // XML columns case "pagetemplatewebparts": case "webpartproperties": case "reportparameters": case "classformdefinition": case "classxmlschema": case "classformlayout": content = HTMLHelper.ReformatHTML(content); break; } // Standard rendering if (standard) { content = HttpUtility.HtmlEncode(content); content = TextHelper.EnsureHTMLLineEndings(content); content = content.Replace("\t", " "); sb.Append("<div style=\"max-height: 300px; overflow: auto;\">" + content + "</div>"); } sb.Append("</td></tr>"); } sb.Append("</tbody></table><br />\n"); pnlContent.Controls.Add(new LiteralControl(sb.ToString())); } } else { GridView newGrid = new GridView(); newGrid.ID = "grid" + dt.TableName; newGrid.EnableViewState = false; newGrid.HeaderStyle.HorizontalAlign = HorizontalAlign.Left; newGrid.CellPadding = 3; newGrid.GridLines = GridLines.Horizontal; pnlContent.Controls.Add(newGrid); newGrid.DataSource = ds; newGrid.DataMember = dt.TableName; newGrid.DataBind(); } } } }
public void ExtractStringLiterals_NoLiterals() { var result = TextHelper.ExtractStringLiterals(" I like green 'apples'"); Assert.IsEmpty(result); }