When running on my local machine, it works fine. But when hosted in a server, my ajax call didn't hit the controller and it gives me error 500 with message:
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond..."
My ajax:
$.ajax({
url: '#Url.Action("Login", "Roster")',
type: 'POST',
data: {
Email: $('#txtUsername').val(),
Password: $('#txtPassword').val(),
},
...
)
in my Roster controller
public async Task<ActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
string tokenAddress = URI + "token";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(tokenAddress);
var account = new Dictionary<string, string>
{
{"username", model.Email },
{"password", model.Password },
{"grant_type", "password" }
};
}
}
}
Related
Im using SignalR Core and ASPNET Core 2.2 and try to to send message to single user. for all user it's working fine.
Csharp code
[HubMethodName("SendMessageToUser")]
public Task DirectMessage(string user, string message)
{
//eg.user = abcd#gmail.com
return Clients.User(user).SendAsync("ReceiveMessage", message);
}
JS code
connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g,"<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
You can send message to specific user using their connection id so
I need to create a hub like this. The GetConnectionId will return the connect id of that user when they connect to signalR hub
public class ConnectionHub : Hub
{
public async Task Send(string userId)
{
var message = $"Send message to you with user id {userId}";
await Clients.Client(userId).SendAsync("ReceiveMessage", message);
}
public string GetConnectionId()
{
return Context.ConnectionId;
}
}
Then in startup.cs
services.AddSignalR();
app.UseSignalR(routes =>
{
routes.MapHub<ConnectionHub>("/connectionHub");
});
Then the client side code
(function () {
var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();
connection.start().then(function () {
console.log("connected");
connection.invoke('getConnectionId')
.then(function (connectionId) {
sessionStorage.setItem('conectionId', connectionId);
// Send the connectionId to controller
}).catch(err => console.error(err.toString()));;
});
$("#sendmessage").click(function () {
var connectionId = sessionStorage.getItem('conectionId');
connection.invoke("Send", connectionId);
});
connection.on("ReceiveMessage", function (message) {
console.log(message);
});
})();
First I invoke getConnectionId in the hub to get user connection id then I can send message to specific user using their connection id.
Hope that help
Im trying to work with an object (VideoInfo) in several Action methods. A form sends a viewmodel with a video file to the Upload method in VideoController. It uploads the video and returns a generated guid. When the callback has returned, a new ajax call is made to the Convert method which returns the guid. As seen in the javascript part of Create.cshtml it makes two other Ajax calls, one to the Progress method and one to the Azure method.
When trying to fetch the VideoInfo object in the Azure method and the Progress method, videoInfo is null. Though it successfully retains the data between the Upload method and Convert method. Im using TempData.Peek() so that it shouldnt mark it for deletion.
I can see that the Upload and Convert method is using the same instance of VideoController, where as the Progress and Azure method uses another instance, I guess this could have to do with the problem.
InstanceId when running Upload method: 23ef96fa-c746-4722-ad07-e9e40fc95f29
InstanceId when running Convert method: 23ef96fa-c746-4722-ad07-e9e40fc95f29
InstanceId when running Progress method: 0aba24b2-ccb8-434d-a27d-cc66cb52c466
InstanceId when running Azure method: 0aba24b2-ccb8-434d-a27d-cc66cb52c466
How can I retain data between my Ajax calls in the VideoController?
Why is the instance id same for the first two calls but then it changes?
VideoController.cs
using System;
namespace MediaPortal.Controllers
{
[Authorize(Roles = "Admin")]
public class VideoController : Controller
{
private static Guid InstanceId { get; }
static VideoController()
{
InstanceId = Guid.NewGuid();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(CreateVideoViewModel model)
{
if (ModelState.IsValid)
{
if (model.File != null)
{
Debug.WriteLine("Upload method InstanceId: " + InstanceId.ToString());
// ...
TempData[videoInfo.Id] = videoInfo;
videoInfo.cvvm.File.SaveAs(videoInfo.TempPath);
return Json(new { Successfull = true, Id = videoInfo.Id });
}
return null;
}
return null;
}
[HttpPost]
public ActionResult Convert(string id)
{
Debug.WriteLine("Convert method InstanceId: " + InstanceId.ToString());
// Create new object of FFMpegConvertor
var converter = new FFMpegConverter();
VideoInfo videoInfo = (VideoInfo)TempData.Peek(id);
// ...
return Json(new { Successfull = true, Id = videoInfo.Id });
}
[HttpPost]
public ActionResult Azure(string id)
{
Debug.WriteLine("Azure method InstanceId: " + InstanceId.ToString());
VideoInfo videoInfo = (VideoInfo)TempData[id];
// ...
if (videoUpload != null && thumbnailUpload != null)
{
Video video = new Video
{
Id = videoInfo.Id.ToString(),
Name = videoInfo.cvvm.Name,
ProjectId = videoInfo.cvvm.ProjectId,
Type = "mp4",
VideoUri = videoUpload.Uri.ToString(),
ThumbnailUri = thumbnailUpload.Uri.ToString()
};
db.Videos.Add(video);
db.SaveChanges();
return Json(new { Successful = true, Data = Url.Action("Index", new { projectId = videoInfo.cvvm.ProjectId }) });
}
return null;
}
[HttpPost]
public JsonResult Progress(string id)
{
Debug.WriteLine("Progress method InstanceId: " + InstanceId.ToString());
try
{
VideoInfo videoInfo = (VideoInfo)TempData.Peek(id);
return Json(new { Data = videoInfo.Progress });
}
catch
{
return Json(new { Data = "No Video Information in Dictionary for Id: " + id });
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Create.cshtml (JQuery/Ajax)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$.noConflict();
jQuery(document).ready(function ($) {
var bar = $('.progress-bar');
var percent = $('.percent');
$('#Myform').ajaxForm({
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function (uploadStatus) {
console.log("Upload finished for video with Id: " + JSON.parse(uploadStatus.responseText).Id);
setTimeout(function () { progress(uploadStatus) }, 1000);
$.ajax({
type: "POST",
url: '#Url.Action("Convert", "Video")?id=' + JSON.parse(uploadStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (convertStatus) {
console.log("Conversion finished for video with Id: " + JSON.parse(convertStatus.responseText).Id);
$.ajax({
type: "POST",
url: '#Url.Action("Azure", "Video")?id=' + JSON.parse(convertStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (azureStatus) {
window.location.href = JSON.parse(azureStatus.responseText).Data;
}
});
}
});
}
});
function progress(uploadStatus) {
$.ajax({
type: "POST",
url: '#Url.Action("Progress", "Video")?id=' + JSON.parse(uploadStatus.responseText).Id,
dataType: "json",
contentType: "application/json; charset=utf-8",
complete: function (progressStatus) {
console.log("Progress: " + JSON.parse(progressStatus.responseText).Data);
if (JSON.parse(progressStatus.responseText).Data < 100) {
setTimeout(function () { progress(uploadStatus) }, 1000);
}
else if (JSON.parse(progressStatus.responseText).Data >= 100) {
console.log("Video Conversion Completed");
}
else {
console.log("Something went wrong");
}
}
})
}
});
</script>
It seems IIS Express was the problem. I cant say why though. I realized this because when I deployed the project to my production server in Azure it all worked fine.
So instead of using IIS Express I installed IIS on my development machine, works perfectly after that.
I know this question has been asked alot and i tried every single solution, but it just won't work for me.
I have a ASP WEB API which looks like this:
private string uploadFolder = ("~/uploads");
[HttpPost]
public async Task<HttpResponseMessage> PostFile()
{
var provider = new MultipartFormDataStreamProvider(uploadFolder);
try
{
StringBuilder sb = new StringBuilder();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var key in provider.FormData.AllKeys)
{
foreach (var a in provider.FormData.GetValues(key))
{
sb.Append(a.ToString());
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return null;
}
}
As you can see, it is a pretty simple one that is able too accept multipart/form-data.
The Ajax code i am using is the following:
$("#form1").submit(function (e) {
var formData = $(this).serializeArray();
var submitUrl = "api/upload";
$.ajax({
url: submitUrl,
type: "POST",
data: formData,
success: function() {
//window.location("Upload.html");
alert("Success");
},
error: function() {
alert("Error");
}
});
e.preventDefault();
});
$(this).submit();
The form i am sending only contains a textfield and a submit button. When i click the submit button, i get an error: 405 Method not allowed.
When i insert the script into chrome and run it from there it gets to the API, but on
await Request.Content.ReadAsMultipartAsync(provider)
it throws an exception in my catch.
Any idea what could cause this?
I am creating a CRUD application, My application is getting a string from from a Kendo input box, and will need to send it to my controller which is expecting a string that I am getting from my Jquery call. However, the string is not getting to my controller. I have tried various ways and I am not able to send it through my Transport. I have put break point and I can confirm that the value is being picked up in my Kendo Observable.
My Datasource
var client = new kendo.data.DataSource({
transport: {
read: {
url: "Client/SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json",
},
My Controller
public ActionResult SearchClient()
{
return View();
}
[HttpPost]
public ActionResult SearchClient(string name)
{
Repo repo = new Repo();
var result = repo.GetClient();
return Json(new
{
list = result,
count = result.Count
}, JsonRequestBehavior.AllowGet);
}
This is my Kendo Observable
var viewModel = kendo.observable({
client: {
clientName: "",
clientNumber: "",
clientType: "",
},
dropdownlist: ["HCC", "Tax", "Audit", "Advisory"],
create: function (e) {
var userRequest = $("#clientname").val();
if (userRequest) {
client.read(userRequest);
}
if (!userRequest)
alert("Please Enter Client Name")
}
});
Search Client method wants POST, not GET? The default will be GET. Either change your api method to use HttpGet, or change the transport to method: "post" for read.
var client = new kendo.data.DataSource({
transport: {
read: {
url: "Client/SearchClient",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "post"
},
I am developing a windows 8.1 app using Parse as back-end, I want to delete a user from windows app,How to achieve this
You can delete a user using Cloud Code.
Parse.Cloud.define("deleteUser", function(request, response) {
var query = new Parse.Query(Parse.User);
query.equalTo("objectId", reques.parsams.userId);
query.first({
success: function(result) {
result.destroy({
success: function() {
response.success("Success");
},
error: function(error) {
response.error("Could not delete object");
}
});
},
error: function() {
response.error("Could not run query");
}
});
});
You'd call the above function in Windows 8, where xxxxxxx is the objectId of the user you'd like to delete.
IDictionary<string, object> params = new Dictionary<string, object>
{
{ "userId", "xxxxxxx" }
};
var result = await ParseCloud.CallFunctionAsync<IDictionary<string, object>>("deleteUser", params);