html agility pack function scraping - c#

I have a problem as I am new in html agility pack. What I'm looking for is function from the page. The code below. I want to just take out a function named getDirections then replace start koniec and then repaste it into webpage again, then display it in my app. One question again, is there need to create two html files? Firt static, which never changes, just to load code, and second to display it? As I have to always replace start koniec? Thanks for help and advice!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Find directions</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var end;
var start;
function getMap()
{
map = new Microsoft.Maps.Map(document.getElementById('myMap'), {credentials: ''});
alert('');
getDirections();
}
function getDirections()
{
start= 'start'; end= 'koniec';
map.getCredentials(callRouteService);
}
function callRouteService(credentials)
{
var routeRequest = 'http://dev.virtualearth.net/REST/v1/Routes?wp.0=' + start + '&wp.1=' + end + '&routePathOutput=Points&output=json&jsonp=routeCallback&key=' + credentials;
var mapscript = document.createElement('script');
mapscript.type = 'text/javascript';
mapscript.src = routeRequest;
document.getElementById('myMap').appendChild(mapscript);
}
function routeCallback(result)
{
var output = document.getElementById("output");
if (output)
{
while (output.hasChildNodes()) {
output.removeChild(output.lastChild);
}
var resultsHeader = document.createElement("h5");
var resultsList = document.createElement("ol");
output.appendChild(resultsHeader);
output.appendChild(resultsList);
}
if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0)
{
//resultsHeader.innerHTML = "Bing Maps REST Route API <br/> Route from " + result.resourceSets[0].resources[0].routeLegs[0].startLocation.name + " to " + result.resourceSets[0].resources[0].routeLegs[0].endLocation.name;
var resultsListItem = null;
//for (var i = 0; i < result.resourceSets[0].resources[0].routeLegs[0].itineraryItems.length; ++i)
//{
//resultsListItem = document.createElement("li");
//resultsList.appendChild(resultsListItem);
//resultStr = result.resourceSets[0].resources[0].routeLegs[0].itineraryItems[i].instruction.text;
//resultsListItem.innerHTML = resultStr;
//}
var bbox = result.resourceSets[0].resources[0].bbox;
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
map.setView({ bounds: viewBoundaries});
var routeline = result.resourceSets[0].resources[0].routePath.line; var routepoints = new Array();
for (var i = 0; i < routeline.coordinates.length; i++)
{
routepoints[i]=new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
}
var routeshape = new Microsoft.Maps.Polyline(routepoints, {strokeColor:new Microsoft.Maps.Color(200,0,0,200)});
var startPushpinOptions = {anchor: new Microsoft.Maps.Point(10, 32) };
var startPin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[0][0], routeline.coordinates[0][1]), startPushpinOptions);
var endPushpinOptions = {anchor: new Microsoft.Maps.Point(10, 32)};
var endPin= new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[routeline.coordinates.length-1][0], routeline.coordinates[routeline.coordinates.length-1][1]), endPushpinOptions);
map.entities.push(startPin);
map.entities.push(endPin);
map.entities.push(routeshape);
}
else
{
if (typeof(result.errorDetails) != 'undefined')
{
resultsHeader.innerHTML = result.errorDetails[0];
}
alert("No Route found");
}
}
</script>
</head>
<body onload="getMap();">
<div id='myMap' style="position:relative; width:400px; height:400px;"></div>
<div id="output"></div>
</body>
</html>

Related

Block keyboard input chatbot

