Scheduler in asp.net to fetch data from website - c#

I have written a code to fetch news from a website.
The code includes UI page in which i am inserting name of website (from which data to be fetched) & on button click event it fetches the news.
The code is as follows :
<form runat="server" style="margin-left:10px;">
<br /><br />
<asp:TextBox ID="txtSiteName" runat="server"></asp:TextBox> <asp:Button ID="btnSubmit" runat="server" Text="Get News" OnClick="btnSubmit_Click"/><br /><br /><br />
<h3>Here are the latest news</h3><br />
<div style="max-height: 350px; overflow: auto">
<asp:GridView ID="gvRss" runat="server" AutoGenerateColumns="false" ShowHeader="false" Width="90%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table width="100%" border="0" cellpadding="0" cellspacing="5">
<tr>
<td>
<asp:CheckBox ID="cbxAddNews" runat="server" />
</td>
<td>
<h3 style="color: #3E7CFF"><%#Eval("Title") %></h3>
</td>
<td width="200px">
<%#Eval("PublishDate") %>
</td>
</tr>
<tr>
<td colspan="2">
<hr />
<%#Eval("Description") %>
</td>
</tr>
<tr>
<td> </td>
<td align="right">
Read More...
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
The codebehind is as follows :
public class Feeds
{
public string Title { get; set; }
public string Link { get; set; }
public string PublishDate { get; set; }
public string Description { get; set; }
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
PopulateRssFeed();
}
private void PopulateRssFeed()
{
//string RssFeedUrl = "https://realty.economictimes.indiatimes.com/rss/topstories";
string RssFeedUrl = txtSiteName.Text;
List<Feeds> feeds = new List<Feeds>();
try
{
XDocument xDoc = new XDocument();
xDoc = XDocument.Load(RssFeedUrl);
var items = (from x in xDoc.Descendants("item")
select new
{
title = x.Element("title").Value,
link = x.Element("link").Value,
pubDate = x.Element("pubDate").Value,
description = x.Element("description").Value
});
if (items != null)
{
foreach (var i in items)
{
Feeds f = new Feeds
{
Title = i.title,
Link = i.link,
PublishDate = i.pubDate,
Description = i.description
};
feeds.Add(f);
}
}
gvRss.DataSource = feeds;
gvRss.DataBind();
}
catch (Exception ex)
{
throw;
}
}
what it does is it takes all the news from one particular website on button click event.
But i want to implement the same functionality using the scheduler! (want to eliminate button click event instead!)
Since i haven't worked on scheduler before, can anyone help me out or any suggestions as how to fetch the data (news) from multiple websites using scheduler & store it in database table instead of directly displaying them??

At client side use setInterval(expression, timeout);.
1) Create a WebMethod at you webpage.
[WebMethod]
public static void UpdateNews()
{
PopulateRssFeed();
}
2) Create a method at client side so that use Ajax to call that WebMethod.
var updateNews = function(){ $.ajax({ type: "POST", url:"YourWebpage.aspx/UpdateNews", contentType: "application/json; charset=utf-8" });}
3) Use SetInterval and call your client side ajax method
setInterval(updateNews(), 5000);//every 5 second

Related

How to get the hidden field value to be set within a table that uses pagination?

