Live update map - Timer class - c# - c#

I'm building a project with asp.net.
Part of the the project is a view (using google maps api) that is showing the the status of the parking lots with maerkers on the map.
Im using JSON file to create the markers.
Moreover, Im using arduino with some sensors that are indicated of the parking lot status.
I want that this Json will be update (override the previous) every 2 seconds (so that if a car enters the parking lot and now its full - it will present on the map as full)
I have 2 functions that creates this Json's and I want to call them every 2 seconds as I said before.
I could not do it. I'll be glad to receive your help.
The name of the view page: "TotalPs".
This is the controller in which the relevant function is located:
public ActionResult TotalPs()
{
ViewBag.Message = "TotalPs";
return View();
}
public ActionResult TotalPData()
{
ReadArduino(); //READ THE DATA FROM THE ARDUINO
callA(); // CREATES THE FIRST JSON
callB(); // CREATES THE 2ND JSON
var totalQueryParkingLot =
from lot in db.parkingLots
orderby lot.PricePerHour
select lot;
return Json(totalQueryParkingLot);
}
public void callA()
{
var totalQueryParkingLot =
from lot in db.parkingLots
orderby lot.PricePerHour
select lot;
var data2 = totalQueryParkingLot.ToList();
var jsonString2 = JsonConvert.SerializeObject(data2);
if (jsonString2 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJsonPL.json"), jsonString2);
}
public void callB()
{
var FreeQueryParkingLot =
from pub in db.publicParkings
orderby pub.PricePerHourpublicParking
select pub;
var data8 = FreeQueryParkingLot.ToList();
var jsonString3 = JsonConvert.SerializeObject(data8);
if (jsonString3 != null)
{
if (!Directory.Exists(Server.MapPath("~/Content/")))
{
Directory.CreateDirectory(Server.MapPath("~/Content/"));
}
}
System.IO.File.WriteAllText(Server.MapPath("~/Content/TotalJsonPU.json"), jsonString3);
}
public void ReadArduino()
{
SerialPort port = new SerialPort("COM3", 9600);
port.BaudRate = 9600;
port.PortName = "COM3";
port.Open();
bool status1 = true;
bool status2 = true;
bool status3 = true;
char[] arr = new char[4];
String data_arduino = port.ReadLine();
for (int i = 0; i < arr.Length; i++)
{
char first = data_arduino[i];
arr[i] = first;
}
int space = arr[0] - 48;
var arduinoQuery1 = from b in db.parkingLots where b.parkingLotID == 22 select b;
foreach (parkingLot parkingLot in arduinoQuery1)
{
parkingLot.freeSpaces = space;
}
db.SaveChanges();
}
In the view I call the function TotalPData() that is calling to the other functions.
Tnx!!

I am assuming that you are applying a ajax call to retrieve json data. So, you can assign interval using setInterval to execute ajax call periodically.
var interval = setInterval(ajaxCall, 5000); //5000 MS == 5 seconds
function ajaxCall() {
clearInterval(interval);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'Controller/TotalPData',
dataType: "json",
success: function (response) {
interval = setInterval(ajaxCall, 5000);
// Do something
},
error: function (a, b, c) {
}
});
}
Also, It could be better to use SignalR to perform this kind of requirements.
SignalR

Related

Twilio on Call-Connect or Hangup get call details

