ASP.NET MVC - Upload a file with SignalR - asp.net

I want to upload a file from the client to the server. Is there a way to upload a file with SignalR or must i need a Controller for this?

SignalR is for real time messaging not uploading files.

While SignalR cannot help with the actual upload, it can be used for updating the client with progress while a file is uploaded.

This file uploading using file input bootstrap plugin (krajee)
You can also upload file without using this plugin.
#section Page{
<script src="~/Scripts/bootstrap-switch.min.js"></script>
<script src="~/Scripts/Uploader/fileinput.js"></script>
<link href="~/Scripts/Uploader/fileinput.css" rel="stylesheet" />
<script>
var itemHub = $.connection.ItemHub;
$(document).ready(function() {
$.connection.hub.start().done(function() {
//do any thing
});
$("#fileinput").fileinput({
allowedFileExtensions: ["jpg", "png", "gif", "jpeg"],
maxImageWidth: 700,
maxImageHeight: 700,
resizePreference: 'height',
maxFileCount: 1,
resizeImage: true
});
$("#fileinput").on('fileloaded', function (event, file, previewId, index, reader) {
var readers = new FileReader();
readers.onloadend = function () {
$(".file-preview-image").attr('src', readers.result);
}
readers.readAsDataURL(file);
});
$('#btnSave').click(function() {
var imagesJson = $('.file-preview-image').map(function () {
var $this = $(this);
return {
image: $this.attr('src'),
filename: $this.attr('data-filename')
};
}).toArray();
itemHub.server.getByteArray(imagesJson);
});
});
</script>
}
Hub class code
[HubName("ItemHub")]
public class ItemHub : Hub
{
public void GetByteArray(IEnumerable<ImageData> images)
{
foreach (var item in images ?? Enumerable.Empty<ImageData>())
{
var tokens = item.Image.Split(',');
if (tokens.Length > 1)
{
byte[] buffer = Convert.FromBase64String(tokens[1]);
}
}
}
}
public class ImageData
{
public string Description { get; set; }
public string Filename { get; set; }
public string Image { get; set; }
}

Related

Signalr Owin simple example javascript client not being called

