How do I dynamically set source of an IFrame? - c#

I have an IFrame embedding a youtube video. I want to create a textbox where user (admins) can paste a new src (URL) of video and the IFrame take the new source. Here is what I have so far:
protected void Edited_Click(object sender, EventArgs e)
{
// HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
string url = TextBox1.Text;
frame1.Attributes["src"] = url;
}
And in the html code is the Iframe:
<div id="video">
<iframe title="YouTube video player" runat="server" width="420"
frameborder="1" style="height: 265px; float: left;
text-align: center;" id="frame1"
name="frame1" align="middle"></iframe>
<br />
</div>
I don't set any src in the beginning but when I paste a URL in the textbox and hit the button, the Iframe doesn't displays anything.

Other responses don't answer the question, they provide an alternative. The question is how to set iFrame src from C#. I'll answer that here.
I'm all for "right tools for the job" and use that mantra a lot myself - but only when the other tools are "wrong". That hasn't been established here. Can someone provide a good technical reason why this should not be done in code-behind?
I think the issue #Pepys is experiencing might be due to something in the URL, which he hasn't provided yet. For example, maybe his URL includes ampersands or other characters which need to be escaped.
The following code works fine for me:
excelframe.Attributes["src"] =
#"https://r.office.microsoft.com/r/rlidExcelEmbed?"
+ #"su=-0000000000"
+ #"&Fi=zzzzzzzzzzzz!111"
+ #"&ak=x%3d9%26x%3d9%26x%3d!zzzzzzzzzz"
+ #"&kip=1"
+ #"&AllowTyping=True"
+ #"&ActiveCell='sheet1'!C3"
+ #"&wdHideGridlines=True"
+ #"&wdHideHeaders=True"
+ #"&wdDownloadButton=True";

You need to do this on the client browser, not server-side. I would suggest something like:
// (Add inside script element in head of page html)
window.onload = function() {
document.getElementById('<id of input>').onchange = function() {
changeFrameUrl();
}
};
function changeFrameUrl() {
var inputVal = document.getElementById('<id of input>').value;
document.getElementById('<id of iframe>').src = inputVal;
}
Hope this helps - it's off the top of my head though, so don't diss me if it doesn't work first time!

Related

Search for RSS Feeds on Google

I hope I am not just chasing a red herring here. I have seen some websites that you are able to search for RSS feeds by typing in some sort of term like "Technology news" and it would return a number of different feeds that you can chose from.
Most look to be where they are just searching their own curated database which is all fine and dandy, however there is one that looks like it uses Google to search for them. http://ctrlq.org/rss/
Does anyone know how this could be done and point me in the right direction to learn how it is done as it is bugging the life out of me? I have done a lot of searching but most seem to point to the depreciated Google Feed API that no longer works or using Google Alerts to create an RSS Feed which I am not wanting to do.
Ideally I would like to do this in C# so that I can easily deal with the results and save the relevant selected option in a database.
It also doesn't need to be Google that it is done in, if there are other options that are available then great :)
Cheers.
I was kinda intrigue by your question and this is what I've find out. First of all I went to the site http://ctrlq.org/rss/ and checked what is done after click on Search button:
function findfeeds() {
var q = $.trim($('#feedQuery').val());
if(q == "") {
resetfeeds();
return false;
}
$('#pleasewait').show();
google.feeds.findFeeds(q, function(result) {
if (!result.error) {
var html = '';
for (var i = 0; i < result.entries.length; i++) {
var entry = result.entries[i];
feedList[i] = entry.url;
var count = i+1;
html += '<div id="feed-' + i + '">';
html += ' <h3><img src="//s2.googleusercontent.com/s2/favicons?domain=' + entry.link + '"/> <a target="_blank" href="' + entry.link + '">' + removeHTMLTags(entry.title) + '</a></h3>';
html += ' <p class="snippet">' + removeHTMLTags(entry.contentSnippet) + '</p>';
html += ' <p class="feedURL">';
html += 'RSS Feed ⋅ ';
html += ' <span class="showhide" rel="' + i + '">Preview Feed</span></p>';
html += ' <div id="feedcontent-' + i + '"></div>';
html += '</div>';
}
$("#results").fadeOut('slow', function() {
$('html, body').animate({scrollTop:0}, 'slow');
$("#results").empty();
$("#results").append(html);
$("#results").show();
});
}
$('#pleasewait').hide();
});
return false;
}
This is the function called after click. I noticed it uses something named 'google.feeds.findFeeds' so a bit of searching and voilà: https://developers.google.com/feed/v1/devguide#optional. There is a google api which provides functionality for searching and browsing public rss feeds :) The site provides examples of use so you can read more there. I hope this covers all of your doubts ;)

Using jQuery .load() with aspx

