Dynamic html news page is not working in C# - c#

I'm trying to create a dynamic news html page.
The problem occurs when I try to create the html dynamically. I'm new to C#, and don't know what's wrong. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NewsAPI;
using NewsAPI.Models;
using NewsAPI.Constants;
namespace NewsDemo
{
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadNewsPage();
}
}
protected void LoadNewsPage()
{
try
{
var newsApiClient = new NewsApiClient("key");
List<string> mylist = new List<string>();
mylist.Add("google-news");
mylist.Add("bbc-news");
mylist.Add("cnn");
mylist.Add("the-new-york-times");
var articlesResponse = newsApiClient.GetTopHeadlines(new TopHeadlinesRequest
{
Sources = mylist,
Language = Languages.EN
});
if (articlesResponse.Status == Statuses.Ok)
{
string resulHtml = "";
resulHtml += "<table>";
foreach (var article in articlesResponse.Articles)
{
resulHtml += string.Format("<tr style='valign:top'>", "");
resulHtml += string.Format("<td width=20%><img src='{0}' width='250px' height='200px'></img></td>", article.UrlToImage);
resulHtml += string.Format("<td width=80%><a href='{0}'><h3>{1}</h3></a>{1}<br>{2}<br>{3}<br><br></td>", article.Url, article.Title, article.Author, article.Description);
resulHtml += string.Format("</tr>", "");
}
resulHtml += string.Format("</table>", "");
Label1.Text = resulHtml;
}
}
catch (Exception ex)
{
throw;
}
}
}
}
Whenever I try to run it, (in VS), Chrome opens and the page never loads. I have no idea what is wrong, as I have a console app that can fetch the news and that works fine.
Any help appreciated.
Thanks!

EDIT
Your comments to my answer helped my understand more.
I think your problem doesn't depend on your code but on a known problem with Chrome+Visual Studio
In short:
Either you can debug with another browser
Or you disable JavaScript debugging
I tested your LoadNewsPage() and it does get HTML just fine.
What seems strange is that you are inserting the HTML into the text of a Label.
Instead of doing that, add this HTML in your markup:
<div id="MyNewsSection" runat="server"></div>
And then replace this
Label1.Text = resulHtml;
with
MyNewsSection.InnerHtml = resulHtml;
Also, as a general debugging help, press F12 when in Chrome: if there are any errors, they will be shown to you.

Related

Highlight all occurances of a selected word in AvalonEdit using an IBackgroundRenderer

I am relatively new to C# and I'm working on a simple application that makes use of AvalonEdit as a small code editor embedded in the bottom of the UI.
I want to highlight all occurrences of a selected word. Right now I have this working using a DocumentColorizingTransformer as outlined by Suplanus in this question.
My code is basically identical to the implementation posted there, but it has its downsides. Mainly that the default highlighting is fighting with the new LineTransformers highlighting and there are visual artifacts that can't be avoided.
So I came across this question where Siegfried (partially) explains a way to accomplish this by using an IBackgroundRenderer class. Unfortunately there isn't a lot of code to go on. Just an outline of how to structure the draw function. There is another question where trigger_segfault posts some similar code utilizing an IBackgroundRenderer but the goal is not to highlight matching words, but search results.
So I've kind of cobbled together what I can between all of these questions and arrived here:
(Removed. See bottom of post for working code)
My question is simply, how do I pass in the matching words? Do I assign an event handler to the "SelectionChanged" event: txtSvgSource.TextArea.SelectionChanged += ValidateSelection; and then implement a setter in my HighlightSelectedWordBackgroundRenderer class to update currentResults?
I just don't understand how to pass in the words to highlight.
I'd like to move away from my current DocumentColorizingTransformer approach and properly implement the IBackgroundRenderer instead.
Anyone with experience using AvalonEdit that could point me in the right direction, your help would be extremely appreciated!
Thanks so much.
Edit 2:
I figured everything out. Here's the final working code if anyone finds this useful:
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace SVGRecolorTool {
public class SearchResult : TextSegment {
/// <summary>The regex match for the search result.</summary>
public Match Match { get; }
/// <summary>Constructs the search result from the match.</summary>
public SearchResult(Match match) {
this.StartOffset = match.Index;
this.Length = match.Length;
this.Match = match;
}
}
public class HighlightSelectedWordBackgroundRenderer : IBackgroundRenderer {
private TextEditor _editor;
TextSegmentCollection<SearchResult> currentResults = new TextSegmentCollection<SearchResult>();
public HighlightSelectedWordBackgroundRenderer(TextEditor editor) {
_editor = editor;
Background = new SolidColorBrush(Color.FromArgb(90, 255, 255, 255));
Background.Freeze();
}
public KnownLayer Layer {
get { return KnownLayer.Caret; }
}
public void Draw(TextView textView, DrawingContext drawingContext) {
if (!textView.VisualLinesValid)
return;
var visualLines = textView.VisualLines;
if (visualLines.Count == 0)
return;
int viewStart = visualLines.First().FirstDocumentLine.Offset;
int viewEnd = visualLines.Last().LastDocumentLine.EndOffset;
foreach (TextSegment result in currentResults.FindOverlappingSegments(viewStart, viewEnd - viewStart)) {
BackgroundGeometryBuilder geoBuilder = new BackgroundGeometryBuilder();
geoBuilder.AlignToWholePixels = true;
geoBuilder.CornerRadius = 0;
geoBuilder.AddSegment(textView, result);
Geometry geometry = geoBuilder.CreateGeometry();
if (geometry != null) {
drawingContext.DrawGeometry(Background, null, geometry);
}
}
}
public TextSegmentCollection<SearchResult> CurrentResults {
get { return currentResults; }
}
public Brush Background { get; set; }
}
}
_renderer = new HighlightSelectedWordBackgroundRenderer(txtSvgSource);
txtSvgSource.TextArea.TextView.BackgroundRenderers.Add(_renderer);
txtSvgSource.TextArea.SelectionChanged += HighlightSelection;
private void HighlightSelection(object sender, EventArgs e) {
_renderer.CurrentResults.Clear();
if(txtSvgSource.SelectedText.Length > 2) {
string pattern = #"\b" + txtSvgSource.SelectedText + #"\b";
Regex rg = new Regex(pattern);
MatchCollection matchedSelections = rg.Matches(txtSvgSource.Text);
if (matchedSelections.Count > 1) {
foreach (Match result in matchedSelections) {
_renderer.CurrentResults.Add(new SearchResult(result));
}
} else {
_renderer.CurrentResults.Clear();
}
} else {
_renderer.CurrentResults.Clear();
}
txtSvgSource.TextArea.TextView.InvalidateLayer(KnownLayer.Selection);
}

