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

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.

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 ;)

Trigger System.Windows.Forms dll using javascript ActiveX object

I am developing a C++ custom wizard with 1 page UI consisting of a dropdown control.
I want to populate this dropdown control with all input languages installed on that machine.
(An input language is a culture/keyboard layout pair that determines how the physical keys on a keyboard map or plot to characters in a language.)
I am trying to get this list & have found a way to do in C#.
public void GetLanguages() {
// Gets the list of installed languages.
foreach(InputLanguage lang in InputLanguage.InstalledInputLanguages) {
textBox1.Text += lang.Culture.EnglishName + '\n';
}
}
No i want to implement the same using javascript as my custom wizard uses .js
I tried doing below, but getting the js runtime error: "Automation Server can't create object".
<select class="sideBtn" size="1" id="LANGUAGE_LISTBOX" accesskey="L" title="Select Languages:">
<script type="text/javascript">
var obj = new ActiveXObject("System.Windows.Forms");
// Gets the list of installed languages.
for (var lang in obj.Windows.Forms.InputLanguage.InstalledInputLanguages)
{
document.write('<option value="' + lang.Culture.EnglishName + '">' + lang.Culture.EnglishName + '</option>');
}
</script>
</select>
I have tried like this as i have referred other articles which shows trigerring a c# dll using javascript ActiveX object.
Triggering C# dll using Javascript ActiveX Object
Can some one help me please??
Regards,
Deepthi
You can't do what you want using this code, because there is no COM object registered as System.Windows.Forms. But the question you've linked to, is exactly what you want.
You have two options to implement this and selecting one of them depends on whether you want to have just the culture names in Javascript side or the whole InputLanguage class. I think the first approach will be enough for you here. For the second one, you should define an interface and a new class that contain all the properties of InputLanguage you need in Javascript.
In the interface IHello, change this:
[DispId(1)]
string GetLanguages();
In the class CHello, change this:
public string GetLanguages()
{
string[] langNames =InputLanguage.InstalledInputLanguages
.OfType<InputLanguage>()
.Select(lang => string.Format("{0}", lang.Culture.EnglishName))
.ToArray();
// This is a simple Join, just to give you the idea
// You better use a proper serialization like JSON
return string.Join(";", langNames);
}
And your javascript code (suppose you either reduced the security levels, or signed you ActiveX):
<script type="text/javascript">
myAx1 = new ActiveXObject("csharpAx.CHello");
if(myAx1 != null)
{
// Gets the list of installed languages.
for (var lang in obj.GetLanguages().split(";"))
{
document.write('<option value="' +
lang +
'">' +
lang +
'</option>');
}
}
</script>

How do I dynamically set source of an IFrame?

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!

ASP.NET image src question