I have a repeater inside an html table that uses pagination. I want to be able to read the values of the hidden fields within the repeater in the code behind, but only the hidden field values of the table page being viewed on postback seem to be set when I'm in the code behind. How do I make it so the hidden field values are set for each repeater item regardless of the table page?
HTML:
<div id="divTableContainer" runat="server">
<table id="tblAssessmentExtracts" class="table table-striped table-sm table-hover ">
<thead>
<tr>
<th>Consumer</th>
<th>Assessment</th>
<th>Completed</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="rptAssessmentExtractQueue" runat="server" OnItemCommand="rptAssessmentExtractQueue_ItemCommand">
<ItemTemplate>
<tr class="assessment-extract-block">
<td><%# Eval("ConsumerName") %>
</td>
<td><%# Eval("SurveyName") %>
</td>
<td><%# Eval("CompletionDate") %></td>
<td class="buttoncell">
<asp:LinkButton ID="btnExportRecord" runat="server" Text="Export" CommandArgument='<%# Eval("Id") %>' />
<asp:HiddenField ID="hdAssessmentId" runat="server" Value='<%# Eval("Id") %>' />
<span class="selection"><asp:HiddenField ID="hdAssessmentSelected" runat="server" /></span>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
</table>
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
var table = $('#tblAssessmentExtracts').DataTable({
"pageLength": 25,
});
});
function selectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info") === false) {
$(element).addClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("true");
}
}
function deselectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info")) {
$(element).removeClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("");
}
}
$('.assessment-extract-block').click(function (e) {
var selectedField = $(this).find('.selection input[type="hidden"]');
if (selectedField.length > 0) {
if (selectedField.val() === "true") {
deselectBlock(0, $(this));
} else {
selectBlock(0, $(this));
}
}
});
</script>
C#:
private IEnumerable<long> getSelectedResponses()
{
List<long> assessmentIds = new List<long>();
foreach (RepeaterItem riAssessment in rptAssessmentExtractQueue.Items)
{
HiddenField hdAssessmentSelected = riAssessment.FindControl("hdAssessmentSelected") as HiddenField;
HiddenField hdAssessmentId = riAssessment.FindControl("hdAssessmentId") as HiddenField;
bool export = false;
if (bool.TryParse(hdAssessmentSelected.Value, out export) && export)
{
long assessmentId;
if (long.TryParse(hdAssessmentId.Value, out assessmentId) && assessmentId > 0)
{
assessmentIds.Add(assessmentId);
}
}
}
return assessmentIds;
}

How to get hidden field value in a html button in code behind in asp.net

I have created an HTML table with a repeater. In this table, I added a button column. It is an HTML button because ASP buttons not working inside of the tag. Therefore, I added an ASP hidden field inside of this HTML button to get selected row ID. I tried several ways to get the ID from the hidden field. I want to get selected row ID when the button click.
I have tried followings
I have tried this code but shows error in SendValueToSender(id); line. SendValueToSender is shown in red line using suggestions It generated method. But when I run the code and click the button shows error.
button_edit_ServerClick
protected void button_edit_ServerClick(object sender, EventArgs e)
{
try
{
var btn = (HtmlButton)sender;
var child = btn.FindControl("hidden");
string id = Convert.ToString(((HiddenField)child).Value);
SendValueToSender(id);
Response.Write("id" + id);
}
catch (Exception exception)
{
Response.Write(exception);
}
}
Generated method for SendValueToSender
private void SendValueToSender(string id)
{
throw new NotImplementedException();
}
Error-After add SendValueToSender method
System.NotImplementedException: The method or operation is not implemented. at EasyTravel.Manage.ManageNode.SendValueToSender(String id) in C:\Users\kularathna\source\repos\EasyTravel\EasyTravel\Manage\ManageNode.aspx.cs:line 241 at EasyTravel.Manage.ManageNode.button_edit_ServerClick(Object sender, EventArgs e) in C:\Users\kularathna\source\repos\EasyTravel\EasyTravel\Manage\ManageNode.aspx.cs:line 229
229 - SendValueToSender(id);
241 - throw new NotImplementedException();
PageLoad Method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Create Database Connection
SqlConnection con = new SqlConnection("Data Source= LAPTOP-J70EHC58 ; Initial Catalog= Bus_Management_System ; Integrated Security = True ; Connect Timeout = 30 ; ");
con.Open();
//Retrieve node details
string sqlst = "SELECT * FROM Node ";
SqlDataAdapter sqlData = new SqlDataAdapter(sqlst, con);
DataTable dt = new DataTable();
sqlData.Fill(dt);
rptrNode.DataSource = dt;
rptrNode.DataBind();
}
}
ManageNode.aspx
<table id="datatable-buttons" class="table table-striped table-bordered">
<thead>
<tr>
<th>Node_ID</th>
<th>Node_Name</th>
<th>Starting_Node</th>
<th>Ending_Node</th>
<th>Distance_Between_Nodes</th>
<th>Ticket_Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="rptrNode" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblNodeID" runat="server" Text='<%# Eval("Node_ID") %>'></asp:Label></td>
<td>
<asp:Label ID="lblNodeName" runat="server" Text='<%# Eval("Node_Name") %>'></asp:Label></td>
<td>
<asp:Label ID="lblStartingNode" runat="server" Text='<%# Eval("Starting_Node") %>'></asp:Label></td>
<td>
<asp:Label ID="lblEndingNode" runat="server" Text='<%# Eval("Ending_Node") %>'></asp:Label></td>
<td>
<asp:Label ID="lblDistance" runat="server" Text='<%# Eval("Distance_Between_Nodes") %>'></asp:Label></td>
<td>
<asp:Label ID="lblTicketPrice" runat="server" Text='<%# Eval("Ticket_Price") %>'></asp:Label></td>
<td>
<button runat="server" clientidmode="Static" class="btn btn-success" id="button_edit" onserverclick="button_edit_ServerClick">
<asp:HiddenField runat="server" ID="hidden" Value='<%#Eval("Node_ID") %>' />
Edit
</button>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
</table>
Button Column(It is in above ManageNode.aspx)
<td>
<button runat="server" clientidmode="Static" class="btn btn-success" id="button_edit" onserverclick="button_edit_ServerClick">
<asp:HiddenField runat="server" ID="hidden" Value='<%#Eval("Node_ID") %>' />
Edit
</button>
</td>
In Design part, Load Jquery Js and Page Js.
<td>
<button runat="server" clientidmode="Static" class="btn btn-success"
id="button_edit" onclick="func('<%#Eval("Node_ID") %>')">
Edit
</button>
</td>
In Page Js:
$(document).ready(function(){
//button Click Function.
function func(Id){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../ManageNode.aspx/SendValueToSender",
data: "{ID: '" + Id + "'}",
dataType: "json",
success: function (data) {
var tdata = jQuery.parseJSON(data.d);
},
error: function (result) {
alert('Data not found.');
}
});
}
});
In Server side.
[WebMethod]
public static void SendValueToSender(string ID)
{
//do your stuff.
}