I am using ASP.NET MVC Web calling with Twilio
Here is my Connect function
function callCustomer(phoneNumber) {
updateCallStatus("Calling " + phoneNumber + "...");
phoneNumber = phoneNumber.replace(/ /g, '');
var params = { To: phoneNumber };
Twilio.Device.connect(params);
}
Here is my Hangup function
function hangUp() {
Twilio.Device.disconnectAll();
}
Here is my TwiML Bin
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Dial callerId="++516xxx9999" record="record-from-answer">{{To}}</Dial>
</Response>
I am using Twilio client v1.6
//media.twiliocdn.com/sdk/js/client/v1.6/twilio.min.js
I want to collect complete information of each call as I connect to call or as I hang up the call like Call Duration, Call Sid, Record Sid, Call To, and other. Then with that information I would like implement play recorded call in my application.
I believe one way of doing it is set CALL STATUS CHANGES under Voice & Fax and receive all params.
This is how I ended up handling it.
/* Callback for when a call ends */
Twilio.Device.disconnect(function (connection) {
console.log(connection);
// Disable the hangup button and enable the call buttons
hangUpButton.prop("disabled", true);
callCustomerButtons.prop("disabled", false);
callSupportButton.prop("disabled", false);
updateCallStatus("Ready");
addCallLog(connection.parameters.CallSid);
});
addCallLog function
function addCallLog(id) {
var type = "";
var entityId = Number($("#Id").val());
$.ajax({
url: "/Phone/AddCallLog?callId=" + id,
type: "POST",
contentType: "application/json;",
success: function (data) {
// Handle Success Event
},
error: function (data) {
// Handle Error Event
}
});
}
Controller Method
[HttpPost]
public ActionResult AddCallLog(string callId,string type,int entityId)
{
TwilioClient.Init(_callSetting.Twilio.AccountSid, _callSetting.Twilio.Authtoken);
var records = CallResource.Read(parentCallSid: callId).ToList();
if (records.Any())
{
var callResource= records[0];
var parentRecord = CallResource.Fetch(pathSid: callId);
if (callResource.Status.ToString().Equals("completed", StringComparison.OrdinalIgnoreCase))
{
CallRecord callRecord = new CallRecord
{
EntityKey = entityId,
EntityType = type,
CallDateTimeUtc = callResource.DateCreated ?? DateTime.UtcNow,
CallSId = callResource.Sid,
ParentCallSId = callResource.ParentCallSid,
CalledById = _operatingUser.Id,
DurationInSeconds = parentRecord==null? Convert.ToDouble(callResource.Duration): Convert.ToDouble(parentRecord.Duration),
ToPhone = callResource.To,
CompanyId = _operatingUser.CompanyId
};
var callRecordResult= _callRecordService.Add(callRecord);
var recording = RecordingResource.Read(callSid: callId).ToList();
if (!recording.Any()) return Json(true);
foreach (RecordingResource recordingResource in recording)
{
using (var client = new WebClient())
{
var url =
"https://api.twilio.com" + recordingResource.Uri.Replace(".json", ".mp3");
var content = client.DownloadData(url);
CallRecordMedia callRecordMedia = new CallRecordMedia
{
CallRecordId = callRecordResult.Id,
ContentType = "audio/mpeg",
RecordingSId = recordingResource.Sid,
RecordingCallSId = recordingResource.CallSid,
FileType = "mp3",
Data = content,
Price = Convert.ToDouble(recordingResource.Price),
PriceUnit = recordingResource.PriceUnit,
DurationInSeconds = Convert.ToDouble(recordingResource.Duration)
};
_callRecordService.AddCallRecording(callRecordMedia);
}
}
}
}
return Json(true);
}

OpenXML not creating document on production, but fine in Dev