So I'm fairly new to the .NET framework, but what I'm trying to do is execute the following jQuery code:
$(document).on('click', 'a[data-link]', function () {
var $this = $(this);
url = $this.data('link');
$("#imagePreview").load("imageProcess.aspx?"+url);
where url holds something like "model=2k01&type=black&category=variable".
Unfortunately this doesn't work, becuase when I do something as simple as a Response.Write() in the aspx file, the div tag imagePreview doesn't do anything. However, removing the ? + url part works, but then I can't send any data over to the aspx file. I'm doing it this way because every link a[data-link] has different data that's being sent over, and I need to find a dynamic way to achieve this. Any suggestions would be much appreciated.
UPDATE:
Here is the part in my html code that is generating the url stuff:
<a class='modelsBlue' href = '#' data-link='model=" + $(this).find('model').text() + "&type=" + category + "'>" + $(this).find("model").text() + "</a>
and #image preview is in my code as:
<div id = "imagePreview"></div>
When I try to run the code above, i get the following error which seems to be coming from the jQuery.js file:
Microsoft JScript runtime error: Syntax error, unrecognized expression: &type=AutoEarly
Here is the imageProcess.aspx.cs file, which right now is just outputting all images in the directory:
namespace ModelMonitoring
{
public partial class imageProcess : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("test");
foreach (var f in Directory.GetFiles(Directory.GetCurrentDirectory()))
{
Response.Write(f);
Response.Write("<br />");
}
}
}
}
SECOND UPDATE:
I don't get the error running in chrome or firefox, but the files are not being output.
Turns out it was a whitespace issue. I had to add a wrapper around:
$(this).find('model').text()
to read:
$.trim($(this).find('model').text())
becuase the xml file I was reading from had whitespace around the model name. Thanks to anyone who replied!

Good ASP.NET method for checking, reading and returning file contents

I found a good way to check if a file exists and read the contents if it does, but for some reason I can't create a method out of it.
Here's what I have so far:
<script runat="server">
void Page_Load(Object s, EventArgs e) {
lblFunction.Text = mwbInclude("test.txt");
}
string mwbInclude(string fileName) {
string inc = Server.MapPath("/extra/include/" + Request["game"] + "/" + fileName);
string valinc;
if(System.IO.File.Exists(inc))
{
valinc = System.IO.File.ReadAllText(inc);
}
return valinc;
}
</script>
I wish I could provide more info, but the server this is on doesn't show any feedback on errors, just a 404 page.
I think
valinc = Response.Write(System.IO.File.ReadAllText(inc));
should be
valinc = System.IO.File.ReadAllText(inc);
Why are you setting the Text property and calling Response.Write? Do you want to render the text as a label, or as the whole response?
If you're getting a 404, it's because your page isn't being found, not because there's a problem with the script itself. Have you tried ripping out all of the code and just sticking in some HTML tags as a sanity check?

Why are backward slashes removed from querystring - ASP.NET & Javascript

