Fullcalendar/Fetching JSON feed(Edited) - c#

I have a problem with the events in my fullCalendar object not showing when using ajax to fetch the data from my JSON feed. I believe the JSON format is proper though since the output from JSON.aspx is:
[{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}]
I used Firebug and it seems like the JSON feed is not getting fetched properly?
When I add the upper JSON-feed directly in the events it displays properly.
(Edit) The JSON response is now working, although the events are still not displayed in fullcalendar.
JSON.aspx
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get events from db and add to list.
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
Response.Write(json);
Response.End();
}
}
And my Site.master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' />
<script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script>
<script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: 'JSON.aspx'
})
});
</script>
I've been scanning related questions for days but none of them seems to fix mine...

Why are your calls so complicated? Try this for now:
$('#fullcal').fullCalendar({
events: 'JSON.aspx',
eventClick: function (calEvent, jsEvent, view) {
alert('a day has been clicked!');
}
});

Related

Web Scraping Java Sites with HtmlAgilityPack

Let me start out by saying that I am no pro at web scraping. I can do the basics on most platforms, but that's about it.
I am trying to create the foundation for a web application that can helps users reinforce their language learning by generating additional data, metrics, as well as create new tools for self-testing. The Duolingo website is not offering up any sort of API so my next thought for now is just to scrape https://www.duome.eu/. I wrote a quick little scraper but didn't realize that the site was java. In the following example, it is my wish to collect all of the words from the Words tab that contain anchors:
using System;
using HtmlAgilityPack;
using System.Net.Http;
using System.Text.RegularExpressions;
namespace DuolingoUpdate
{
class Program
{
static void Main(string[] args)
{
string userName = "Podus";
UpdateDuolingoUser(userName);
Console.ReadLine();
}
private static async void UpdateDuolingoUser(string userName)
{
string url = "https://www.duome.eu/" + userName + "/progress/";
// Create the http client connection
HttpClient httpClient = new HttpClient();
var html = await httpClient.GetStringAsync(url);
// Store the html client data in an object
HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//var words = htmlDocument.DocumentNode.Descendants("div")
// .Where(node => node.GetAttributeValue("id", "")
// .Equals("words")).ToList();
//var wordList = words[0].Descendants("a")
// .Where(node => node.GetAttributeValue("class", "")
// .Contains("wA")).ToList();
Console.WriteLine(html);
}
}
}
The html object of the above code contains:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="google" value="notranslate">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Duolingo · Podus # duome.eu</title>
<link rel="stylesheet" href="/style.css?1548418871" />
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if("".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
//localStorage.tz = visitortimezone;
//timezone = Date.parse(localStorage.tz);
//timezone = localStorage.tz;
//console.log(timezone);
$.ajax({
type: "GET",
url: "/tz.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
</head>
<body>
<noscript>Click here to adjsut XP charts to your local timezone. </noscript>
<!-- Yandex.Metrika counter --> <script type="text/javascript" > (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter47765476 = new Ya.Metrika({ id:47765476, clickmap:true, trackLinks:true, accurateTrackBounce:true }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks"); </script> <noscript><div><img src="https://mc.yandex.ru/watch/47765476" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter -->
</body>
</html>
But if you go to the actual url https://www.duome.eu/Podus/progress/, the site contains a ton of script. So upon inspection the first problem is that I am not getting the html that I see in the browser. The second problem is that if you view source, its nothing like what is in inspect and I don't see anything in source that would lead me to isolate the data from div id="words".
Given my lackluster knowledge of java built web pages, how do I do this, or is it even possible?
You can access dualingo profile data in JSON format via https://www.duolingo.com/users/<username>
eg. https://www.duolingo.com/users/Podus
This should be much easier than trying to scrape the duome profile page manually.

How to call C# method in javascript by using GeckoFX as the wrapper of XULRunner

I am using GeckoFX16 and xulrunner-16.0.2.en-US.win32 in my project.
The thing is, I want to call a C# method in javascript.
I am curious, is there a way to do this?
Just like below:
C# part:
private GeckoWebBrowser weBrowser;
public browser()
{
InitializeComponent();
Gecko.Xpcom.Initialize("xulrunner");
weBrowser = new GeckoWebBrowser();
weBrowser.Parent = this;
weBrowser.Dock = DockStyle.Fill;
weBrowser.Navigate("test.html");
}
public string loadData(){
//load data from local file.
return str;
}
javascript part:
<script type='text/javascript'>
var data = window.loadData();
alert(data);
</script>
I am new in this area, I’ll appreciate if it is possible!
Important update:
Currently code with event.initMessageEvent does not work because this construction has been replaced on
var event = new MessageEvent('yourEventName', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
You can use a MessageEvent to invoke code in c#, but as far as I know you can't then return a string like you're wanting to. One of the unit tests demonstrates how to invoke the c# code:
[Test]
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
I know it's awkward, but you could then use a c#-->javascript call to get data back to javascript-land. See This Question for how to do that. So your javascript would first send this message to c# land, then it would get a callback with the string value you need.
Hope that helps.
You can add message event listener to your web browser and call your method like this:
private void load()
{
browser.AddMessageEventListener("myFunction", ((string s) => this.showMessage(s)));
browser.LoadHtml
(
#"<!DOCTYPE html>
<html><head>
<meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"">
<script type=""text/javascript"">
function fireEvent(name, data)
{
event = document.createEvent('MessageEvent');
event.initMessageEvent(name, false, false, data, null, null, null, null);
document.dispatchEvent(event);
}
</script>
</head>
<body>
<input type=""button"" onclick=""fireEvent('myFunction', 'some data');"" value=""SHOW DATA"" />
</body></html>"
);
}
...
private void showMessage(string s)
{
MessageBox.Show(s);
}
Now you can add more msg events to your msg listener (if you need to) and fire them all in the same way.

How to create auto complete in jquery with asp.net

I'm using this following code for auto complete feature ,
but I need to fetch values from database using sql server 2008 and C# , asp.net.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
</body>
</html>
How can i fetch that array list values from my database using (EF4 and asp.net)
The first step is to create a C# ASP.Net page which produces a JSON result that the autocomplete plugin can parse. According to the documentation you can use the two following formats:
Array: An array can be used for local data.
There are two supported formats: An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
http://api.jqueryui.com/autocomplete/#option-source
Alternatively you can use a function to parse out whatever format you need but it sounds like the simplest solution will fulfill your needs.
I'm going to assume you're using ASP.Net forms which isn't really tuned for this kind of thing but you can still make it work with some tweaking. Let's create a page in your web application root called SearchResults.aspx.
The first thing to do is to clear out everything from your ASPX file except the line:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SearchResults.aspx.cs" Inherits="ASP.Net_Forms.SearchResults" %>
Then you're free to change the code behind to output whatever format you like. In this case we'll be using JSON in a structure that Autocomplete can understand natively. We'll also need to set the response type.
public partial class SearchResults : System.Web.UI.Page
{
private class SomeSearchableClass
{
public int ID { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
// The autocomplete plugin defaults to using the querystring
// parameter "term". This can be confirmed by stepping through
// the following line of code and viewing the raw querystring.
List<SomeSearchableClass> Results = SomeSearchSource(Request.QueryString["term"]);
Response.ContentType = "application/json;charset=UTF-8";
// Now we need to project our results in a structure that
// the plugin can understand.
var output = (from r in Results
select new { label = r.Name, value = r.ID }).ToList();
// Then we need to convert it to a JSON string
JavaScriptSerializer Serializer = new JavaScriptSerializer();
string JSON = Serializer.Serialize(output);
// And finally write the result to the client.
Response.Write(JSON);
}
List<SomeSearchableClass> SomeSearchSource(string searchParameter)
{
// This is where you'd put your EF code to gather your search
// results. I'm just hard coding these examples as a demonstration.
List<SomeSearchableClass> ret = new List<SomeSearchableClass>();
ret.Add(new SomeSearchableClass() { ID = 1, Name = "Watership Down" });
ret.Add(new SomeSearchableClass() { ID = 2, Name = "Animal Farm" });
ret.Add(new SomeSearchableClass() { ID = 3, Name = "The Plague Dogs" });
ret = ret.Where(x => x.Name.Contains(searchParameter)).ToList();
return ret;
}
}
And finally just change your jQuery to use the correct source:
$( "#tags" ).autocomplete({ source: "/SearchResults.aspx" });
See this below sample from jQueryUI Autocomplete Example
Hope you can do by yourself!.
All you need to do is call some page or handler and prepare JSON data.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "yourpage.aspx",
dataType: "jsonp",
data: {
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});

SignalR site is not staying in sync when page is open in more than one tab

I'm working through a SignalR demo that displays database info in a list when a button is hit.
My Hub has 2 functions: One to remove DB objects from a list, and one to re-add DB objects to that list.
These functions are performed in my View and perform great when I only have the page open once. But if I open the page in another tab (can be the same browser or a different one), the pages do not stay in sync.
Meaning, when one page's button is hit, the other page is not displaying the data correctly.
Often times one page will do fine, while the other will perform the remove but not the add! It's mind-boggling. They should just be reflections of each other from my understanding.
Has anyone else run into something similar?
Thanks in advance for any help!
Here's my Hub :
[HubName("hubtest")]
public class HubTest : Hub
{
CmsContext db = new CmsContext();
public void showdata()
{
var f = from x in db.Data
select x;
Clients.remove();
Clients.add(f);
}
}
And here's the javascript in my View for the functions:
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var hubtest = $.connection.hubtest;
hubtest.remove = function () {
//clear list of any prior values
var list = document.getElementById('dataList');
while (list.hasChildNodes()) {
list.removeChild(list.childNodes[0])
}
};
hubtest.add = function (data) {
//populate with updated values
for (var i = 0; i < data.length; i++) {
var element = data[i];
$('#dataList').append('<li>' + element.Question + '</li>');
}
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
</script>
<input type="button" id="broadcast" value="broadcast" />
<ul id="dataList">
</ul>
Try this instead:
<script type="text/javascript">
$(function () {
var hubtest = $.connection.hubtest;
hubtest.add = function (data) {
//clear the values first.
var list = $('#dataList');
list.empty();
//populate with new values
for (var i = 0; i < data.length; i++) {
var element = data[i];
list.append('<li>' + element.Question + '</li>');
}
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
</script>
And this:
[HubName("hubtest")]
public class HubTest : Hub
{
TestDatabaseEntities db = new TestDatabaseEntities();
public void showdata()
{
var f = from x in db.FAQs
select x;
Clients.add(f);
}
}
First of all thanks for your replies. I really appreciate your feedback!
I eventually got it to where my pages are staying in sync when open in multiple tabs by altering how my data is sent to the View.
Where I was performing the for loop in my Javascript to display each piece of data, now I am doing that in my Hub like so:
[HubName("hubtest")]
public class HubTest : Hub
{
CmsContext db = new CmsContext();
public void showdata()
{
Clients.clearlist();
var faqs = from x in db.Faqs
select x;
foreach (Faq faq in faqs)
{
Clients.add(faq.Question.ToString());
}
}
}
Then my Javascript is just appending that FAQ question to the list:
$(function () {
var hubtest = $.connection.hubtest;
hubtest.clearlist = function () {
var list = $('#datalist');
list.empty();
};
hubtest.add = function (data) {
$('#datalist').append('<li>' + data + '</li>');
};
$("#broadcast").click(function () {
hubtest.showdata();
});
// Start the connection
$.connection.hub.start();
});
Sending just a simple string of my data to be printed individually seems to allow my page to stay in sync.
Before the data I was sending was a list of DB objects and my Javascript was looping through each and adding that object's Question column to the list. Not sure why this was such an issue - especially since it would work on one open tab but not all open tabs - but that simple change fixed my site sync issues.
Thanks again!

assign C# string of array or string[] to javascript array

I have a js code in which an array works well when its like
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C"
];
I then made an array string in my code behind or .cs like on class level
public static string[] test={"animal","lovely"};
I then changed js array to this
var availableTags = "<%=test%>"; // also tried without quotes
Now I m not having the results as was having with previous js array
Editing with complete code,the jquery I taken from http://jqueryui.com/demos/autocomplete/#multiple
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.Script.Serialization;
public partial class onecol : System.Web.UI.Page
{
JavaScriptSerializer serializer;
public static string test = "['animal','lovely']";
public static string check;
protected void Page_Load(object sender, EventArgs e)
{
serializer = new JavaScriptSerializer();
//serializer
this.detail.ToolsFile = "BasicTools.xml";
test = returnTitle();
}
}
and the script with html is
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="Jscript.js"></script>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.17.custom.css"></script>
<link href="~/jquery-ui-1.8.17.custom.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
$(function () {
var availableTags = <%=test%>;
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="demo" >
<div class="ui-widget">
<label for="tags">Tag programming languages: </label>
<input id="Text1" class="#tags" size="50" />
</div>
</div>
actually its a auto complete functionality to give tags ,the auto complete suggestions for tagging I want to get from C# code ,I took Jquery source from jqueryui.com/demos/autocomplete/#multiple and then I tried to give it C# string from .cs file , I explained it with code on edited version , with C# code behind it works exactly as its in the link
You need to serialize the C# string array into a javascript array.
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Usually I create a simple static class as a wrapper.
public static class JavaScript
{
public static string Serialize(object o)
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(o);
}
}
Then you can use that class to serialize the item you need to
//C# Array(Member of asp page)
protected string[] Values = { "Sweet", "Awesome", "Cool" };
<script type="text/javascript">
var testArray = <%=JavaScript.Serialize(this.Values) %>
</script>
var availableTags = ['<%=String.join("','",test)%>'];
It would be something like this...
var availableTags = ["<%= string.Join("\", \"", test) %>"];
or
var availableTags = ['<%= string.Join("', '", test) %>'];
The first one would render as
var availableTags = ["Sweet", "Awesome", "Cool"];
and the second one would render as
var availableTags = ['Sweet', 'Awesome', 'Cool'];
both of which are fine for autocomplete.
test property should be a string property and it should render the string which will be parsed by Js engine as an array. Try this.
Code behind property
public static string test= "['animal','usman lovely']";
JS
var availableTags = <%=test%>;//No quotes
only use indexes to get your test string array
i have tried by giving indexes like
var availableTags = "<%=test[0]%>"; // animal
var availableTags = "<%=test[1]%>"; // lovely
If you're doing an online coding challenge, the browser-based IDE might not let you use string.join, like with my job, which has us use iMocha.
Instead of that, I just created a StringBuilder object (from System.Text) and iterated over the array, appending each integer and a blank space, then converting the result to a string. Something like this:
var array = new int[] {1, 3, 5, 7, 9};
var str = new StringBuilder();
foreach (int i in array)
{
str.Append(i);
str.Append(" ");
}
var result = str.ToString();

Categories

Resources