I am building a ChatBot using C# and Visual Studio. What I want to do is after some queries to the ChatBot, the user can't use the keyboard anymore, I've seen some websites that explain how to do it but I didn't understand well, so if someone can help me.
The idea is to put in the else block something that prevent the user to write to the ChatBot, so if he want to write the things that he type won't appear on the screen. Here is my code :
private int NombreDeMessages;
protected override async Task MessageReceived(IDialogContext context, IAwaitable<IMessageActivity> item)
{
var message = await item;
NombreDeMessages += 1;
string code = EndOfConversationCodes.CompletedSuccessfully;
CancellationToken cancellationToken = default(CancellationToken);
if (message.Text != null && NombreDeMessages < 3)
{
await base.MessageReceived(context, item);
}
else if (message.Text != null && NombreDeMessages == 3)
{
AdaptiveCard card = new AdaptiveCard();
card.Body.Add(new TextBlock()
{
Text = "STOP FLOODING",
Weight = TextWeight.Bolder,
IsSubtle = true,
Wrap = true,
Size = TextSize.Large
});
card.Body.Add(new TextBlock()
{
Text = "You have reach the limit of queries",
IsSubtle = false,
Wrap = true,
Size = TextSize.Normal
});
card.Body.Add(new Image()
{
Url = "http://images.roadtrafficsigns.com/img/dp/lg/traffic-stop-sign.png",
HorizontalAlignment = AdaptiveCards.HorizontalAlignment.Center,
Size = ImageSize.Stretch
});
Attachment attachment = new Attachment()
{
ContentType = AdaptiveCard.ContentType,
Content = card
};
var flood = context.MakeMessage();
flood.Attachments.Add(attachment);
await context.PostAsync(flood);
}
else
{
var reply = context.MakeMessage();
reply.Type = ActivityTypes.EndOfConversation;
reply.AsEndOfConversationActivity().Code = code;
await context.PostAsync(reply, cancellationToken);
}
}
Yes I want to block input on the web application, I don't have a C# application. My HTML code is this one:
<!DOCTYPE html>
<html>
<body style="width:100%;height:100%;">
<script>
(function () {
var div = document.createElement("div");
document.getElementsByTagName('body')[0].appendChild(div);
div.outerHTML = "<div id='botDiv' style='height: 38px; position: fixed; bottom: 0; z-index: 1000; background-color: #fff'><div id='botTitleBar' style='height: 38px; width: 400px; position:fixed; cursor: pointer;'></div><iframe width='400' height='600' src='https://webchat.botframework.com/embed/supportbotv2?s=4mHD9MekOvU.cwA.8ZU.Pn31pCpv8kyq7UQCr3y4bM-99W4eHxUt-LlhBnCp9JY'></iframe></div>";
document.querySelector('body').addEventListener('click', function (e) {
e.target.matches = e.target.matches || e.target.msMatchesSelector;
if (e.target.matches('#botTitleBar')) {
var botDiv = document.querySelector('#botDiv');
botDiv.style.height = botDiv.style.height == '600px' ? '38px' : '600px';
};
});
}());</script>
</body>
</html>
What's wrong with disabling the control where keyboard input is taken? For example:
this.textBox1.enabled = false

Add code in page base to header C#