Checking a query Result in ASP

In my database i have a Table called News. In News i have a column named Link. This link CAN be null. If the article is written by the editors the link will be null , if the editors just want to reference an article from another site then this Link will contain a value.
My task: Make a href to the article. Here i have a problem if my editor writes the article i put a href to that article . If it is not written(so the link is not null) i have to pur that href insteaf.
I have no idea how to do this, any tips ?
Code:
Display:
<asp:DropDownList ID="DropDownSelect" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="DropDownSelect_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="DesDate"> Descending Date </asp:ListItem>
<asp:ListItem Value="AsDate"> Ascending Date </asp:ListItem>
<asp:ListItem Value="AsAlp"> Ascending Alphabetical </asp:ListItem>
<asp:ListItem Value="DesAlp"> Descending Alphabetical </asp:ListItem>
</asp:DropDownList>
<asp:ListView ID="productList" runat="server"
DataKeyNames="NewsID" GroupItemCount="1"
ItemType="SiteStiri.Models.News" SelectMethod="GetProducts">
<EmptyDataTemplate>
<table >
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<EmptyItemTemplate>
<td/>
</EmptyItemTemplate>
<GroupTemplate>
<tr id="itemPlaceholderContainer" runat="server">
<td id="itemPlaceholder" runat="server"></td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td runat="server">
<table>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<img src="/Catalog/Images/Thumbs/<%#:Item.ImagePath%>"
width="100" height="75" style="border: solid" /></a>
</td>
</tr>
<tr>
<td>
<a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>">
<p style="color: black;">
<%#:Item.NewsTitle%>
</p>
</a>
</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</p>
</td>
</ItemTemplate>
<LayoutTemplate>
<table style="width:100%;">
<tbody>
<tr>
<td>
<table id="groupPlaceholderContainer" runat="server" style="width:100%">
<tr id="groupPlaceholder"></tr>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
<tr></tr>
</tbody>
</table>
</LayoutTemplate>
</asp:ListView>
</div>
Behind the page:
public IQueryable<News> GetProducts()
{
var _db = new SiteStiri.Models.NewsContext();
IQueryable<News> query = _db.News;
if ("DesDate".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderByDescending(u => u.ReleaseDate);
}
if ("AsDate".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderBy(u => u.ReleaseDate);
}
if ("AsAlp".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderBy(u => u.NewsTitle);
}
if ("DesApl".Equals(DropDownSelect.SelectedItem.Value))
{
query = query.OrderByDescending(u => u.NewsTitle);
}
return query;
}
public void DropDownSelect_SelectedIndexChanged(object sender, EventArgs e)
{
GetProducts();
productList.DataBind();
}
How can i put here <a href="NewsDetails.aspx?newsID=<%#:Item.NewsID%>"> either the page link to my site if Link IS null or the Link of the link IS NOT null?
To give a more detailed answer, set the Link column as NOT NULL and set the default value to be your URL. This was, if the user / news editor doesn't enter a value, your URL will be added to the field. The advantage of this is that you don't need any code to check for NULL etc.
Also, make sure the UI validates the URL that's added with regular expression, in case a rogue value is added.
If you want to alter it in code, you could try something like this...
public class News
{
public string Title { get; set; }
public string Url { get; set; }
public IQueryable<News> GetNews()
{
var news = new List<News> {new News {Title = "News1", Url = "NewsURL"},
new News {Title = "News1"}};
return news.AsQueryable();
}
}
You could then take out the list with no links and update them with your link...
var news = new News();
var initialNews = news.GetNews();
var newsWithLink = initialNews.Where(n => n.Url != null);
var newsWithOutLink = initialNews.Where(n => n.Url == null);
foreach (var newsItem in newsWithOutLink)
{
newsItem.Url = "MyURL";
}
var newsToDisplay = newsWithLink.Concat(newsWithOutLink);
I've just put that small example together to show how to update the links.