I have launched a new application at work. We create letters using OpenXML which works flawlessly on Dev, but on production the solution is not returning.
$("#createLetter").on("click", CreateLetter);
function CreateLetter() {
$.ajax({
type: "POST",
url: "/Letters/CreateLetter",
data: {
EntityType: "#overview.EntityType",
EntityId: #overview.EntityId,
Recipient: $("#Recipient").val(),
TemplatesLocation: $("#templatePath").val(),
SaveAs: $("#saveAs").val()
},
async: false,
success: openLetter
});
}
function openLetter(data) {
openFile(data);
window.location.reload(false);
}
Controller Method:
[ValidateInput(false)]
[HttpPost]
public JsonResult CreateLetter(CreateLetter input)
{
Recipient obj = logic.SplitRecipientInput(input.Recipient);
input.RecipientId = obj.RecipientId;
input.RecipientType = obj.Type;
input.Username = Helpers.GetLoggedInUser();
var x = logic.CreateLetter(input);
if (x.Success == 1)
{
return Json(x.Data, JsonRequestBehavior.AllowGet);
}
else
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
}
Consumption Logic:
public CreatedLetter CreateLetter(CreateLetter input)
{
CreatedLetter response = new CreatedLetter();
Parameters.Add("TemplatePath", GetApiValue(input.TemplatesLocation));
Parameters.Add("EntityType", GetApiValue(input.EntityType));
Parameters.Add("EntityId", GetApiValue(input.EntityId));
Parameters.Add("RecipientId", GetApiValue(input.RecipientId));
Parameters.Add("RecipientType", GetApiValue(input.RecipientType));
Parameters.Add("Username", GetApiValue(input.Username));
Parameters.Add("SaveAs", GetApiValue(input.SaveAs));
response = Api.WebRequest<CreatedLetter>("CreateLetters", Parameters, Method.POST) as CreatedLetter;
return response;
}
API Controller method:
[ActionName("CreateLetter")]
[HttpPost]
public ApiResponse CreateLetter(LetterCreateInput input)
{
try
{
LetterTemplateLogic logic = new LetterTemplateLogic();
Random r = new Random();
var randomId = r.Next(100000, 999999);
string fileName = string.Format("{0} - {1}", randomId, input.SaveAs);
input.SaveAs = fileName;
// Get all objects for Letter
List<object> objs = logic.TemplateObjectsRetriever(input.EntityId, input.EntityType, input.Username, randomId);
objs.Add(logic.GetRecipient(input.RecipientId, input.RecipientType));
// Get save location
string saveLocation = logic.LetterLocationResolver(input.EntityId, input.EntityType);
var data = logic.OpenAndUpdateTemplate(objs, input.TemplatePath, input.SaveAs, saveLocation, FileExtension);
AttachmentInput letterAttachment = new AttachmentInput();
letterAttachment.Id = input.EntityId;
letterAttachment.FileTypeId = 1;
letterAttachment.Path = data;
letterAttachment.Username = input.Username;
letterAttachment.Description = fileName;
letterAttachment.EntityType = input.EntityType;
logic.InsertLetterAttachment(letterAttachment);
return ApiResponse.Return(data);
}
catch (Exception ex)
{
return ApiResponse.Error(ex);
}
}
This returns literally nothing on production. No errors in the console, no errors from the API which logs erroneous calls. I was hoping someone could make a suggestion?
Thanks.

SignalR client method fires multiple times

I'm playing around with SignalR, trying to create a heatmap overlay on a Google map. However, my method is firing multiple times and I can't figure out why.
The data returned from SQL is formatted into JSON, so I can plot it onto the overlay using this plugin - http://www.patrick-wied.at/static/heatmapjs/
I've been following the web api demo found at http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency but without luck. My code is below:
View (snipped to show relevant code)
<script type="text/javascript">
var map;
var heatmap;
var testData;
$(function () {
// Proxy created on the fly
var sales = $.connection.productSalesHub;
// Declare a function on the product sales hub so the server can invoke it
sales.client.displaySales = function () {
getSalesData();
};
// Start the connection
$.connection.hub.start();
getSalesData();
});
function getSalesData() {
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json'
})
.done(function (res) {
if (res.length > 0) {
var myLatlng = new google.maps.LatLng(48.3333, 16.35);
// sorry - this demo is a beta
// there is lots of work todo
// but I don't have enough time for eg redrawing on dragrelease right now
var myOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE,
disableDefaultUI: false,
scrollwheel: true,
draggable: true,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
disableDoubleClickZoom: false
};
testData = res;
map = new google.maps.Map(document.getElementById("heatmapArea"), myOptions);
heatmap = new HeatmapOverlay(map, {
"radius": 15,
"visible": true,
"opacity": 60,
legend: {
position: 'br',
title: 'Amount of items sold'
}
});
google.maps.event.addListenerOnce(map, "idle", function() {
heatmap.setDataSet(testData);
});
}
})
.fail(function () {
alert("error");
})
.always(function() {
alert("complete");
});
}
</script>
Values controller:
public class ValuesController : ApiController
{
ProductSalesRepository repo = new ProductSalesRepository();
// GET api/values
public JObject Get()
{
var data = repo.GetProductSalesData();
return repo.BuildJson(data);
}
}
ProductSalesHub.cs
public class ProductSalesHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ProductSalesHub>();
context.Clients.All.displaySales();
}
}
And lastly, my repo
public class ProductSalesRepository
{
public IEnumerable<ProductSalesInfo> GetProductSalesData()
{
using (
var connection =
new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT top 10 [lat],[lng],[count]
FROM [dbo].[ProductSales]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new ProductSalesInfo()
{
Lat = x.GetString(0),
Long = x.GetString(1),
Count = x.GetInt32(2)
}).ToList();
}
}
}
public JObject BuildJson(IEnumerable<ProductSalesInfo> data )
{
IEnumerable<ProductSalesInfo> productSalesInfos = data as List<ProductSalesInfo> ?? data.ToList();
int max = (from d in productSalesInfos.ToList() select d.Count).Max();
JObject o = new JObject(
new JProperty("max", max),
new JProperty("data",
new JArray(from d in productSalesInfos
select new JObject(
new JProperty("lat", d.Lat),
new JProperty("lng", d.Long),
new JProperty("count", d.Count)))));
return o;
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
ProductSalesHub.Show();
}
}
I've been staring at this for hours now, without figuring out why the ajax call is triggered multiple times.
Any ideas?
I had this exact same problem. I was injecting my repository class and had multiple instances of it. Here you are adding the event every time GetProductSalesData() method is called. I would add the event once in the constructor and use the singleton pattern to make sure it is only called once.
Because every client who open the page request the server by signalR and signalR response to all client thats why you see multiple response and request.
use
this.Clients.Client(this.Context.ConnectionId).displaySales();
instead of
context.Clients.All.displaySales();
cheers.