I have a 5.3.0 version of signalr self hosting that is being upgraded to a newer version of signalr.
Using https://github.com/SignalR/SignalR/wiki/Self-host example i have created a simple example, but i can’t get it to work.
I can get a connection to the hub on the server and call methods on the hub, but i can’t get the hub to call the javascript client.
When looking at it in fiddler I never see a response come back from the hub.
Here is the code
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Hosting;
using Owin;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8080/";
using (WebApplication.Start<Startup>(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
}
using Microsoft.AspNet.SignalR;
using Owin;
namespace ConsoleApplication3
{
class Startup
{
// This method name is important
public void Configuration(IAppBuilder app)
{
var config = new HubConfiguration
{
EnableCrossDomain = true,
EnableJavaScriptProxies = true
};
app.MapHubs(config);
}
}
}
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Newtonsoft.Json;
namespace ConsoleApplication3.Hubs
{
public class Chat : Hub
{
public override Task OnConnected()
{
Notify(Context.ConnectionId);
return new Task(() => { });
}
public void RunTest()
{
Notify(Context.ConnectionId);
}
public void Notify(string connectionId)
{
dynamic testMessage = new
{
Count = 3,
Message = "Some test message",
Timestamp = DateTime.Now
};
String json = JsonConvert.SerializeObject(testMessage);
var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
context.Clients.Client(connectionId).sendNotification(json);
}
}
}
And here is the client side
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/json2.js"></script>
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/jquery.signalR-1.0.1.js"></script>
<script src="http://localhost:8080/signalr/hubs"></script>
<script>
$(function () {
// Proxy created on the fly
var notification = $.connection.chat;
$.connection.hub.logging = true;
// Declare functions that can be run on the client by the server
notification.client.sendNotification = onAddNotification;
notification.client.disconnected = function (connectionid) {
console.log(connectionid);
};
// Testing code only
$("#testButton").click(function () {
// Run test function on server
notification.server.runTest();
});
jQuery.support.cors = true;
// Map the onConnect and onDisconnect functions
notification.client.connected = function () {
alert("Notification system connected");
};
notification.client.disconnected = function () { };
$.connection.hub.url = "http://localhost:8080/signalr";
//$.connection.hub.start();
$.connection.hub.start(function () {
alert("Notification system connected");
});
});
// Process a newly received notification from the server
function onAddNotification(message) {
// Convert the passed json message back into an object
var obj = JSON.parse(message);
var parsedDate = new Date(parseInt(obj.Timestamp.substr(6)));
// Update the notification list
$('#notifications').prepend('<li>' + obj.Message + ' at ' + parsedDate + '</li>');
};
</script>
</head>
<body>
Send test
<ul class="unstyled" id="notifications">
</ul>
</body>
Any ideas would be appreciated, since i am fairly stuck.
Few things in your code:
Change this:
public override Task OnConnected()
{
Notify(Context.ConnectionId);
return new Task(() => { });
}
To:
public override Task OnConnected()
{
Notify(Context.ConnectionId);
return base.OnConnected();
}
Also in your hub:
This function is trying too hard:
public void Notify(string connectionId)
{
dynamic testMessage = new
{
Count = 3,
Message = "Some test message",
Timestamp = DateTime.Now
};
String json = JsonConvert.SerializeObject(testMessage);
var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();
context.Clients.Client(connectionId).sendNotification(json);
}
I'm not even sure why you're passing the connection id (maybe it was meant to be static?)
public void Notify()
{
dynamic testMessage = new
{
Count = 3,
Message = "Some test message",
Timestamp = DateTime.Now
};
Clients.Client(Context.ConnectionId).sendNotification(testMessage);
}
You don't need to serialize twice, we already do it for you.
Remove:
jQuery.support.cors = true;
Never set that.
Also:
// Map the onConnect and onDisconnect functions
notification.client.connected = function () {
alert("Notification system connected");
};
notification.client.disconnected = function () { };
These aren't mapping anything client side. You can't map connected and disconnected from the server to the client. The client has its own events.
Other things:
This should be inside of the start callback so that you don't hit it before it's ready:
$.connection.hub.start().done(function() {
// Testing code only
$("#testButton").click(function () {
// Run test function on server
notification.server.runTest();
});
});

How can i use engine object in my console application

"How can i use engine in my console application"
I shouldn't use the ITemplate-interface and Transform-Method.
I am using Tridion 2011
Could anyone please suggest me.
You can't. The Engine class is part of the TOM.NET and that API is explicitly reserved for use in:
Template Building Blocks
Event Handlers
For all other cases (such as console applications) you should use the Core Service.
There are many good questions (and articles on other web sites) already:
https://stackoverflow.com/search?q=%5Btridion%5D+core+service
http://www.google.com/#q=tridion+core+service
If you get stuck along the way, show us the relevant code+configuration you have and what error message your get (or at what step you are stuck) and we'll try to help from there.
From a console application you should use the Core Service. I wrote a small example using the Core Service to search for items in the content manager.
Console.WriteLine("FullTextQuery:");
var fullTextQuery = Console.ReadLine();
if (String.IsNullOrWhiteSpace(fullTextQuery) || fullTextQuery.Equals(":q", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.WriteLine("SearchIn IdRef:");
var searchInIdRef = Console.ReadLine();
var queryData = new SearchQueryData
{
FullTextQuery = fullTextQuery,
SearchIn = new LinkToIdentifiableObjectData
{
IdRef = searchInIdRef
}
};
var results = coreServiceClient.GetSearchResults(queryData);
results.ToList().ForEach(result => Console.WriteLine("{0} ({1})", result.Title, result.Id));
Add a reference to Tridion.ContentManager.CoreService.Client to your Visual Studio Project.
Code of the Core Service Client Provider:
public interface ICoreServiceProvider
{
CoreServiceClient GetCoreServiceClient();
}
public class CoreServiceDefaultProvider : ICoreServiceProvider
{
private CoreServiceClient _client;
public CoreServiceClient GetCoreServiceClient()
{
return _client ?? (_client = new CoreServiceClient());
}
}
And the client itself:
public class CoreServiceClient : IDisposable
{
public SessionAwareCoreServiceClient ProxyClient;
private const string DefaultEndpointName = "netTcp_2011";
public CoreServiceClient(string endPointName)
{
if(string.IsNullOrWhiteSpace(endPointName))
{
throw new ArgumentNullException("endPointName", "EndPointName is not specified.");
}
ProxyClient = new SessionAwareCoreServiceClient(endPointName);
}
public CoreServiceClient() : this(DefaultEndpointName) { }
public string GetApiVersionNumber()
{
return ProxyClient.GetApiVersion();
}
public IdentifiableObjectData[] GetSearchResults(SearchQueryData filter)
{
return ProxyClient.GetSearchResults(filter);
}
public IdentifiableObjectData Read(string id)
{
return ProxyClient.Read(id, new ReadOptions());
}
public ApplicationData ReadApplicationData(string subjectId, string applicationId)
{
return ProxyClient.ReadApplicationData(subjectId, applicationId);
}
public void Dispose()
{
if (ProxyClient.State == CommunicationState.Faulted)
{
ProxyClient.Abort();
}
else
{
ProxyClient.Close();
}
}
}
When you want to perform CRUD actions through the core service you can implement the following methods in the client:
public IdentifiableObjectData CreateItem(IdentifiableObjectData data)
{
data = ProxyClient.Create(data, new ReadOptions());
return data;
}
public IdentifiableObjectData UpdateItem(IdentifiableObjectData data)
{
data = ProxyClient.Update(data, new ReadOptions());
return data;
}
public IdentifiableObjectData ReadItem(string id)
{
return ProxyClient.Read(id, new ReadOptions());
}
To construct a data object of e.g. a Component you can implement a Component Builder class that implements a create method that does this for you:
public ComponentData Create(string folderUri, string title, string content)
{
var data = new ComponentData()
{
Id = "tcm:0-0-0",
Title = title,
Content = content,
LocationInfo = new LocationInfo()
};
data.LocationInfo.OrganizationalItem = new LinkToOrganizationalItemData
{
IdRef = folderUri
};
using (CoreServiceClient client = provider.GetCoreServiceClient())
{
data = (ComponentData)client.CreateItem(data);
}
return data;
}
Hope this gets you started.

Scriptcontrol - bind client & server properties

Is it possible to bind properties on the client and server side in Scriptcontrol, so when I set property in javascript, change will be visible also in code behind and when I set property in code behind, change will be visible in javascript?
I can't get it work like above - it is set initially, when I set property where scriptcontrol is declared, but when I change it later it is still the same as before...
EDIT: I try to do a ProgressBar for long postbacks in our ASP.NET application. I have tried many options but none works for me... I want to set progress value in code behind and has it updated in view during long task postback.
Code for ScriptControl:
C#:
public class ProgressBar : ScriptControl
{
private const string ProgressBarType = "ProgressBarNamespace.ProgressBar";
public int Value { get; set; }
public int Maximum { get; set; }
protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
this.Value = 100;
this.Maximum = 90;
var descriptor = new ScriptControlDescriptor(ProgressBarType, this.ClientID);
descriptor.AddProperty("value", this.Value);
descriptor.AddProperty("maximum", this.Maximum);
yield return descriptor;
}
protected override IEnumerable<ScriptReference> GetScriptReferences()
{
yield return new ScriptReference("ProgressBar.cs.js");
}
}
Javascript:
Type.registerNamespace("ProgressBarNamespace");
ProgressBarNamespace.ProgressBar = function(element) {
ProgressBarNamespace.ProgressBar.initializeBase(this, [element]);
this._value = 0;
this._maximum = 100;
};
ProgressBarNamespace.ProgressBar.prototype = {
initialize: function () {
ProgressBarNamespace.ProgressBar.callBaseMethod(this, "initialize");
this._element.Value = this._value;
this._element.Maximum = this._maximum;
this._element.show = function () {
alert(this.Value);
};
},
dispose: function () {
ProgressBarNamespace.ProgressBar.callBaseMethod(this, "dispose");
},
get_value: function () {
return this._value;
},
set_value: function (value) {
if (this._value !== value) {
this._value = value;
this.raisePropertyChanged("value");
}
},
get_maximum: function () {
return this._maximum;
},
set_maximum: function (value) {
if (this._maximum !== value) {
this._maximum = value;
this.raisePropertyChanged("maximum");
}
}
};
ProgressBarNamespace.ProgressBar.registerClass("ProgressBarNamespace.ProgressBar", Sys.UI.Control);
if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
I'll appreciate any way to implement this progress bar...
Personally, I do this often using hidden fields.
Bear in mind that hidden fields are not secure and may have other downfalls, since they don't actually hide their value, just simply do not display it.
ASPX Markup
<asp:HiddenField ID="hiddenRequest" runat="server" ClientIDMode="Static" />
ASPX.CS Code behind
public string HiddenRequest
{
set
{
hiddenRequest.Value = value;
}
get
{
return hiddenRequest.Value;
}
}
Page JAVASCRIPT (with jQuery)
$('#hiddenRequest').val('MyResult');
This way, I can access the same field using one variable as such, accessed both from client side and server side.

MVC3 Valums Ajax File Upload

I'm trying to use valums ajax uploader. http://valums.com/ajax-upload/
I have the following on my page:
var button = $('#fileUpload')[0];
var uploader = new qq.FileUploader({
element: button,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
sizeLimit: 2147483647, // max size
action: '/Admin/Home/Upload',
multiple: false
});
it does post to my controller but qqfile is always null. I tried these:
public ActionResult Upload(HttpPostedFile qqfile)
AND
HttpPostedFileBase file = Request.Files["file"];
without any luck.
I found an example for ruby on rails but not sure how to implement it in MVC
http://www.jigsawboys.com/2010/10/06/ruby-on-rails-ajax-file-upload-with-valum/
In firebug i see this:
http://localhost:61143/Admin/Home/Upload?qqfile=2glonglonglongname+-+Copy.gif
I figured it out. this works in IE and Mozilla.
[HttpPost]
public ActionResult FileUpload(string qqfile)
{
var path = #"C:\\Temp\\100\\";
var file = string.Empty;
try
{
var stream = Request.InputStream;
if (String.IsNullOrEmpty(Request["qqfile"]))
{
// IE
HttpPostedFileBase postedFile = Request.Files[0];
stream = postedFile.InputStream;
file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
}
else
{
//Webkit, Mozilla
file = Path.Combine(path, qqfile);
}
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(file, buffer);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, "application/json");
}
return Json(new { success = true }, "text/html");
}
This component is sending an application/octet-stream instead of multipart/form-data which is what the default model binder can work with. So you cannot expect Request.Files to have any value with such a request.
You will need to manually read the request stream:
public ActionResult Upload(string qqfile)
{
var stream = Request.InputStream;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
var path = Server.MapPath("~/App_Data");
var file = Path.Combine(path, qqfile);
File.WriteAllBytes(file, buffer);
// TODO: Return whatever the upload control expects as response
}
IE uploads using multipart-mime. Other browsers use Octet-Stream.
I wrote an upload handler to work with Valums Ajax Uploader that works with both MVC & Webforms & both upload methods. I'd be happy to share with you if you wanted. It closely follows the the PHP handler.
My controller to handle the upload looks like this:
public class UploadController : Controller
{
private IUploadService _Service;
public UploadController()
: this(null)
{
}
public UploadController(IUploadService service)
{
_Service = service ?? new UploadService();
}
public ActionResult File()
{
return Content(_Service.Upload().ToString());
}
The UploadService looks this:
public class UploadService : IUploadService
{
private readonly qq.FileUploader _Uploader;
public UploadService()
: this(null)
{ }
public UploadService(IAccountService accountservice)
{
_Uploader = new qq.FileUploader();
}
public UploadResult Upload()
{
qq.UploadResult result = _Uploader.HandleUpload();
if (!result.Success)
return new UploadResult(result.Error);
.... code .....
return new UploadResult((Guid)cmd.Parameters["#id"].Value);
}
catch (Exception ex)
{
return new UploadResult(System.Web.HttpUtility.HtmlEncode(ex.Message));
}
finally
{
............code.........
}
}
...............code ............
You should try:
Stream inputStream = (context.Request.Files.Count > 0) ? context.Request.Files[0].InputStream : context.Request.InputStream;
I am developing in ASP.Net 4.0 but we don't have MVC architecture. I had same issue few days back. But, I figured it out and here is my solution.
//For IE Browser
HttpPostedFile selectedfile = Request.Files[0];
System.Drawing.Bitmap obj = new System.Drawing.Bitmap(selectedfile.InputStream);
//For Non IE Browser
System.Drawing.Bitmap obj = new System.Drawing.Bitmap(Request.InputStream);
Now, you can use obj for further operation.

FullCalendar events from asp.net ASHX page not displaying

I have been trying to add some events to the fullCalendar using a call to a ASHX page using the following code.
Page script:
<script type="text/javascript">
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today', center: 'title', right: 'month, agendaWeek,agendaDay'
},
events: 'FullCalendarEvents.ashx'
})
});
</script>
c# code:
public class EventsData
{
public int id { get; set; }
public string title { get; set; }
public string start { get; set; }
public string end { get; set; }
public string url { get; set; }
public int accountId { get; set; }
}
public class FullCalendarEvents : IHttpHandler
{
private static List<EventsData> testEventsData = new List<EventsData>
{
new EventsData {accountId = 0, title = "test 1", start = DateTime.Now.ToString("yyyy-MM-dd"), id=0},
new EventsData{ accountId = 1, title="test 2", start = DateTime.Now.AddHours(2).ToString("yyyy-MM-dd"), id=2}
};
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json.";
context.Response.Write(GetEventData());
}
private string GetEventData()
{
List<EventsData> ed = testEventsData;
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var data in ed)
{
sb.Append("{");
sb.Append(string.Format("id: {0},", data.id));
sb.Append(string.Format("title:'{0}',", data.title));
sb.Append(string.Format("start: '{0}',", data.start));
sb.Append("allDay: false");
sb.Append("},");
}
sb.Remove(sb.Length - 1, 1);
sb.Append("]");
return sb.ToString();
}
}
The ASHX page gets called and returnd the following data:
[{id: 0,title:'test 1',start: '2010-06-07',allDay: false},{id: 2,title:'test 2',start: '2010-06-07',allDay: false}]
The call to the ASHX page does not display any results, but if I paste the values returned directly into the events it displays correctly. I am I have been trying to get this code to work for a day now and I can't see why the events are not getting set.
Any help or advise on how I can get this to work would be appreciated.
Steve
In case anyone stumbles across this problem. I tried all of the above solutions, but none of them worked.
For me, the problem was solved by using an older version of jquery. I switched from version 1.5.2 which was included in the fullcalendar package to version 1.3.2
Steve,
I ran into something similar -- it would render the events if the JSON was directly in the fullCalendar call, but it would not render the identicla JSON coming from an outside URL. I finally got it to work by modifying the JSON so that "id", "title", "start", "end", and "allDay" had the quotes around them.
So instead of this (to use your sample JSON):
[{id: 0,title:'test 1',start: '2010-06-07',allDay: false},{id: 2,title:'test 2',start: '2010-06-07',allDay: false}]
...I had this:
[{"id": 0,"title":"test 1","start": "2010-06-07","allDay": false},{"id": 2,"title":"test 2","start": "2010-06-07","allDay": false}]
Now, why it worked locally but not remotely, I can't say.
Your JSON data lost the end item:
{id: 0,title:'test 1',start: '2010-06-07',end: '2010-06-07',allDay: false}
Let's look at what we know and eliminate possibilities:
The ASHX page gets called and returnd the ... data:
So the server-side portion is working just fine, and the code to call out to the server side is working.
I paste the values returned directly into the events it displays correctly.
So the code that handles the response works correctly.
Logically we see here that code that connects your server response to your calendar's input is not working. Unfortunately, I'm not up on the jQuery fullCalendar method, but perhaps you're missing a callback declaration?
I think it might have something to do with your date values.
FullCalendar events from asp.net ASHX page not displaying is a correct solution to the issue.
And I used long format for dates.
And #Steve instead of StringAppending we can use :-
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
String sJSON = oSerializer.Serialize(evList);
evList being your list containing all events which has the essential properties like id,start,end,description,allDay etc..
I know this thread is an old thread,but this will be helpful to other users.
Just collating all the answers.
I struggled with this issue and resolved it using an .ashx handler as follows
My return class looks like…
public class Event
{
public Guid id { get; set; }
public string title { get; set; }
public string description { get; set; }
public long start { get; set; }
public long end { get; set; }
public bool allDay { get; set; }
}
Where DateTime values are converted to long values using…
private long ConvertToTimestamp(DateTime value)
{
long epoch = (value.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
return epoch;
}
And the ProcessRequest looks like…
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
DateTime start = new DateTime(1970, 1, 1);
DateTime end = new DateTime(1970, 1, 1);
try
{
start = start.AddSeconds(double.Parse(context.Request.QueryString["start"]));
end = end.AddSeconds(double.Parse(context.Request.QueryString["end"]));
}
catch
{
start = DateTime.Today;
end = DateTime.Today.AddDays(1);
}
List<Event> evList = new List<Event>();
using (CondoManagerLib.Linq.CondoDataContext Dc = new CondoManagerLib.Linq.CondoDataContext(AppCode.Common.CGlobals.DsnDB))
{
evList = (from P in Dc.DataDailySchedules
where P.DateBeg>=start && P.DateEnd<=end
select new Event
{ description = P.Description,
id = P.RecordGuid,
title = P.Reason,
start = ConvertToTimestamp(P.DateBeg),
end = ConvertToTimestamp(P.DateEnd),
allDay = IsAllDay(P.DateBeg, P.DateEnd)
}).ToList();
}
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
String sJSON = oSerializer.Serialize(evList);
context.Response.Write(sJSON);
}
And my Document Ready…
> $(document).ready(function () {
> $('#calendar').fullCalendar({
> header: { left: 'title', center: 'prev,today,next', right: 'month,agendaWeek,agendaDay' },
> editable: false,
> aspectRatio: 2.1,
> events: "CalendarEvents.ashx",
> eventRender: function (event, element) {
> element.qtip({
> content: event.description,
> position: { corner: { tooltip: 'topLeft', target: 'centerLeft'} },
> style: { border: { width: 1, radius: 3, color: '#000'},
> padding: 5,
> textAlign: 'center',
> tip: true,
> name: 'cream'
> }
> });
> }
> })
> });
The qTip pluging can be found at http://craigsworks.com/projects/qtip/
Hope this helps.

Resources