ASP.NET Paging next page button does not work properly

I'am trying to divide all of my products that i listed by using a repeater to pages. For example there are 3 pages. The paging looks well but when i click to next page button it is going to page 4 which is not exist actually. What can be the reason ? Implementation is below.
private void showShoes()
{
dataInThePage = new PagedDataSource()
{
DataSource = ap.getShoes(),
AllowPaging = true,
PageSize = 2,
CurrentPageIndex = pageNo
};
shoeRepeater.DataSource = dataInThePage;
shoeRepeater.DataBind();
pageAmount = dataInThePage.PageCount - 1;
//
pageInfoLabel.Text = "Page: " + (dataInThePage.CurrentPageIndex + 1) + "/" + dataInThePage.PageCount + " - Number of Shoes: " + (dataInThePage.DataSourceCount);
//
previousButton.Enabled = !dataInThePage.IsFirstPage;
nextButton.Enabled = !dataInThePage.IsLastPage;
}
private int pageNo
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set
{
ViewState["pageNumber"] = value;
}
}
private int pageAmount
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set { ViewState["pageNumber"] = value; }
}
public PagedDataSource dataInThePage { get; set; }
protected void previousButton_Click(object sender, EventArgs e)
{
pageNo -= 1;
showShoes();
}
protected void nextButton_Click(object sender, EventArgs e)
{
pageNo += 1;
showShoes();
}
Front-end:
<ajaxToolkit:TabPanel ID="TabPanel5" runat="server">
<HeaderTemplate>Show Shoes</HeaderTemplate>
<ContentTemplate runat="server">
<asp:Repeater ID="shoeRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table border="1" style="border-color:#ff9900; width:400px; font-weight:bold; font-family:'Oswald', Arial, sans-serif;">
<tr>
<td rowspan="6" style="width:150px; height:150px;">
<image src="shoeImages/<%#DataBinder.Eval(Container.DataItem,"ImagePath") %>"></image>
</td>
</tr>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem,"BrandName") %> - <%#DataBinder.Eval(Container.DataItem,"ModelName") %>
</td>
</tr>
<tr>
<td>
Price: $<%#DataBinder.Eval(Container.DataItem,"Price") %>
</td>
</tr>
<tr>
<td>
Size: <%#DataBinder.Eval(Container.DataItem,"Size") %>
</td>
</tr>
<tr>
<td>
Color: <%#DataBinder.Eval(Container.DataItem,"PrimaryColor") %> - <%#DataBinder.Eval(Container.DataItem,"SecondaryColor") %>
</td>
</tr>
<tr>
<td>
Quantity: <%#DataBinder.Eval(Container.DataItem,"Quantity") %>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
<div style="width:600px; height:20px;">
<div style="width:50px; height:100%; float:left">
<asp:Button ID="previousButton" runat="server" OnClick="previousButton_Click" Text="<<" Width="50px"/>
</div>
<div style="width:500px; height:100%; float:left; text-align:center">
<asp:Label ID="pageInfoLabel" runat="server" Text=" "></asp:Label>
</div>
<div style="width:50px; height:100%; float:left">
<asp:Button ID="nextButton" runat="server" OnClick="nextButton_Click" Text=">>" Width="50px"/>
</div>
</div>
</ContentTemplate>
</ajaxToolkit:TabPanel>
I had to guess on a number of things, but I was able to take the posted code and get it to work in VS 2010 using an ASP.NET 4.0 project.
Here are the things I did to get it working:
Add a Shoe POCO with the 8 public properties referenced in the .aspx page (not shown)
Add a FakeShoeRepository class that has a private static List<Shoe> with 9 shoes (not shown)
Add a static method called getShoes() that returns a reference to the private member variable of the repository (not shown)
Set the dataInThePage.DataSource = FakeShoeRepository.getShoes() (not shown)
Add a Page_Load() event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pageNo = 0;
showShoes();
}
}
Remove the pageAmount property
Remove the one place pageAmount was being set in the showShoes() method (this was effectively setting ViewState["pageNumber"] = PageCount - 1)
The last two items are where the actual problem was in the provided code.