AS3 Socket/Server MMO Communication

I'm working on a flash MMO with a c# server. I have a simple messaging protocol for the sockets. When a client joins he sends out this:
"%|clientId|need"
And positions are updated like this:
"$|clientId|xPosition|yPosition"
For some reason this isn't working. I store all the avatars in an array, the avatar class simply extends movieclip. This should add all clients into the room but it isn't working. Any ideas?
Edit: The error is probably in the client-side code above, I think it's with how I store the Avatars in an array.
Here is my code:
id.text = String(Math.random());
import flash.net.Socket;
import flash.events.MouseEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.utils.Dictionary;
var avatars:Array = new Array();
var _socket:Socket = new Socket();
_socket.addEventListener(ProgressEvent.SOCKET_DATA,socketData);
_socket.addEventListener(Event.CONNECT,socketConnected);
_socket.addEventListener(IOErrorEvent.IO_ERROR,socketError);
_socket.connect("192.168.1.4",8000);
function sendText(msg:String):void {
if (_socket.connected) {
_socket.writeUTFBytes(msg);
_socket.flush();
} else {
}
}
function socketConnected(e:Event):void {
chat.appendText("Connected. \n");
sendText("%|" + id.text + "|need");
//chat.scrollV = chat.maxScrollV;
}
function socketError(e:IOErrorEvent):void {
chat.appendText("SYSTEM MSG:"+e.text+"\n");
//chat.scrollV = chat.maxScrollV;
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
//var xml:XML = new XML(str);
chat.appendText(str + "\n");
//[pos]|50|334
if(str.search("$")){
var positionArray = str.split("|");
avatars[str[1]].x = str[2];
avatars[str[1]].x = str[3];
}
if(str.search("%")){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
dump.text = miniArray[1];
}
}
me.addEventListener(MouseEvent.MOUSE_DOWN, drag);
me.addEventListener(MouseEvent.MOUSE_UP, sDrag);
var timing:Boolean = false;
var t:Timer = new Timer(1);
t.addEventListener(TimerEvent.TIMER, tick);
function tick(e:TimerEvent){
if(timing){
sendText('$|'+id.text+'|'+me.x+'|'+me.y);
}
else{
}
}
t.start();
function drag(e:MouseEvent){
me.startDrag();
timing = true;
}
function sDrag(e:MouseEvent){
me.stopDrag();
timing = false;
}
Edit: Changing answer based on additional information.
You had a few problems after addressing the code. First was your use of if(str.search)... The $ and % can be parsed as a regular expression. Additionally since your chars were at an index of 0 these if's could fail to be true. Lastly your were using str[1] instead of positionArray[1] etc. Below is the working code with some hacking to test without the use of a socket server. Might show you some tricks on how to do some focused testing when you run into issues like this.
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
public class TestSocket extends Sprite
{
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.Dictionary;
import flash.utils.Timer;
[Embed(source="assets/avatar.png")]
private var Avatar:Class;
private var avatars:Array = new Array();
function TestSocket():void
{
socketSimulator(10);
}
function socketData(e:ProgressEvent):void {
var str:String = e.currentTarget.readUTFBytes(e.currentTarget.bytesAvailable);
trace(str);
if(str.indexOf("$") >= 0){
var positionArray = str.split("|");
avatars[positionArray[1]].x = positionArray[2];
avatars[positionArray[1]].x = positionArray[3];
}
if(str.indexOf("%") >= 0){
var miniArray = str.split("|");
avatars[miniArray[1]] = new Avatar();
addChild(avatars[miniArray[1]]);
}
}
/** Test Code **/
private var _numClients;
private function socketSimulator(numClients:int):void
{
_numClients = numClients;
var msg:String;
while(--numClients >= 0)
{
msg = "%|" + numClients + "|need";
sendFakeData(msg);
}
var timer:Timer = new Timer(500, 9999);
timer.addEventListener(TimerEvent.TIMER, sendFakeMovement);
timer.start();
}
private function sendFakeMovement(e:TimerEvent):void
{
var id:uint = Math.random() * _numClients;
var x:Number = Math.random() * 1000;
var y:Number = Math.random() * 1000;
var msg:String = "$|"+id+"|"+x+"|"+y;
sendFakeData(msg);
}
//This is just hacked test code, don't do this in production
private function sendFakeData(msg:String):void
{
var e:MyProgressEvent = new MyProgressEvent(ProgressEvent.SOCKET_DATA);
e.currentTarget = {
readUTFBytes: function(bytes:int = 0):String
{
return msg;
}
}
socketData(e);
}
}
}
import flash.events.ProgressEvent;
class MyProgressEvent extends ProgressEvent
{
private var _currentTarget:Object;
public function set currentTarget(val:Object):void
{
_currentTarget = val;
}
override public function get currentTarget():Object
{
return _currentTarget;
}
function MyProgressEvent(type:String):void
{
super(type);
}
}
Before you test log in/log off/position, make sure that your architecture supports sending and receiving data in the first place, I mean, send a string ("some data") on the front-end and check if you're really receiving ("some data") on the back-end. I am afraid the byte endianness that you're sending on the client is different from that on the server and so the server will mis-understand the incoming data. If so you need to convert the incoming messages to the suitable endianness before trying to process them.