I am trying to generate a URL that contains a UNC path as one of the query string variables. The URL will open in a pop up window when an ASP.NET button control is clicked by the user. When the clicks the button, the backwards slashes are removed from the UNC path causing the page to break.
The button renders correctly in the page source file with all the backward slashes.
Is there any way to prevent this?
Here is my source code:
Code behind:
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + url + #"')");
ASPX page
<script language="javascript" type="text\javascript">
function FullPop(Newurl) {
Win = window.open( Newurl,"Monitor", "fullscreen=0,toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600,top=50,left=50");
Win.focus();
}
</script>
<asp:button id="MyButton" runat="server" cssclass="mycss" text="View Actual Target" />
Update
Server.UrlEncode does not work. Same behavior.
Update 1
Based on Daniel Lew's answer, I developed the following solution:
protected void Page_Load(object sender, EventArgs e)
{
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + this.EscapeforJavaScript(url) + #"')");
}
private string EscapeforJavaScript(string url)
{
return url.Replace(#"\", #"\\");
}
You have to URL encode the value that you put in the URL:
string url = "http://www.mysite.com/page.aspx?a=" + Server.UrlEncode(unc);
Edit:
To safely put the url in the Javascript code, you also have to encode the string for being a literal string:
MyButton.Attributes.Add("onclick", #"FullPop('" + url.Replace(#"\", #"\\").Replace("'", #"\'") + #"')");
(The javascript: protocol is only used when the Javascript is used as href for a link, not when you put code in an event like onclick.)
I don't know anything about asp.net, but I have had experience with problems when adding text straight into JavaScript before through templating. Have you tried escaping the backslashes on your url, to avoid this?
// Returns "\myservermyfoldermyfile.txt", due to escpaing the backslash.
alert("\\myserver\myfolder\myfile.txt");
// Returns correct value of "\\myserver\myfolder\myfile.txt"
alert("\\\\myserver\\myfolder\\myfile.txt");
You may want to try URLEncoding your string on your server side, using the following method:
public static string UrlFullEncode(string strUrl)
{
if (strUrl == null)
return "";
strUrl = System.Web.HttpUtility.UrlEncode(strUrl);
}
I'm not 100% sure it if will replace the backslashes, but it's worth a try.

Can you recommend alternative FileUpload control for asp.net-mvc?

Currently using System.Web.UI.WebControls.FileUpload wrapped in our own control.
We have licenses for Telerik. I wanted to know if anyone had experience with that or could suggest a better one?
Some criteria to be measured by
validation
peformance
multiple files
localisation (browse is difficult)
security
Personally, if you have the Telerik controls I would give them a shot. I've found that they are very helpful, and the user experience is good. Their upload control is quite nice.
I just posted about this in another question, but if you use this ActiveX control you will be able to process images quickly and efficiently. The component will actually resize the images on the client machine before sending them. This reduces unnecessary bandwidth and transfers multiple images at one time.
We extended the FileUploadControl to add some validation. We also wrote our own control that allows multiple files to be uploaded at once. We are currently evaluating both. Hopefully we decide on one, I would hate to have 2 different upload controls to maintain.
Check out Dean Brettle's NeatUpload. It's basically a custom HttpHandler that streams files to disk with loads of extra configurability. It's open source and Dean is an absolute star for supporting his users.
Check this one out: Html-5-Uploader
Drag-and-drop multiple files on your webpage!
Link doesn't always work so here it is again: http://www.igloolab.com/jquery-html5-uploader/
.
Controller: (modified from my original code, hope i don't forgot something, but it's pretty clear)
<HttpPost()> _
Public Function Upload(uploadedFile As System.Web.HttpPostedFileBase) As ActionResult
If uploadedFile IsNot Nothing Then
If uploadedFile.ContentLength > 0 Then
Dim mimeType As String = Nothing
'Upload
Dim PathFileName As String = System.IO.Path.GetFileName(uploadedFile.FileName)
Dim path = System.IO.Path.Combine(Server.MapPath("~/App_Data/Uploads"), PathFileName)
If Not System.IO.Directory.Exists(Path) Then
System.IO.Directory.CreateDirectory(Path)
End If
Dim firstLoop As Boolean = True
uploadedFile.SaveAs(path)
Next
End If
Return Nothing
End Function
This is the View (don't forget links to css and js ;))
<h1>
#SharedStrings.Upload</h1>
<h2>
#SharedStrings.UploadInformation</h2>
<div id="dropbox">
</div>
<div id="upload">
</div>
<script type="text/javascript">
$(function () {
var fileTemplate = "<div id=\"{{id}}\">"; fileTemplate += "<div class=\"progressbar\"></div>"; fileTemplate += "<div class=\"preview\"></div>"; fileTemplate += "<div class=\"filename\">{{filename}}</div>"; fileTemplate += "</div>"; function slugify(text) { text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, ''); text = text.replace(/-/gi, "_"); text = text.replace(/\s/gi, "-"); return text; }
$("#dropbox").html5Uploader({ onClientLoadStart: function (e, file) {
var upload = $("#upload"); if (upload.is(":hidden")) { upload.show(); }
upload.append(fileTemplate.replace(/{{id}}/g, slugify(file.name)).replace(/{{filename}}/g, file.name));
}, onClientLoad: function (e, file) { /*$("#" + slugify(file.name)).find(".preview").append("<img src=\"" + e.target.result + "\" alt=\"\">");*/ }, onServerLoadStart: function (e, file) { $("#" + slugify(file.name)).find(".progressbar").progressbar({ value: 0 }); }, onServerProgress: function (e, file) { if (e.lengthComputable) { var percentComplete = (e.loaded / e.total) * 100; $("#" + slugify(file.name)).find(".progressbar").progressbar({ value: percentComplete }); } }, onServerLoad: function (e, file) { $("#" + slugify(file.name)).find(".progressbar").progressbar({ value: 100 }); }
});
});
</script>
And my css
/*html 5 uploader*/
#dropbox
{
/*picture where people would drag-drop their files to*/
background-image:url(../Images/UploadToMedia.png);
height:128px;
margin-bottom:40px;
margin-left:auto;
margin-right:auto;
background-repeat:no-repeat;
margin-top:0;
width:128px;
}
You could try a flash-based solution that allows you to display whatever text, textboxes, buttons, or anything else as part of your own file upload control. These solutions typically put a 1x1 flash movie on the page that acts as a bridge between javascript and flash such that javascript can call flash's file upload box dynamically.
In a recent project, I used FancyUpload to do exactly that.

Categories