How To use a html button to fire a c# function

I used a asp:button to bind the data from a textbox into a grid, but my problem was getting the page to stop refreshing. So I changed the asp:button to html button, because it was server side causing the page to refresh. Now I dont know how to use the same c# code to bind the data using html button.
Here's an example of my c# code:
//Site Class
class Sites
{
//Strings and variables are created based off text box Id to make matter easier to read
public string SiteName { get; set; }
public string Slick { get; set; }
public string UserID { get; set; }
}
//Created a new list based on class.
//Items are added based on whats in the textboxes
//and events are fired to gridview by the click of the class button
protected void SiteDetails_Click(object sender, EventArgs e)
{
List<Sites> list;
if (Session["list"] == null)
{
list = new List<Sites>();
}
else
{
list = (List<Sites>)Session["list"];
}
list.Add(new Sites() { SiteName = Sname.Text, Slick = Slick.Text, UserID = User_ID.Text });
Session["list"] = list;
SiteGrid.DataSource = list;
SiteGrid.DataBind();
}
And This is my Html aspx page:
Site Details
SiteName:
<td style="width: 102px; height: 8px;">Slic:</td>
<td style="width: 153px; height: 8px;">
<asp:TextBox ID="Slick" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 129px; margin-left: 40px; height: 23px;">User ID:</td>
<td style="width: 152px; height: 23px;">
<asp:TextBox ID="User_ID" runat="server" style="font-weight: bold"></asp:TextBox>
</td>
<td style="width: 102px; height: 23px;">
Password:</td>
<td style="width: 153px; height: 23px;">
<asp:TextBox ID="Pass" runat="server" TextMode="Password" ></asp:TextBox>
</td>
</tr>
<%-- //Site Button--%>
<tr>
<td></td>
<td>
<button ID="SiteDetails" OnClick="SiteDetails_Click()">AddSites</button>
</td>
</tr>
</table>
<%-- //Site GridView--%>
<asp:GridView ID="SiteGrid" class="table-bordered table-hover tableGridLines="None">
</asp:GridView>

Categories

Resources