Namespace is not working properly

I am getting a error for my namespace that says " the type or namespace name could not be found (are you missing a using directive or an assembly reference?) " and have no idea why... i have been trying to figure this one out for hours now... btw i am a newbie with c#
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using portfolioNamespace;
public partial class DefaultCode : System.Web.UI.Page{
Portfolio myPortfolio;
protected void Page_Load(object sender, EventArgs e){
//declare
myPortfolio = new Portfolio();
populate();
}
private void populate(){
//populate everything
populateMenu();
populateHome();
populateSamples();
populateAbout();
}
private void populateMenu(){
//populate the menu
String[] menu;
menu = myPortfolio.getMyMenu();
repLinks.DataSource = menu;
repLinks.DataBind();
//populates a hidden text box so i can get an array in javascript
for (int i = 0; i<=menu.Length - 1; i++){
dummy.Value = dummy.Value & menu(i) & "-";
}
}
private void populateHome(){
//populate home
homeRepeater.DataSource = myPortfolio.getHomeInfo;
homeRepeater.DataBind();
}
private void populateSamples(){
//populate samples
samplesRepeater.DataSource = myPortfolio.getSamplesInfo;
samplesRepeater.DataBind();
}
private void populateAbout(){
//populate about
aboutRepeater.DataSource = myPortfolio.getAboutInfo;
aboutRepeater.DataBind();
}
}
In your Solution Explorer Right click your References, click Add Reference > Browse, then find your dll file that contains portfolioNamespace and add it to your References.
See documentation for more details: How to: Add or Remove References By Using the Add Reference Dialog Box
You probably haven't created the portfolioNamespace.
You do so by wrapping your code in
namespace portfolioNamespace
{
//your code here
}
Have a read through these references, namespace (C# Reference) and Namespaces (C# Programming Guide)
It is not clear which file is getting error.
whatever the class name is giving error put cursor on that and press CTRL + DOT(.) it will suggest you to add the correct name space

User Input from textbox1 > store in a list > output in textbox2

I just have a question regarding C# list. I am a totally noob when it comes to programming and I'm really sorry for being a bird brainer. I am doing some practice coding and I am creating a simple program that will allow users to input names through textbox1 and then once they press the button1, the names will be stored in a List and will be output on textbox2.
I am having hard time storing the data from textbox1. Checked it online but I haven't found the right article for my concern so I'm trying my luck here.
Sorry guys, I forgot to mention I am using Winforms.
Thank you so much for the fast replies.
assuming winforms...
Drag and drop 2 lists and a button onto your designer.
drag a button onto your designer
double-click your button to automatically create an event
make a list structure somewhere inside your form to store the list
instantiate your list in the form constructor
in the button1_Click event add the text of textbox1 to the list
generate the text of 1textbox2`
here is an example
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
list = new List<string>();
}
List<string> list;
private void button1_Click(object sender, EventArgs e)
{
list.Add(textBox1.Text);
string txt = "";
foreach(string s in list)
{
txt += s + " ";
}
textBox2.Text = txt;
}
}
}
Something like that ?
string name = Textbox1.Text;
ListBox1.Add(name);
If your utilizing a traditional Windows Form Application; I'm not sure you meant to store the data in another Text Box. But a List Box may be more along your goal.
Drag the following: Textbox, Second Textbox, Listbox, and Button from the toolbox to your Form.
Adjust them however you would like, treat them like a canvas for a painting.
Once it appears to be configured how you would like double click the Button.
At this point Visual Studio will leave Designer View and go into Code View. So you'll be able to see the code. It will automatically place you in the Button code block.
These blocks are quite important, as you progress you'll notice how C# is structured.
private void button1_click(object sender, EventArgs e)
{
// Logic to add will go in here.
}
What does this mean?
Private : Is the modifier, it means it is restricted to this class.
Void: Means it isn't asking for a return type.
button1_click: That is the name of the button, you can change that within it's Properties. It's good practice to name the component infront so you know what your working with.
What that entire block is, is an Event. So when it is clicked it will perform an action. That is what it means; so this is where your goal is implemented:
private void btnAddToList_Click(object sender, EventArgs e)
{
// Test to ensure it isn't null.
if(txtAddText.Text != String.EmptyOrNull)
{
// Declare a variable with the initial textbox value.
string txtVar = txtAddText.Text;
// Has the second textbox inherit value from other Textbox.
txtNewText = txtVar
// Now Add it to a Listbox.
lstContainer.Items.Add(txtAddText.Text + DateTime.Now());
}
else
{
// Null or Empty Character, Error Message.
MessageBox.Show("Invalid Entry, please enter a valid entry");
}
}
That will provide the fundamental knowledge, but as you can see from your other examples they do it differently. You'll notice that bugs can exist in such logic if you aren't careful. Which you'll learn to identify based on the structure you configure.
Hopefully this is helpful, and it looks like a lot of others did some terrific post for you as well.
Happy coding.
You could use something simple as this:
private void button1_Click_1(object sender, EventArgs e)
{
string[] names = textBox1.Text.Split(new string[] { " ", Environment.NewLine, "," }, StringSplitOptions.RemoveEmptyEntries);
//you can add more parameters for splitting the string
textBox2.Text = string.Join(",", names);
//you can replace the comma with something more suitable for you
}
The first line splits the string that you entered in the textBox1 (hence names separated by newlines, blank characters or commas) into array of string (instead of list that you requested) and the second line joins the strings into one big string of names separated by commas and puts it into the textBox2
This is very simple.
List<string> mylist=new List<string>();
mylist.Add(textbox1.Text);
textbox2.Text=mylist[mylist.Count - 1]
First you create a list of string objects.
Then add the text from textbox1 to the end of the list.
Then get the last element you added from the list by getting the length of the list and subtracting 1 since in C# collections are 0 based and the first element is [0] and not [1].
Within the button1 click listener (if you don't have this hook go into the GUI builder view and double click on the button, it will automatically create and register the listener for you), add the following code;
textbox2.Text = textbox1.Text; // set tb2 = tb1
textbox1.Text = System.String.Empty; // clear tb1
Now, in your post you say store the data in a list, but you don't specify how the user is to input that data so it's hard to give you a specific answer. If the names are say separated by commas to get an array with all the names you could simply do;
string[] names = textbox1.Text.Split(',');
However, from your post it doesn't seem you want to store the data in a list at all. If you just want the input in textbox1 to be displayed in textbox2 upon clicking the input button then use use the first code snippet. If you go the second route, you'll have to convert the array back into a single string. This can be done easily with a for loop.
string result = System.String.Empty;
for (int i = 0; i < names.Length; i++)
result = result + names[i] + " ";
To make textbox2 display what's in textbox1 and display the number of names;
textbox2.Text = textbox1.Text; // set tb2 = tb1
string[] names = textbox1.Text.Split(','); // i use a comma but use whatever
// separates the names might just want ' ' for whitespace
textbox1.Text = System.String.Empty; // clear tb1
MessageBox.Show("You entered " + names.Count.ToString() + " names."); // show the names count
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ShowAllSaveNameAndCountApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> ourList=new List<string>();
string txt =" ";
private void buttonSave_Click(object sender, EventArgs e)
{
ourList.Add(textBoxEntryName.Text);
foreach (string s in ourList)
{
txt+= s+ "\n ";
}
textBoxEntryName.Clear();
ourList.Clear();
}
private void buttonShowAllName_Click(object sender, EventArgs e)
{
textBoxShowName.Text = txt;
}
}
}

Combo Box and Entity Framework

I'm writing a simple first app using Winforms, C#, VS2010, and Entity Framework. Basically, I have a rich DB I'm tapping, and I've already set up the framework, successfully enough to populate a DataGridView control with a subset of the Work Order table.
Now, I want to place a combo box on the form ("cbProjectID") whose value is ProjectID and DisplayValue is ProjectNbr. I only want to put projects in the combo box list that are related to WorkOrders, and only unique ProjectIDs within that set (a project may have dozens of work orders....)
I'm assuming I need to generate a list from EF, using LINQ. I'm pretty new at LINQ, and I'm not figuring it out...Here's my code so far...
using System;
using CPASEntityFramework;
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BrowseWorkOrders
{
public partial class BrowseWOs : Form
{
public BrowseWOs()
{
InitializeComponent();
}
private void BrowseWOs_Load(object sender, EventArgs e)
{
var context = new CPASEntities();
var query = context.tblWorkOrders.Where(c => c.ProjectID==8);
tblWorkOrderBindingSource.DataSource = query.ToList();
// Now, I want to load up the Combo Box with all the projects in the Work Order Table
}
}
}
I've been through the net trying to find a method I understand, but I'm failing. Perhaps someone can help me out. Here's my Datasource (I assume I should NOT use tblProject, but instead use the tblProject inside tblWorkOrder in order to get my subset...)
Any help and/or guidance would be appreciated.
Here's the code now...
namespace BrowseWorkOrders
{
public partial class BrowseWOs : Form
{
public BrowseWOs()
{
InitializeComponent();
}
private void BrowseWOs_Load(object sender, EventArgs e)
{
// Following loads up all Projects into the cbProjectID Combo Box
var context = new CPASEntities();
var PrID = context.qryProjectIDNbrDescs.ToList();
cbProjectID.DataSource = PrID;
cbProjectID.ValueMember = "ID";
cbProjectID.DisplayMember = "ProjectNbr";
}
private void cbProjectID_SelectedIndexChanged(object sender, EventArgs e)
{
var context = new CPASEntities();
var query = context.tblWorkOrders.Where(c => c.ProjectID == (int)cbProjectID.SelectedValue).ToList();
tblWorkOrderBindingSource.DataSource = query;
}
}
}
You need the tblProject on the top because the other is for a single WorkOrder only. However, you need to filter the list with those who have at least on WorkOrder:
var projects = context.tblProjects.Where(p => p.tblWorkOrders.Any()).ToArray();
cbProjectID.DataSource = projects;
cbProjectID.ValueMember = "ProjectID";
cbProjectID.DisplayMember = "ProjectNbr";

Getting SelectedValue from a DropDownList

I am trying to create a basic macro that encapsulates a form and the ability to email the details entered into it. It works fine for Textboxes, but for some reason the DropDownLists take the first value in the list of options. I've been working on this for hours and seem to've tried everything, so hopefully someone can suggest a solution. I am using Umbraco 4.0.3 and unfortunately upgrade is not an option. My reduced code is as follows:
CorpRefundForm.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="CorpRefundForm.ascx.cs" Inherits="umbracowebsitewizard_site.Usercontrols.CorpRefundForm" %>
<asp:DropDownList ID="frm_dropdown" runat="server" CssClass="linkselect" />
<br />
<button id="submitButton" runat="server" onserverclick="submitButton_Click">Submit</button>
CorpRefundForm.ascx.cs
using System;
using System.Net.Mail;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace umbracowebsitewizard_site.Usercontrols
{
public partial class CorpRefundForm : UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
frm_dropdown.Items.Add(new ListItem("Select one", ""));
frm_dropdown.Items.Add(new ListItem("One", "One"));
frm_dropdown.Items.Add(new ListItem("Two", "Two"));
frm_dropdown.Items.Add(new ListItem("Three", "Three"));
frm_dropdown.Items.Add(new ListItem("Four", "Four"));
}
}
public void submitButton_Click(object sender, EventArgs e)
{
SmtpClient mySMTPClient = new SmtpClient();
mySMTPClient.Send("[email removed]", "[email removed]", "Test", frm_dropdown.SelectedValue + frm_dropdown.Text + frm_dropdown.SelectedItem.Value + frm_dropdown.SelectedItem.Text);
}
}
}
CorpRefundForm.ascx.designer.cs:
using System.Web.UI.WebControls;
namespace umbracowebsitewizard_site.Usercontrols
{
public partial class CorpRefundForm
{
protected DropDownList frm_dropdown;
}
}
That probably happens since your first ListItem does not have a Value assigned. Try to assign a value, and see if it works.
frm_dropdown.Items.Add(new ListItem("Select one", "-1"));
Solved it! Turns out the jquery.linkselect-1.2.07.min.js library was doing something with the DropDownList that broke it. Took that out and it worked.

Categories