I set the value of a image control via the following jquery code:
$('.image').click(function () {
var imgPath = $(this).attr('src');
var imgName = imgPath.substring(0, imgPath.length - 4);
var imgAlt = $(this).attr('alt');
$('#<%= detailedImage.ClientID %>').
attr('src', imgName + '-large.jpg').
attr('alt', imgAlt);
The picture shows up perfectly in the browser. However I cannot access it's src attribute:
string imgName = detailedImage.Src;
imgName is always an empty string. Any suggestions?
Changing the src of an img, even though the img is placed within a <form> doesn't submit the src to the server. You need to set the new src in something that will be submitted in the form, i.e. a hidden field. Try this:
$('.image').click(function () {
var imgPath = $(this).attr('src');
var imgName = imgPath.substring(0, imgPath.length - 4);
var imgAlt = $(this).attr('alt');
var src = imgName + '-large.jpg';
$('#<%= detailedImage.ClientID %>').
attr('src', src).
attr('alt', imgAlt);
$('#<%= hiddenInput.ClientID %>').val(src);
});
If you now have something like this in your markup:
<input type="hidden" id="ImageSource" runat="server" />
You should be able to retrieve ImageSource.Value server-side.
I'm sure there are a number of ways to solve this, depending a lot on factors elsewhere in your page and your application which would contribute to the overall functionality and user experience. But in terms of suggestions, how about this:
Instead of trying to maintain the state of the selected image in the image control, separate it out into a different control. Use a standard img HTML element for displaying the image(s) to the user on the client-side and keep that as solely a user experience concern. Don't use it as part of a form.
Then create a separate control (a hidden field, a text box which has been styled to not be displayed, etc.) and set the path of the image file as the value of that control in your JavaScript. Something like this:
$('.image').click(function () {
var imgPath = $(this).attr('src');
var imgName = imgPath.substring(0, imgPath.length - 4);
var imgAlt = $(this).attr('alt');
$('#showImage').attr('src', imgName + '-large.jpg').attr('alt', imgAlt);
$('#<%= imagePath.ClientID %>').val(imgName + '-large.jpg');
});
Note that the src and alt are being set on a standard img tag (with id showImage in this case) and the value that the server-side code cares about is being set on another control entirely (with server-side id imagePath in this case).
I don't have a way of testing this on hand right now, but it's a suggestion. It's possible it may not work, and if that's the case let me know so I can modify/remove this answer. But it seems like it would make sense given that things like TextBox ASP.NET controls are meant to have their values modified on the client-side. (Indeed, in this case you may have better luck with a TextBox styled to not be displayed than with a hidden field.)

Getting the executed output of an aspx page after a short delay

I have an aspx page which has some javascript code like
<script>
setTimeout("document.write('" + place.address + "');",1);
</script>
As it is clear from the code it will going to write something on the page after a very short delay of 1 ms. I have created an another page to get the page executed by some query string and get its output. The problem is
I can not avoid the delay as simply writing document.write(place.address); will not print anything as it takes a little time to get values so if I set it in setTimeout for delayed output of 1 ms it always return me a value
If I request the output from another page using
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead("http://localhost:4859/Default.aspx?lat=" + lat + "&lng=" + lng));
string strData = sr.ReadToEnd();
I get the source code of the document instead of the desired output.
I would like to either avoid that delay or else delayed the client request output so that I get a desired value not the source code.
The JS on default.aspx is
<script type="text/javascript">
var geocoder;
var address;
function initialize() {
geocoder = new GClientGeocoder();
var qs=new Querystring();
if(qs.get("lat") && qs.get("lng"))
{
geocoder.getLocations(new GLatLng(qs.get("lat"),qs.get("lng")),showAddress);
}
else
{
document.write("Invalid Access Or Not valid lat long is provided.");
}
}
function getAddress(overlay, latlng) {
if (latlng != null) {
address = latlng;
geocoder.getLocations(latlng, showAddress);
}
}
function showAddress(r) {
place = r.Placemark[0];
setTimeout("document.write('" + place.address + "');",1);
//document.write(place.address);
}
</script>
and the code on requestClient.aspx is as
System.Net.WebClient wc = new System.Net.WebClient();
System.IO.StreamReader sr = new System.IO.StreamReader(wc.OpenRead("http://localhost:4859/Default.aspx?lat=" + lat + "&lng=" + lng));
string strData = sr.ReadToEnd();
I'm not a JavaScript expert, but I believe using document.write after the page has finished loading is a bad thing. You should be creating an html element that your JavaScript can manipulate, once the calculation is complete.
Elaboration
In your page markup, create a placeholder for where you want the address to appear:
<p id="address">Placeholder For Address</p>
In your JavaScript function, update that placeholder:
function showAddress(r) {
place = r.Placemark[0];
setTimeout("document.getElementById('address').innerHTML = '" + place.address + "';",1);
}
string strData = sr.ReadToEnd();
I get the source code of the document instead of the desired output
(Could you give a sample of the output. I don't think I've seen a web scraper work that way so that would help me to be sure. But if not this is a good example web scraper)
Exactly what are you doing with the string "strData" If you are just writing it out, I recommend you putting it in a Server side control (like a literal). If at all possible, I'd recommend you do this server side using .net rather than waiting 1 ms in javascript (which isn't ideal considering the possibility that 1 ms may or may not be an ideal amount of time to wait on a particular user's machine hence: "client side"). In a case like this and I had to do it client side I would use the element.onload event to determine if a page has finished loading.

Categories