separate spaces for each user - c#

Sorry for my bad english. The application reads data from the accelerometer of the smartphone. He has a server in which when a smartphone is connected, a pair of id-data about the position in space is created. At the moment, data from all users come to the server. The task is to do the opposite: each time a user connects, a separate space is created that receives data from only one id.
Server code:
var express = require('express');
var compression = require('compression');
var http = require('http');
var path = require('path');
var socketIO = require('socket.io');
const port = process.env.PORT || 5000;
var cors = require('cors');
var app = express();
var server = http.Server(app);
var io = socketIO(server);
app.use(cors()) ;// Use this after the variable declaration
app.set('port', port);
app.use(compression());
app.use(express.static(__dirname + '/'));
app.use('/static', express.static(__dirname + '/static'));
// Routing
app.get('/', function (request, response) {
response.sendFile(path.join(__dirname, 'view.html'));
console.log(Object.keys(player_move).length);
if (Object.keys(player_move).length >= 1){
let data = {
id: socketId,
x: player_move[socketId].x,
z: player_move[socketId].z,
};
response.send(data);
console.log('connected');
}else{
response.send("no");
console.log('not connected');
};
});
app.use(express.static(__dirname + '/client/'));
// Routing
app.get('/view', function (request, response) {
response.sendFile(path.join(__dirname, '/client/index.html'));
});
server.listen(port, function () {
console.log('Старт сервера по адресу localhost:' + port);
console.log('Старт просмотра по адресу localhost: ' + port + ' /view');
});
var player_move = {};
var socketId;
io.on('connection', function (socket) {
socket.on('new player', function () {
console.log('new player');
socket.emit('ok');
});
socket.on('disconnect', function () {
});
socket.on('movement', function () {
console.log('movement');
console.log('player_move', player_move);
if (player_move[socketId]) {
let data = {
id: socketId,
x: player_move[socketId].x,
z: player_move[socketId].z,
};
socket.emit('ok', data);
}
});
socket.on('phone_data', function (data) {
console.log('phone_date', data);
socketId = socket.id;
player_move[socket.id] = {
x: data.x,
z: data.z
};
});
// GET method route
app.get('/', function (req, res) {
res.send('Contact');
console.log("est kontakt");
});
});
socket code:
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.Networking;
public class SocketController : MonoBehaviour
{
[SerializeField]
PlayerController player;
// Start is called before the first frame update
void Start()
{
StartCoroutine(GetRequest("http://plantgo.ru:5000"));
}
private void Awake()
{
//socket.url = "ws://127.0.0.1:5000/socket.io/?EIO=4&transport=websocket";
}
// Update is called once per frame
void Update()
{
}
//private IEnumerator Connector()
//{
// while (true)
// {
// socket.Emit("movement");
// yield return new WaitForSeconds(0.10f);
// }
// wait 1 seconds and continue
// }
class PlayerInfo
{
public string id;
public string x;
public string z;
}
IEnumerator GetRequest(string uri)
{
while (true)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
// Request and wait for the desired page.
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
}
else
{
Debug.Log(pages[page] + ":\nReceived: " + webRequest.downloadHandler.text);
if (webRequest.downloadHandler.text == "no")
{
continue;
}
else
{
PlayerInfo playerInfo = (PlayerInfo)JsonUtility.FromJson<PlayerInfo>(webRequest.downloadHandler.text);
Debug.Log(playerInfo);
player.PlayerMove(float.Parse(playerInfo.x, CultureInfo.InvariantCulture), float.Parse(playerInfo.z, CultureInfo.InvariantCulture));
}
}
}
//yield return new WaitForSeconds(0.1f);
}
}
}
when I start the server, several users can control the character at once, since they are in the same game space, it is necessary for each to have its own.

Related

Unity Firebase Null reference problem. After firebase authentication cannot send or recieve data in unity 2020.1.17f