I have the following code in my MasterPageBase.cs file:
protected override void OnLoad(EventArgs e)
{
string url = Request.Path;
var page = _ContentPageRepository.GetContentPageByUrl(url, ConfigurationManager.GetSiteID());
if (page != null)
{
PageBase.SetTitle(page.Title);
PageBase.SetDescription(page.Description);
PageBase.SetKeywords(page.Keywords);
}
else
{
this.ProcessSiteMap();
}
this.AddGACode();
base.OnLoad(e);
}
I need this.AddGACode(); to get added to the head section of the page, but when I view the source of the page as I am running the solution, I see that this is adding it to the body section of the page.
I have tried Page.Header.Controls.Add(AddGACode()); and get the following errors:
The best overloaded method match has some invalid arguments and cannot convert from 'void' to 'System.Web.UI.Control'
What can I do to get this code added to the head? TIA
EDIT: Request to see the AddGACode method:
private void AddGACode()
{
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
if (!ConfigurationManager.EnableUniversalGATracking)
{
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\">");
csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
}
else
{
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
}
}
}
EDIT:
This code is in the AddGACode method. There is still this.AddGACode(); in the OnLoad of the page that seems to duplicate the code with this edit, but both codes will disappear if I delete this.AddGACode(); from OnLoad
ClientScriptManager cs = Page.ClientScript;
StringBuilder csText = new StringBuilder();
csText.Append("<!-- Universal GA Code --><script type=\"text/javascript\">");
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
csText.Append("</script>");
cs.RegisterClientScriptBlock(GetType(), "GACode", csText.ToString());
LiteralControl lc = new LiteralControl(csText.ToString());
Page.Header.Controls.Add(lc);
This adds the script into the head tag:
LiteralControl lt = new LiteralControl("<script type='text/javascript'>alert('test');</script>");
Header.Controls.Add(lt);
UPDATE
LiteralControl lt = new LiteralControl(AddGACode());
Header.Controls.Add(lt);
...
private string AddGACode()
{
var result = string.Empty;
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\">");
if (!ConfigurationManager.EnableUniversalGATracking)
{
csText.Append(String.Format("var _gaq = _gaq || []; _gaq.push(['_setAccount', '{0}']); ", gaCode));
csText.Append("_gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();");
}
else
{
csText.Append(String.Concat("(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', '", gaCode, " ', 'auto'); ga('send', 'pageview');"));
}
csText.Append("</script>");
result = csText.ToString();
}
return result;
}
I'd keep your markup, in this instance your ga scripts, on mastpage itself. In the head tag add two literals, gaGaq and gaUniversal an then use you logic to contol the visibility of them.
<head runat="server"><script type="text\javascript">
<asp:Literal id="gaGaq" runat="server">
<!-- Put you gaq code here-->
<!-- Keep {0} as a place holder for gaqCode -->
</script>
</asp:Literal>
<asp:Literal id="gaUniveral" runat="server">
<script type="text\javascrtip">
<!-- Put you universal code here-->
<!-- Keep {0} as a place holder for gaqCode -->
</script>
</asp:Literal>
</head>
C#
private void AddGACode()
{
var gaCode = SiteManager.GetSite().GoogleAnalyticsCode;
if (!String.IsNullOrEmpty(gaCode) && Response.StatusCode == 200)
{
if(ConfigurationManager.EnableUniversalGATracking)
{
//Set gaCode
gaUniversal.Text = string.Fomat(gaUniveral.Text, gaCode);
}
else
{
//Set gaCode
gaGaq.Text = string.Format(ga.Text, gaCode);
}
gaUniversal.Visible = ConfigurationManager.EnableUniversalGATracking;
gaGaq.Visible = !ConfigurationManager.EnableUniversalGATracking;
}
else
{
//Hide Both literals if no gaCode
gaUniversal.Visible = gaGaq.Visible = false;
}
}
You could also look at putting all this into a custom control. If you're interested in taking that route I wrote a blog article on exactly that for the gaq style google analytics so I could drop it onto my many asp.net websites. The code in that article owuld need to be modified to suite your needs but should be enough to get you stared.

Javascript submit form not getting submitted in Firefox and IE

I am submitting a form in javascript to a controller in C# MVC it submits easily in chrome but not in Firefox and IE
//CSHTML CODE
<th class="gen2">
<button type="button" id="buttonClass">Generate</button>
</th>
<td class="money"><input type="checkbox" class="chk" name="checkboxID" value=#item.WithdrawalID></td>
//Javascript code
$("#buttonClass").click(function () {
getValueUsingClass();
});
function getValueUsingClass() {
var data = "";
var submitForm = document.createElement('form');
//Creating a form and giving the attributes
submitForm.name = "formSubmit";
submitForm.id = "formSubmit";
submitForm.method = "post";
submitForm.action = "generatebankfile";
var chkArray = \[\];
alert(chkArray);
$(".chk:checked").each(function () {
chkArray.push($(this).val());
});
for (var i = 0; i < chkArray.length; i++) {
data = data + chkArray\[i\];
if (i != chkArray.length - 1) {
data = data + ',';
}
}
var element = document.createElement("input");
element.name = "checkboxID";
element.value = data;
submitForm.appendChild(element);
if (chkArray.length > 0) {
submitForm.submit();
}
else {
alert("Please select at least one of the checkbox");
}
}
append form to the body
document.getElementsByTagName('body')[0].appendChild(submitForm);

how to get email address via html Agility Pack 2

How can I catch an email address from a website ?
I try to catch a email from a website that seems its protected by some JavaScript...
Here is the HTML code :
<p class="email">
<a href="mailto:info#aryanaz.ir" class="email">
info#aryanaz.ir
<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script></a>
</p>
I use this code that catch protected value and it doesn't work :
HtmlAgilityPack.HtmlDocument doc = hw.Load(url);
var Email = from HtmlNode n in doc.DocumentNode.SelectNodes("//a[contains(#href, 'mailto:')]")
select n;
foreach (HtmlNode node in Email )
{
string email = node.InnerHtml.Trim();
if (node.InnerHtml.Trim() != "")
{
ClassBase.ENonQuery("addfullvalueemail ", System.Data.CommandType.StoredProcedure, new SqlParameter[]
{
new SqlParameter("#Email ",email ),
});
}
}