Return data from jQuery callback ASP.NET 2.0

I am new to jQuery and I am implementing an example I found on CodeProjects.
What I need is to get a string with an imagename and new image index returned from the PageMethod I am calling.
However each time I try to return something else than a number via Response.Write the callback fails and I go into the error function.
$(document).ready(function() {
var imageIndex = $("[id$='hdn_imageIndex']");
var app_path = $("[id$='hdn_app_path']");
$("#btn_next").click(function() {
var json = "{'Index':'" + imageIndex.val() + "'}";
var ajaxPage = app_path.val() + "/JSONProcessor.aspx?NextImage=1"; //this page is where data is to be retrieved and processed
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=UTF-8",
dataType: "json",
async: false,
success: function(result) {
alert("success: " + result.d);
// I want my return value from my PageMethod HERE.
},
error: function(msg) { alert("failed: " + msg.d); }
};
var returnText = $.ajax(options).responseText;
});
});
The PageMethod in JSONProcessor.aspx looks like this:
public void NextImage()
{
System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string line = "";
line = sr.ReadToEnd();
JObject jo = JObject.Parse(line);
int newImageIndex = -1;
int oldImageIndex = int.Parse(Server.UrlDecode((string)jo["Index"]));
List<string> images = (List<string>)Session["ShowHouseImages"];
int noOfImages = images.Count;
if (noOfImages > 0)
{
if (oldImageIndex == noOfImages - 1)
{
newImageIndex = 0;
}
else
{
newImageIndex = oldImageIndex + 1;
}
string[] result = ChangeImage(newImageIndex, images);
Response.StatusCode = 200;
Response.Write("1");
// What I REALLY WANT TO RETURN IS THIS
// Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
}
Response.Write("0");
}
JSON return from WebMethods does not seem to be a part of .NET 2.0. That is why I do it like this. Hope somebody can help me out.
To my understanding in the line
Response.Write(string.Format("{0};{1};{2}", result[0], result[1], result[2]));
you are not returning a correct JSON object. It should probably look something like
Response.Write(string.Format("{{images:[{0},{1},{2}]}}", result[0], result[1], result[2]));
This returns you an array with three elements. The produced output should be:
{images:[1,2,3]}
In JavaScript you can access data using result.images[0],result.images1, etc.
I'm not sure if you need to specify array object name (images).
I suggest you take a look at JSON website to get a better understanding of the syntax. This way you will be able to construct complex object by yourself.

Categories

Resources