Here is the code i am currently using to send data and receive data:
all the plugins have been downloaded to the latest version.we are trying to use firebase real time database is send and receive scores that have to be implemented in the game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using Firebase;
using Google;
using Firebase.Database;
using System.Linq;
public class LBnew : MonoBehaviour
{
private GoogleSignInConfiguration configuration;
private FirebaseAuth auth;
public string userID;
private DatabaseReference reference;
public string webClientId = " <your client id>";
private void Awake()
{
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
var dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
{
FirebaseApp app;
app = FirebaseApp.DefaultInstance;
Initialize();
}
else
{
Debug.Log(" not resolve firebase dependencies");
}
});
}
void Initialize()
{
configuration = new GoogleSignInConfiguration { WebClientId = webClientId, RequestEmail = true, RequestIdToken = true };
auth = FirebaseAuth.DefaultInstance;
userID = FirebaseAuth.DefaultInstance.CurrentUser.DisplayName;
reference = FirebaseDatabase.DefaultInstance.RootReference;
Debug.Log(" initiallized");
sendscore();
}
public void sendscore()
{
StartCoroutine(UpdateScore(10));
}
private IEnumerator UpdateScore(int _score)
{
Debug.Log(" Your userID " + userID);
//Set the currently logged in user score
var DBTask = reference.Child("user").Child(userID).Child("score").SetValueAsync(_score);
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register score task with {DBTask.Exception}");
// Debug.Log(" failed to reg score ");
}
else
{
Debug.Log(" success to reg score ");
}
StartCoroutine(LoadScoreboardData());
}
private IEnumerator LoadScoreboardData()
{
var DBTask = reference.Child("users").OrderByChild("score").GetValueAsync();
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $" load leaderboard task with {DBTask.Exception}");
Debug.Log(" srinu failed to load leaderScoreboardData ");
}
else
{
//Data has been retrieved
DataSnapshot snapshot = DBTask.Result;
//Destroy any existing scoreboard elements
//foreach (Transform child in scoreboardContent.transform)
//{
// Destroy(child.gameObject);
//}
//Loop through every users UID
//foreach (DataSnapshot childSnapshot in snapshot.Children)
//{
foreach (DataSnapshot childSnapshot in snapshot.Children.Reverse<DataSnapshot>())
{
// Instantiate new scoreboard elements
// GameObject scoreboardElement = Instantiate(scoreElement, scoreboardContent);
// scoreboardElement.GetComponent<LbAllList>().NewDataElement(username, Schoolname, score);
Debug.Log(" leaderScoreboardData " + childSnapshot.Child("score"));
}
//}
}
}
}
we are using unity 2020.1.17f as the version of unity
Any help would be appreciated thanks

Unity - Appending Data to Existing Document in Firestore