Check if adobe reader is installed on client machine

Currently I am working on a web page which will tell user about certain configurations on client machine. Out of this there is also requirement of detecting if Adobe Reader is installed on client machine or not. I am using ASP.NET/C#.
I have looked the following url for the answer
"Check Adobe Reader is installed (C#)?" but the code look into the server registry entires where IIS is installed and not the client machine where browser is running.
Is it possible to detect if Adobe reader is installed on client machine and not the server which is hosting the website?
pls, check the script below, it worked fine for me in IE, FireFox and Chrome
<html>
<body>
<script type="text/javascript">
var found = false;
var info = '';
try
{
acrobat4 = new ActiveXObject('PDF.PdfCtrl.1');
if (acrobat4)
{
found = true;
info = 'v. 4.0';
}
}
catch (e)
{
//???
}
if (!found)
{
try
{
acrobat7 = new ActiveXObject('AcroPDF.PDF.1');
if (acrobat7)
{
found = true;
info = 'v. 7+';
}
}
catch (e)
{
//???
}
if (!found && navigator.plugins && navigator.plugins.length>0)
{
for (var i = 0; i<navigator.plugins.length; i++)
{
if (navigator.plugins[i].name.indexOf('Adobe Acrobat') > -1)
{
found = true;
info = navigator.plugins[i].description + ' (' + navigator.plugins[i].filename + ')';
break;
}
}
}
}
document.write("Acrobat Reader Installed : " + found);
document.write("<br />");
if (found) document.write("Info : " + info);
</script>
</body>
</html>
hope this helps, regards
I used this script and called it on ready function :
Note: i used the alerts here just to know how to use it.
<script type="text/javascript">
$(document).ready(function () {
alert(getAcrobatInfo().browser);
alert(getAcrobatInfo().acrobat === "installed");
alert(getAcrobatInfo().acrobatVersion);
});
var getAcrobatInfo = function () {
var getBrowserName = function () {
return '<%=Session["browser"].ToString()%>';
};
var getActiveXObject = function (name) {
try { return new ActiveXObject(name); } catch (e) { }
};
var getNavigatorPlugin = function (name) {
for (key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name == name) return plugin;
}
};
var getPDFPlugin = function () {
return this.plugin = this.plugin || function () {
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
//
// load the activeX control
// AcroPDF.PDF is used by version 7 and later
// PDF.PdfCtrl is used by version 6 and earlier
return getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
}
else {
return getNavigatorPlugin('Adobe Acrobat') || getNavigatorPlugin('Chrome PDF Viewer') || getNavigatorPlugin('WebKit built-in PDF') || getWebKitPlugin();
}
}();
};
var getWebKitPlugin = function () {
for (var key in navigator.plugins) {
var plugin = navigator.plugins[key];
if (plugin.name && plugin.name.substring(0, 6) == "WebKit" && (plugin.name.indexOf("pdf") != -1 || plugin.name.indexOf("PDF") != -1)) return plugin;
}
};
var isAcrobatInstalled = function () {
return !!getPDFPlugin();
};
var getAcrobatVersion = function () {
try {
var plugin = getPDFPlugin();
if (getBrowserName() == 'ie' || getBrowserName().toLocaleLowerCase() == 'internetexplorer') {
var versions = plugin.GetVersions().split(',');
var latest = versions[0].split('=');
return parseFloat(latest[1]);
}
if (plugin.version) return parseInt(plugin.version);
return plugin.name
}
catch (e) {
return null;
}
}
// The returned object
return {
browser: getBrowserName(),
acrobat: isAcrobatInstalled() ? 'installed' : false,
acrobatVersion: getAcrobatVersion()
};
};
</script>
Also add this code behind:
public void detectBrowser()
{ //Set the Browser session variable
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Session["Browser"] = browser.Browser;
}
Hope it helps.

Categories

Resources