public static void OpenCommentDiscussion(int articleId, int topicId) { try { var api = DiscourseHelper.CreateApi(); api.SetVisibility(topicId, true); // delete the worthless auto-generated "this topic is now invisible/visible" rubbish var topic = api.GetTopic(topicId); foreach (var post in topic.Posts.Where(p => p.Type == Post.PostType.ModeratorAction)) { api.DeletePost(post.Id); } StoredProcs .Articles_CreateOrUpdateArticle(articleId, Discourse_Topic_Opened: YNIndicator.Yes) .Execute(); } catch (Exception ex) { throw new InvalidOperationException( string.Format("An unknown error occurred when attempting to open the Discourse discussion. " + "Verify that the article #{0} is assigned to a valid correct topic ID (currently #{1})", articleId, topicId), ex); } }
private void LoadConfigExecute(object sender) { var fileDialog = new OpenFileDialog(); fileDialog.Multiselect = false; fileDialog.CheckFileExists = true; fileDialog.DefaultExt = "*.msConfigStore"; fileDialog.Filter = "ConfigFile (*.msConfigStore)|*.msConfigStore"; var result = fileDialog.ShowDialog(); if (result.HasValue && result.Value && File.Exists(fileDialog.FileName)) { Tables.Clear(); Views.Clear(); StoredProcs.Clear(); SelectedTable = null; var binFormatter = new BinaryFormatter(); ConfigStore options; try { using (var fs = fileDialog.OpenFile()) { options = (ConfigStore)binFormatter.Deserialize(fs); } } catch (Exception) { Status = "File is an in invalid format"; return; } var version = typeof(SharedMethods).Assembly.GetName().Version; if (new Version(options.Version) != version) { var messageBoxResult = MessageBox.Show(Application.Current.MainWindow, "Warning Version missmatch", string.Format("The current Entity Creator version ({0}) is not equals the version ({1}) you have provided.", version, options.Version), MessageBoxButton.OKCancel); if (messageBoxResult == MessageBoxResult.Cancel) { return; } } if (options.SourceConnectionString != null) { ConnectionString = options.SourceConnectionString; CreateEntrysAsync(ConnectionString, "", string.Empty).ContinueWith(task => { foreach (var optionsAction in options.Actions) { optionsAction.Replay(this); } }); } } }
public static IList <Post> GetFeaturedCommentsForArticle(int articleId) { try { return(DiscourseCache.GetOrAdd( "FeaturedCommentsForArticle_" + articleId, () => { Logger.Debug("Getting and caching featured comments for article (ID={0}).", articleId); var api = DiscourseHelper.CreateApi(); return StoredProcs.Articles_GetFeaturedComments(articleId) .Execute() .Select(c => api.GetReplyPost(c.Discourse_Post_Id)) .Where(p => !p.Hidden) .ToList() .AsReadOnly(); } )); } catch (Exception ex) { Logger.Error("Error getting featured comments for article (ID={0}), error: {1}", articleId, ex); return(new Post[0]); } }
private void ddlConfigurationFile_SelectedIndexChanged(object sender, EventArgs e) { this.ddlInstance.Items.Clear(); if (this.ddlConfigurationFile.SelectedIndex <= 0) { return; } if (this.ddlConfigurationFile.SelectedValue == "X") { this.ctl_txtConfigurationFileName.Visible = true; this.ctl_ddlInstance.Visible = false; this.ctl_txtInstanceName.Visible = true; } else { this.ctl_txtConfigurationFileName.Visible = false; this.ctl_ddlInstance.Visible = true; this.ctl_txtInstanceName.Visible = false; this.ddlInstance.Items.Add(string.Empty); this.ddlInstance.Items.AddRange(StoredProcs .ConfigurationFiles_GetConfigurationFile(int.Parse(ddlConfigurationFile.SelectedValue), null) .Execute() .ConfigurationFileInstances_Extended .Select(cfg => new ListItem { Text = cfg.Instance_Name, Value = cfg.Instance_Name }) .ToArray() ); } }
public ActionResult Login(string username, string password) { bool validLogin = StoredProcs.Authors_ValidateLogin(username, password).Execute().Value; if (validLogin) { var author = AuthorModel.GetAuthorBySlug(username); var principal = new AuthorPrincipal(author); var userData = JsonConvert.SerializeObject(principal.ToSerializableModel()); var expiresDate = DateTime.Now.AddMinutes(30); var authTicket = new FormsAuthenticationTicket(1, author.Slug, DateTime.Now, expiresDate, false, userData); string encTicket = FormsAuthentication.Encrypt(authTicket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { HttpOnly = true, Expires = expiresDate, Path = FormsAuthentication.FormsCookiePath }; this.Response.Cookies.Add(cookie); var cookieIsAdmin = new HttpCookie("IS_ADMIN", "1") { HttpOnly = false, Expires = expiresDate, Path = FormsAuthentication.FormsCookiePath }; this.Response.Cookies.Add(cookieIsAdmin); return(new RedirectResult(FormsAuthentication.GetRedirectUrl(author.Slug, false))); } return(View()); }
public ActionResult ApproveComment(FeatureCommentViewModel post) { if (this.User == null) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } if (post.Article == null || post.Comment == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var article = ArticleModel.GetArticleById((int)post.Article); if (article == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } if (!this.User.IsAdmin && this.User.Identity.Name != article.Author.Slug) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } if (!StoredProcs.Articles_ApproveComment(article.Id, post.Comment).Execute().Value) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } if (!string.IsNullOrEmpty(Request.QueryString["no-redirect"])) { return(new HttpStatusCodeResult(HttpStatusCode.Accepted)); } return(RedirectToRoute("CommentModerationAdmin")); }
public ActionResult UnfeatureComment(FeatureCommentViewModel post) { if (this.User == null) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } if (post.Article == null || post.Comment == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } var article = ArticleModel.GetArticleById((int)post.Article); if (article == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } if (!this.User.IsAdmin && this.User.Identity.Name != article.Author.Slug) { return(new HttpStatusCodeResult(HttpStatusCode.Forbidden)); } if (!StoredProcs.Articles_UnfeatureComment(article.Id, post.Comment).Execute().Value) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } return(RedirectToRoute("ArticleCommentsAdmin", new { id = article.Id })); }
public ActionResult EditComment(int article, int comment, string body, string name) { var articleModel = ArticleModel.GetArticleById(article); if (articleModel == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } var commentModel = CommentModel.GetCommentById(comment); if (commentModel == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } if (body == null) { body = commentModel.BodyRaw; name = commentModel.Username; return(View(new EditCommentViewModel { Article = articleModel, Comment = commentModel, Post = new CommentFormModel { Body = body, Name = name } })); } StoredProcs.Comments_CreateOrUpdateComment(comment, article, body, name, commentModel.PublishedDate, commentModel.UserIP, commentModel.UserToken, commentModel.ParentCommentId).ExecuteNonQuery(); return(RedirectToRoute("ArticleCommentsAdmin", new { id = articleModel.Id })); }
/// <summary> /// Runs a stored proc from the database /// </summary> /// <param name="spName">Name of the stored proc to run</param> /// <param name="parameters">a list of parameters to be passed to the stored proc</param> /// <returns></returns> public int RunStoredProc(StoredProcs spName, List <Parameter> parameters) { int returnValue; using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) { var cmd = new SqlCommand(spName.ToString(), con) { CommandType = CommandType.StoredProcedure }; foreach (var parameter in parameters) { cmd.Parameters.AddWithValue(parameter.ParameterName, parameter.ParameterValue); } cmd.Connection.Open(); returnValue = cmd.ExecuteNonQuery(); cmd.Connection.Close(); } return(returnValue); }
/// <summary> /// Runs a stored proc from the database and returns an ID of the record that was inserted /// This will add a @ReturnVal to the parameter list. Your stored proc needs to include this /// value as well /// </summary> /// <param name="spName">Name of the stored proc to run</param> /// <param name="parameters">a list of parameters to be passed to the stored proc</param> /// <returns>ID of the inserted record</returns> public int RunStoredProcReturnId(StoredProcs spName, List <Parameter> parameters) { int returnValue; using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) { var cmd = new SqlCommand(spName.ToString(), con) { CommandType = CommandType.StoredProcedure }; foreach (var parameter in parameters) { cmd.Parameters.AddWithValue(parameter.ParameterName, parameter.ParameterValue); } var param = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int); param.Direction = ParameterDirection.Output; cmd.Connection.Open(); cmd.ExecuteNonQuery(); var result = param.Value; returnValue = (int)result; cmd.Connection.Close(); } return(returnValue); }
public override void Import(IBuildImporterContext context) { var configurer = (TfsConfigurer)this.GetExtensionConfigurer(); string buildNumber = VsoArtifactImporter.DownloadAndImport( configurer, this, this.TeamProject, this.TfsBuildNumber, this.BuildDefinition, new ArtifactIdentifier(context.ApplicationId, context.ReleaseNumber, context.BuildNumber, context.DeployableId, this.ArtifactName) ); if (this.CreateBuildNumberVariable) { this.LogDebug($"Setting $TfsBuildNumber build variable to {buildNumber}..."); StoredProcs.Variables_CreateOrUpdateVariableDefinition( Variable_Name: "TfsBuildNumber", Environment_Id: null, Server_Id: null, ApplicationGroup_Id: null, Application_Id: context.ApplicationId, Deployable_Id: null, Release_Number: context.ReleaseNumber, Build_Number: context.BuildNumber, Execution_Id: null, Value_Text: buildNumber, Sensitive_Indicator: YNIndicator.No ).Execute(); this.LogInformation("$TfsBuildNumber build variable set to: " + buildNumber); } }
public static int CreateCommentDiscussion(ArticleModel article) { Logger.Information("Creating comment discussion for article \"{0}\" (ID={1}).", article.Title, article.Id); var api = DiscourseHelper.CreateApi(); // create topic and embed <!--ARTICLEID:...--> in the body so the hacky JavaScript // for the "Feature" button can append the article ID to each of its query strings var topic = api.CreateTopic( new Category(Config.Discourse.CommentCategory), article.Title, string.Format( "Discussion for the article: {0}\r\n\r\n<!--ARTICLEID:{1}-->", article.Url, article.Id ) ); api.SetVisibility(topic.Id, false); StoredProcs .Articles_CreateOrUpdateArticle(article.Id, Discourse_Topic_Id: topic.Id) .Execute(); return(topic.Id); }
public static void UnfeatureComment(int articleId, int discourseTopicId) { Logger.Information("Unfeaturing comment for article (ID={0}) and discourse topic (ID={1}).", articleId, discourseTopicId); StoredProcs .Articles_UnfeatureComment(articleId, discourseTopicId) .Execute(); }
public static IEnumerable <AdModel> GetAllFooterAds() { var ads = StoredProcs.Ads_GetAds().Execute(); return(ads.Select(ad => new AdModel { Id = ad.Ad_Id, BodyHtml = ad.Ad_Html })); }
public static bool PullCommentsFromDiscourse(ArticleModel article) { Logger.Debug("Pulling and caching comments from Discourse for article (ID={0}).", article.Id); const int commentsToPull = 40; if (article.DiscourseTopicId == null) { return(false); } if (article.CachedCommentCount >= commentsToPull) { return(false); } if (article.PublishedDate < DateTime.Now.Subtract(TimeSpan.FromDays(60.0))) { return(false); } var cachedComments = StoredProcs.Comments_GetComments(article.Id) .Execute() .Where(c => c.Discourse_Post_Id != null) .ToDictionary(c => (int)c.Discourse_Post_Id); Logger.Debug("Cached comments count for article (ID={0}) is: {1}", article.Id, cachedComments.Keys.Count); var topic = GetDiscussionTopic((int)article.DiscourseTopicId); int commentsPulled = 0; foreach (var post in topic.Posts.Where(p => !p.Username.Equals("PaulaBean", StringComparison.OrdinalIgnoreCase)).Take(commentsToPull)) { if (cachedComments.ContainsKey(post.Id)) { continue; } commentsPulled++; StoredProcs.Comments_CreateOrUpdateComment( article.Id, CommentModel.TrySanitizeDiscourseBody(post.BodyHtml), post.Username, post.PostDate, post.Id ).Execute(); } if (commentsPulled > 0) { Logger.Debug("Comments were pulled and cached from Discourse for article (ID={0}).", article.Id); } else { Logger.Debug("No comments were pulled from Discourse for article (ID={0}).", article.Id); } return(commentsPulled > 0); }
private TfsIssueTrackingProvider GetProvider() { var application = StoredProcs.Applications_GetApplication(this.EditorContext.ApplicationId) .Execute() .Applications_Extended .First(); return((TfsIssueTrackingProvider)Util.Providers.CreateProviderFromId <IssueTrackingProviderBase>(application.IssueTracking_Provider_Id.Value)); }
public static void ReassignCommentDiscussion(int articleId, int topicId) { StoredProcs .Articles_CreateOrUpdateArticle( articleId, Discourse_Topic_Id: topicId, Discourse_Topic_Opened: YNIndicator.No ).Execute(); }
private void CreateArtifact(string artifactName, string path) { if (string.IsNullOrEmpty(artifactName) || artifactName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { throw new InvalidOperationException("Artifact Name cannot contain invalid file name characters: " + new string(Path.GetInvalidFileNameChars())); } if (StoredProcs.Releases_GetRelease(this.Context.ApplicationId, this.Context.ReleaseNumber) .Execute().ReleaseDeployables_Extended .Any(rd => rd.Deployable_Id == this.Context.DeployableId && rd.InclusionType_Code == Domains.DeployableInclusionTypes.Referenced)) { this.LogError( "An Artifact cannot be created for this Deployable because the Deployable is Referenced (as opposed to Included) by this Release. " + "To prevent this error, either include this Deployable in the Release or use a Predicate to prevent this action group from being executed."); return; } var fileOps = this.Context.Agent.GetService <IFileOperationsExecuter>(); var zipPath = fileOps.CombinePath(this.Context.TempDirectory, artifactName + ".zip"); this.LogDebug("Preparing directories..."); fileOps.DeleteFiles(new[] { zipPath }); this.ThrowIfCanceledOrTimeoutExpired(); var rootEntry = fileOps.GetDirectoryEntry( new GetDirectoryEntryCommand { Path = path, Recurse = false, IncludeRootPath = false } ).Entry; if ((rootEntry.Files == null || rootEntry.Files.Length == 0) && (rootEntry.SubDirectories == null || rootEntry.SubDirectories.Length == 0)) { this.LogWarning("There are no files to capture in this artifact."); } this.LogDebug("Zipping output..."); this.Context.Agent.GetService <IRemoteZip>().CreateZipFile(path, zipPath); var zipFileEntry = fileOps.GetFileEntry(zipPath); this.ThrowIfCanceledOrTimeoutExpired(); this.LogDebug("Transferring file to artifact library..."); var artifactId = new ArtifactIdentifier(this.Context.ApplicationId, this.Context.ReleaseNumber, this.Context.BuildNumber, this.Context.DeployableId, artifactName); ArtifactBuilder.ImportZip(artifactId, fileOps, zipFileEntry); this.LogDebug("Cleaning up..."); fileOps.DeleteFiles(new[] { zipPath }); this.LogInformation("Artfact captured from TFS."); }
protected override void Execute() { var collection = this.GetTeamProjectCollection(); var buildService = collection.GetService <IBuildServer>(); var buildDefinition = buildService.GetBuildDefinition(this.TeamProject, this.BuildDefinition); if (buildDefinition == null) { throw new InvalidOperationException($"Build definition \"{this.BuildDefinition}\" was not found."); } this.LogInformation($"Queueing build of {this.TeamProject}, build definition {Util.CoalesceStr(this.BuildDefinition, "any")}..."); var queuedBuild = buildService.QueueBuild(buildDefinition); this.LogInformation($"Build number \"{queuedBuild.Build.BuildNumber}\" created for definition \"{queuedBuild.BuildDefinition.Name}\"."); if (this.CreateBuildNumberVariable) { this.LogDebug($"Setting $TfsBuildNumber build variable to {queuedBuild.Build.BuildNumber}..."); StoredProcs.Variables_CreateOrUpdateVariableDefinition( Variable_Name: "TfsBuildNumber", Environment_Id: null, Server_Id: null, ApplicationGroup_Id: null, Application_Id: this.Context.ApplicationId, Deployable_Id: null, Release_Number: this.Context.ReleaseNumber, Build_Number: this.Context.BuildNumber, Execution_Id: null, Value_Text: queuedBuild.Build.BuildNumber, Sensitive_Indicator: YNIndicator.No ).Execute(); this.LogInformation("$TfsBuildNumber build variable set to: " + queuedBuild.Build.BuildNumber); } if (this.WaitForCompletion) { this.LogInformation("Waiting for build completion..."); queuedBuild.StatusChanged += (s, e) => { this.ThrowIfCanceledOrTimeoutExpired(); this.LogDebug("TFS Build status reported: " + ((IQueuedBuild)s).Status); }; queuedBuild.WaitForBuildCompletion(TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(this.Timeout)); } if (this.ValidateBuild) { this.ValidateBuildStatus(); } this.LogInformation($"TFS build {queuedBuild.Build.BuildNumber} created."); }
public static ArticleModel GetArticleByLegacyPost(int postId) { var article = StoredProcs.Articles_GetArticleByLegacyPost(postId).Execute(); if (article == null) { return(null); } return(ArticleModel.FromTable(article)); }
public static ArticleModel GetArticleBySlug(string slug) { var article = StoredProcs.Articles_GetArticleBySlug(slug).Execute(); if (article == null) { return(null); } return(ArticleModel.FromTable(article)); }
public static ArticleModel GetArticleById(int id) { var article = StoredProcs.Articles_GetArticleById(id).Execute(); if (article == null) { return(null); } return(ArticleModel.FromTable(article)); }
public ActionResult DeleteComments(DeleteCommentsModel post) { var commentIdsCsv = string.Join(",", post.Delete); Logger.Information("Deleting comments with IDs \"{0}\".", commentIdsCsv); StoredProcs.Comments_DeleteComments(commentIdsCsv).Execute(); return(Redirect(Request.UrlReferrer.ToString())); }
public static void ReassignCommentDiscussion(int articleId, int topicId) { Logger.Information("Reassigning comment discussion for article (ID={0}) and topic (ID={1}).", articleId, topicId); StoredProcs .Articles_CreateOrUpdateArticle( articleId, Discourse_Topic_Id: topicId, Discourse_Topic_Opened: YNIndicator.No ).Execute(); }
public ActionResult EditSeries(EditSeriesViewModel post) { StoredProcs.Series_CreateOrUpdateSeries( post.Series.Slug, post.Series.Title, post.Series.Description ).Execute(); return(RedirectToAction("index")); }
public static SeriesModel GetSeriesBySlug(string slug) { var series = StoredProcs.Series_GetSeriesBySlug(slug).Execute(); if (series == null) { return(null); } return(SeriesModel.FromTable(series)); }
public static AuthorModel GetAuthorBySlug(string slug) { var author = StoredProcs.Authors_GetAuthorBySlug(slug).Execute(); if (author == null) { return(null); } return(AuthorModel.FromTable(author)); }
public void CreateEntrys(string connection, string outputPath, string database) { TargetDir = outputPath; Manager = new DbAccessLayer(DbAccessType.MsSql, connection); bool checkDatabase; try { checkDatabase = Manager.CheckDatabase(); } catch (Exception) { checkDatabase = false; } if (!checkDatabase) { throw new Exception("Database not accessible. Maybe wrong Connection or no Selected Database?"); } var databaseName = string.IsNullOrEmpty(Manager.Database.DatabaseName) ? database : Manager.Database.DatabaseName; if (string.IsNullOrEmpty(databaseName)) { throw new Exception("Database not exists. Maybe wrong Connection or no Selected Database?"); } WinConsole.WriteLine("Connection OK ... Reading Server Version ..."); SqlVersion = Manager.RunSelect <string>(Manager.Database.CreateCommand("SELECT SERVERPROPERTY('productversion')")).FirstOrDefault(); WinConsole.WriteLine("Server version is {0}", SqlVersion); WinConsole.WriteLine("Reading Tables from {0} ...", databaseName); Tables = Manager.Select <TableInformations>() .ToArray() .AsParallel() .Select(s => new TableInfoModel(s, databaseName, new DbAccessLayer(DbAccessType.MsSql, connection))) .ToList(); Views = Manager.Select <ViewInformation>() .ToArray() .AsParallel() .Select(s => new TableInfoModel(s, databaseName, new DbAccessLayer(DbAccessType.MsSql, connection))) .ToList(); StoredProcs = Manager.Select <StoredProcedureInformation>() .Select(s => new StoredPrcInfoModel(s)) .ToList(); WinConsole.WriteLine( "Found {0} Tables, {1} Views, {2} Procedures ... select a Table to see Options or start an Action", Tables.Count(), Views.Count(), StoredProcs.Count()); Enums = new List <Dictionary <int, string> >(); RenderMenu(); }
public ActionResult EditArticle(EditArticleViewModel post) { if (string.IsNullOrEmpty(post.Article.Series.Slug)) { this.ModelState.AddModelError(string.Empty, "A series is required"); } if (string.IsNullOrEmpty(post.Article.Author.Slug)) { this.ModelState.AddModelError(string.Empty, "An author is required"); } if (!string.IsNullOrEmpty(post.Article.Author.Slug) && !this.User.IsAdmin && post.Article.Author.Slug != this.User.Identity.Name) { this.ModelState.AddModelError(string.Empty, "Only administrators can change authors."); } if (!this.ModelState.IsValid) { return(View(post)); } try { if (post.OpenCommentDiscussionChecked && post.Article.DiscourseTopicId > 0) { DiscourseHelper.OpenCommentDiscussion((int)post.Article.Id, (int)post.Article.DiscourseTopicId); } Logger.Information("Creating or updating article \"{0}\".", post.Article.Title); int?articleId = StoredProcs.Articles_CreateOrUpdateArticle( post.Article.Id, post.Article.Slug ?? this.User.Identity.Name, post.PublishedDate, post.Article.Status, post.Article.Author.Slug, post.Article.Title, post.Article.Series.Slug, post.Article.BodyHtml, post.Article.DiscourseTopicId ).Execute(); post.Article.Id = post.Article.Id ?? articleId; if (post.CreateCommentDiscussionChecked) { DiscourseHelper.CreateCommentDiscussion(post.Article); } return(RedirectToAction("index")); } catch (Exception ex) { post.ErrorMessage = ex.ToString(); return(View(post)); } }
private DataTable ObtenerDatos() { var tabla = new dsImpresiones.TotalPagoDataTable(); var pagos = StoredProcs.ConsTotalPagos(Desde, Hasta, IdCarrera, IdCurso, IdMedioPago); foreach (var p in pagos) { tabla.AddTotalPagoRow(p.Carrera, p.Curso, p.IdCarrera, p.IdCurso, p.MedioPago, p.Cantidad, p.Total); } return(tabla); }