How do you add data to Firestore without over-writing previous data for the same key? For example, I want to add a document called "Player 1" to the Collections "Trajectory Log." I want to keep track of all the positions for Player 1 throughout one game into a single doc. In other words, how do you append data to a Firestore document?
This is the code I have for writing the data to Firestore. How do I make sure that the "data" is not over-written every time this code runs for the same user? Any help in how to implement this would be appreciated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Firestore;
using System.Threading.Tasks;
using UnityEngine.UI;
using System.Linq;
using System.Threading;
using Firebase.Auth;
public class TrajectoryToFirebase : MonoBehaviour
{
protected bool operationInProgress;
protected Task previousTask;
protected CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
// name of the collection container that documents get stored into
protected string collectionPath = "Trajectory Log";
protected string documentId = "";
public float samplingRate = 1f;
private System.DateTime dt;
private Vector3 lastpos = Vector3.zero;
private Quaternion lastrot = Quaternion.identity;
//public GameStats gameStats;
public Text text;
//Boilerplate taskmanagement code made by the Firebase People
////////////////////////////////////////////////////////////////////////////
class WaitForTaskCompletion : CustomYieldInstruction
{
Task task;
TrajectoryToFirebase dbManager;
protected CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
// Create an enumerator that waits for the specified task to complete.
public WaitForTaskCompletion(TrajectoryToFirebase dbManager, Task task)
{
dbManager.previousTask = task;
dbManager.operationInProgress = true;
this.dbManager = dbManager;
this.task = task;
}
// Wait for the task to complete.
public override bool keepWaiting
{
get
{
if (task.IsCompleted)
{
dbManager.operationInProgress = false;
dbManager.cancellationTokenSource = new CancellationTokenSource();
if (task.IsFaulted)
{
string s = task.Exception.ToString();
Debug.Log(s);
}
return false;
}
return true;
}
}
}
////////////////////////////////////////////////////////////////////////////
//Get the instance of the Firestore database
protected FirebaseFirestore db
{
get
{
return FirebaseFirestore.DefaultInstance;
}
}
private CollectionReference GetCollectionReference()
{
return db.Collection(collectionPath);
}
//Gets the reference to the docuement in Firstore
//Here I am just setting the document manually to the userID of the sign in user
private DocumentReference GetDocumentReference()
{
//documentId = FirebaseAuth.DefaultInstance.CurrentUser.UserId;
documentId = "User 1";
return GetCollectionReference().Document(documentId);
}
// Need function here that sends log data to firestore
// make this so that it checks to see if the document is null, and if it is not, it appends to the previous entry
// Firebase transaction?
public void TrackTrajectory()
{
Debug.Log("Trajectory Tracker Called");
if (transform.position != lastpos || transform.rotation != lastrot)
{
var data = new Dictionary<string, object>
{
{"Time", System.Math.Round(Time.time, 2)},
{"Pos X", System.Math.Round(transform.position.x, 3)},
{"Pos Y", System.Math.Round(transform.position.y, 3)},
{"Pos Z", System.Math.Round(transform.position.z, 3)},
{"Rot X", System.Math.Round(transform.rotation.x, 3)},
{"Rot Y", System.Math.Round(transform.rotation.y, 3)},
{"Rot Z", System.Math.Round(transform.rotation.z, 3)},
};
StartCoroutine(WriteDoc(GetDocumentReference(), data));
Debug.Log("I recorded trajectory data");
// append here? firestore transaction?
lastpos = transform.position;
lastrot = transform.rotation;
}
}
// starts "timer" to start recording position and orientation?
public void Start()
{
dt = System.DateTime.Now;
Debug.Log(dt.ToString("yyyy-MM-dd-H-mm-ss"));
InvokeRepeating("TrackTrajectory", 0f, 1f / samplingRate);
}
// *** what does this do?
public void readDataButton()
{
StartCoroutine(ReadDoc(GetDocumentReference()));
}
private static string DictToString(IDictionary<string, object> d)
{
return "{ " + d
.Select(kv => "(" + kv.Key + ", " + kv.Value + ")")
.Aggregate("", (current, next) => current + next + ", ")
+ "}";
}
//Writes the data
private IEnumerator WriteDoc(DocumentReference doc, IDictionary<string, object> data)
{
Task setTask = doc.SetAsync(data);
yield return new WaitForTaskCompletion(this, setTask);
if (!(setTask.IsFaulted || setTask.IsCanceled))
{
Debug.Log("Data written");
}
else
{
Debug.Log("Error");
}
}
private IEnumerator ReadDoc(DocumentReference doc)
{
Task<DocumentSnapshot> getTask = doc.GetSnapshotAsync();
yield return new WaitForTaskCompletion(this, getTask);
if (!(getTask.IsFaulted || getTask.IsCanceled))
{
DocumentSnapshot snap = getTask.Result;
IDictionary<string, object> resultData = snap.ToDictionary();
text.text = DictToString(resultData);
Debug.Log("Data read");
}
else
{
text.text = "Error";
}
}
}
You have to use UpdateAsync() instead of SetAsync()
You can read here the Firebase documentation on updates

How can I scan a document using ASP.net MVC 5 with the help of Twain

Please help me out by sharing the step by step procedure to achieve the scanning functionality using Twain in ASP.Net MVC5. Thank you
Solution is here:
In ASP.Net/Core Project you send message to call winform project:
var start = function () {
var i = 0;
var wsImpl = window.WebSocket || window.MozWebSocket;
window.ws = new wsImpl('ws://localhost:8181/');
ws.onmessage = function (e) {
$('#submit').hide();
$('#scanBtn').hide();
$('.loader').show();
if (typeof e.data === "string") {
//IF Received Data is String
}
else if (e.data instanceof ArrayBuffer) {
//IF Received Data is ArrayBuffer
}
else if (e.data instanceof Blob) {
i++;
var f = e.data;
f.name = "File" + i;
storedFiles.push(f);
formdata.append(f.name, f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div class=\"col-sm-2 text-center\"
style=\"border: 1px solid black; margin-left: 2px;\"><img
height=\"200px\" width=\"200px\" src=\"" + e.target.result + "\"
data-file='" + f.name + "' class='selFile' title='Click to
remove'><br/>" + i + "</div>";
selDiv.append(html);
$('#submit').show();
$('#scanBtn').show();
$('.loader').hide();
}
reader.readAsDataURL(f);
}
};
ws.onopen = function () {
//Do whatever u want when connected succesfully
};
ws.onclose = function () {
$('.dalert').modal('show');
};
}
window.onload = start;
function scanImage() {
ws.send("1100");
};
https://javascript.info/websocket
In Winforms Project you scan document and send graphic data back to Asp.Net/Core project:
public partial class Form1 : Form
{
ImageCodecInfo _tiffCodecInfo;
TwainSession _twain;
bool _stopScan;
bool _loadingCaps;
List allSockets;
WebSocketServer server;
public Form1()
{
InitializeComponent();
if (NTwain.PlatformInfo.Current.IsApp64Bit)
{
Text = Text + " (64bit)";
}
else
{
Text = Text + " (32bit)";
}
foreach (var enc in ImageCodecInfo.GetImageEncoders())
{
if (enc.MimeType == "image/tiff") { _tiffCodecInfo = enc; break; }
}
this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
allSockets = new List<IWebSocketConnection>();
server = new WebSocketServer("ws://0.0.0.0:8181");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine("Open!");
allSockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
allSockets.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "1100")
{
this.Invoke(new Action(()=> {
this.WindowState = FormWindowState.Normal;
}));
}
};
});
}
Link to project.
https://github.com/mgriit/ScanAppForWeb
You can remake this project, as you want.
At this moment, none of the browsers support scanning out of the box. You need to use a third-party library (not part of Microsoft's .NET core components). Below example uses Scanner.js, which is a product offered by our company:
Enable Scanning from TWAIN Scanners to ASP.NET Pages: Step by Step
Below steps use Scanner.js as example; they may differ for other products.
1) Include the scanning library in your HTML code:
<script type="text/javascript" src="//asprise.azureedge.net/scannerjs/scanner.js"></script>
2) Add a button to trigger the scanning process:
function scanToJpg() {
scanner.scan(displayImagesOnPage,
{
"twain_cap_setting" : {
"ICAP_PIXELTYPE" : "TWPT_RGB", // Color
"ICAP_XRESOLUTION" : "100", // DPI: 100
"ICAP_YRESOLUTION" : "100",
"ICAP_SUPPORTEDSIZES" : "TWSS_USLETTER" // Paper size: TWSS_USLETTER, TWSS_A4, ...
},
"output_settings" :
[
{
"type" : "return-base64",
"format" : "jpg"
}
]
}
);
}
3) Handle the scan result - display, upload, etc.
Below code creates an img element for each image scanned to display on the current web page:
/** Processes the scan result */
function displayImagesOnPage(successful, mesg, response) {
var scannedImages = scanner.getScannedImage(response, true, false); // returns an array of ScannedImage
for(var i = 0; (scannedImages instanceof Array) && i < scannedImages.length; i++) {
var scannedImage = scannedImages[i];
processScannedImage(scannedImage);
}
}
/** Images scanned so far. */
var imagesScanned = [];
/** Processes a ScannedImage */
function processScannedImage(scannedImage) {
imagesScanned.push(scannedImage);
var elementImg = createDomElementFromModel( {
'name': 'img',
'attributes': {
'class': 'scanned',
'src': scannedImage.src
}
});
document.getElementById('images').appendChild(elementImg);
}
For examples of scanning into PDF formats and direct uploading, please visit the code repository: https://github.com/Asprise/scannerjs.javascript-scanner-access-in-browsers-chrome-ie.scanner.js

Cannot get WebSocket request by using Microsoft Owiin selfhost

I found the example on the internet. Somehow, I cannot make it run correctly.
I did a lot of search but still cannot find out what is the mistake?!
Hope, someone can help to figure it out.
Server code:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Tracing;
using HTek.Core.MEF;
using HTek.Core.Server.Web.MEF;
using HTek.Core.Server.Web.Tracing;
using Microsoft.Owin;
using Owin;
// http://owin.org/extensions/owin-WebSocket-Extension-v0.4.0.htm
using WebSocketAccept = System.Action<System.Collections.Generic.IDictionary<string, object>, // options
System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>>; // callback
using WebSocketCloseAsync = System.Func<int /* closeStatus */,
string /* closeDescription */,
System.Threading.CancellationToken /* cancel */,
System.Threading.Tasks.Task>;
using WebSocketReceiveAsync = System.Func<System.ArraySegment<byte> /* data */,
System.Threading.CancellationToken /* cancel */, System.Threading.Tasks.Task<System.Tuple<int /* messageType */,
bool /* endOfMessage */,
int /* count */>>>;
using WebSocketSendAsync = System.Func<System.ArraySegment<byte> /* data */,
int /* messageType */,
bool /* endOfMessage */,
System.Threading.CancellationToken /* cancel */,
System.Threading.Tasks.Task>;
using WebSocketReceiveResult = System.Tuple<int, // type
bool, // end of message?
int>; // count
namespace Server.WebApi
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var webApiConfiguration = ConfigureWebApi();
// Use the extension method provided by the WebApi.Owin library:
app.UseWebApi((HttpConfiguration)webApiConfiguration);
app.Use(UpgradeToWebSockets);
}
private HttpConfiguration ConfigureWebApi()
{
WebComposition provider = new WebComposition();
Composition.SetCurrentProvider(provider);
Composition.Start();
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new
{
id = RouteParameter.Optional
});
provider.ConfigureWebApi(config);
//// tracing config
config.Services.Replace(typeof(ITraceWriter), new Tracer());
return config;
}
private static Task UpgradeToWebSockets(IOwinContext context, Func<Task> next)
{
WebSocketAccept accept = context.Get<WebSocketAccept>("websocket.Accept");
if (accept == null)
{
// Not a websocket request
return next();
}
accept(null, WebSocketEcho);
return Task.FromResult<object>(null);
}
private static async Task WebSocketEcho(IDictionary<string, object> websocketContext)
{
var sendAsync = (WebSocketSendAsync)websocketContext["websocket.SendAsync"];
var receiveAsync = (WebSocketReceiveAsync)websocketContext["websocket.ReceiveAsync"];
var closeAsync = (WebSocketCloseAsync)websocketContext["websocket.CloseAsync"];
var callCancelled = (CancellationToken)websocketContext["websocket.CallCancelled"];
byte[] buffer = new byte[1024];
WebSocketReceiveResult received = await receiveAsync(new ArraySegment<byte>(buffer), callCancelled);
object status;
while (!websocketContext.TryGetValue("websocket.ClientCloseStatus", out status)
|| (int)status == 0)
{
// Echo anything we receive
await
sendAsync(new ArraySegment<byte>(buffer, 0, received.Item3),
received.Item1,
received.Item2,
callCancelled);
received = await receiveAsync(new ArraySegment<byte>(buffer), callCancelled);
}
await
closeAsync((int)websocketContext["websocket.ClientCloseStatus"],
(string)websocketContext["websocket.ClientCloseDescription"],
callCancelled);
}
}
}
private static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Logger<Program>.InfoFormat("Server running on {0}", baseAddress);
Console.ReadLine();
}
}
And HTML client:
var wsUri = "ws://localhost:9000";
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
websocket.close();
}
function onError(evt)
{
writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
Everything looks good. Excepted, 'accept'(in 'UpgradeToWebSockets') is always NULL.
WebSocket is not supports in old Windows releases such as Windows 7.
You might upgrade to a newer release such as Windows 10.

Call back from server to client

I am using ASP.NET MVC 4 application, I need to Display messages in the Client, by sending messages from Controller to Client.
My requirement is user click a button in UI and i will process the files on the server and Display message in UI on end of each foreach file i process. i need to show the File names in the Client Using ASP.NET MVC.
Can any one Help how to show the messages in the Client by calling client method from server on for-each loop each time.
I am able to call the controller and end of each controller I am sending final message to UI, but how to send on each foreach loop iteration?
Try this:
Script method to update progress based on predefined interval you want
Controller:
public class HomeController : Controller
{
private static IDictionary<Guid, int> tasks = new Dictionary<Guid, int>();
public ActionResult Index()
{
return View();
}
public ActionResult Start()
{
var taskId = Guid.NewGuid();
tasks.Add(taskId, 0);
Task.Factory.StartNew(() =>
{
for (var i = 0; i <= 100; i++)
{
tasks[taskId] = i; // update task progress
Thread.Sleep(50); // simulate long running operation
}
tasks.Remove(taskId);
});
return Json(taskId);
}
public ActionResult Progress(Guid id)
{
return Json(tasks.Keys.Contains(id) ? tasks[id] : 100);
}
}
View:
<script type="text/javascript">
function updateMonitor(taskId, status) {
$("#" + taskId).html("Task [" + taskId + "]: " + status);
}
$(function () {
$("#start").click(function (e) {
e.preventDefault();
$.post("Home/Start", {}, function (taskId) {
// Init monitors
$("#monitors").append($("<p id='" + taskId + "'/>"));
updateMonitor(taskId, "Started");
// Periodically update monitors
var intervalId = setInterval(function () {
$.post("Home/Progress", { id: taskId }, function (progress) {
if (progress >= 100) {
updateMonitor(taskId, "Completed");
clearInterval(intervalId);
} else {
updateMonitor(taskId, progress + "%");
}
});
}, 100);
});
});
});
Start new task …
You have to write an ActionResult that progressively write result to the response. so you can show the user some data in every foreach loop iteration. I have written a simple ActionResult that writes a number every 2 seconds:
public class ProgressiveResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
for (int i = 0; i < 20; i++)
{
context.HttpContext.Response.Write(i.ToString());
Thread.Sleep(2000);
context.HttpContext.Response.Flush();
}
context.HttpContext.Response.End();
}
}
and this is an action that returns this result:
public ActionResult LongProcess()
{
return new ProgressiveResult();
}
So you can write an ActionResult and write your foreach code in ExecuteResult method.
UPDATE:
You can make this call with an Ajax request and return result with a simple code like the following code:
var result = "";
function showResult() {
if (result !== oReq.responseText) {
result = oReq.responseText;
console.log(result);
}
}
var oReq = new XMLHttpRequest();
oReq.open("get", "/Home/LongProcess", true);
oReq.send();
setInterval(showResult, 1000);

Categories

Resources