Google Map API on MVC5 - google-maps-api-3

I'm having problem when trying to produce multiple marker for multiple address on the map. So basically, I'm pulling the address from my database and let the GoogleLocationService() to detect the coordinates of it. Though I'm not sure how can i pass multiple latitue and longitude for my VIEW(.CSHTML).
I'm still new on MVC so I'm kinda having trouble on passing the values from controller to view. any suggestions?
On my Code (Controller) :
public ActionResult Index() {
VerifyUserModel user = new VerifyUserModel();
user.UserName = "Kenneth Baleda";
user.AccountLevel = "MGR";
foreach (string w in a.Companies.Where(x => x.IsActive == "Active").Where(x => x.CompanyName != "tbd").Where(x => x.FullCompanyName != "Test")
.Where(x => x.FullCompanyName != "")
.Select(x => x.Address).ToArray())
{
user.CompanyAddress = w;
var location = new GoogleLocationService();
var point = location.GetLatLongFromAddress(w);
user.Latitude = point.Latitude;
user.Longtitude = point.Longitude;
}
return View(user);
}
While on my (Model) :
public class VerifyUserModel
{
public string UserName { get; set; }
public string AccountLevel { get; set; }
public double Latitude { get; set; }
public double Longtitude { get; set; }
public string CompanyAddress { get; set; }
}
Then my (.CSHTML) :
#foreach (var place in Model)
{
<text>
var latlng = new google.maps.LatLng(#Model.Latitude, #Model.Longtitude);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: 'Latitude: ' + latlng.Ya + ' Longitude :' + latlng.Za,
draggable: true,
icon: image
});
infoWindow = new google.maps.InfoWindow({
content:"-- Test Address --"
});
infoWindow.open(map, marker);
geocoder = new google.maps.Geocoder();
//Update postal address when the marker is dragged
google.maps.event.addListener(marker, 'click', function () { //dragend
geocoder.geocode({ latLng: marker.getPosition() }, function (responses) {
if (responses && responses.length > 0) {
infoWindow.setContent(
"<div style=\"font-size:smaller;\">" + responses[0].formatted_address
+ "<br />"
+ "Latitude: " + marker.getPosition().lat() + "&nbsp"
+ "Longitude: " + marker.getPosition().lng() + "</div>"
);
infoWindow.open(map, marker);
} else {
alert('Error: Google Maps could not determine the address of this location.');
}
});
map.panTo(marker.getPosition());
});
// Close the marker window when being dragged
google.maps.event.addListener(marker, 'dragstart', function () {
infoWindow.close(map, marker);
});
</text>
}

Related

how do I parse the http response object coming from asmx

$scope.Edit = function (id) {
console.log("edit id : " + id);
$scope.Employee = {};
$scope.eid = id;
var data = JSON.stringify({empid: $scope.eid});
var url = "/services/EmployeeService.asmx/EditEmployee";
$http.post(url, data).then(function (response) {
$scope.Employee = response.data;
console.log($scope.Employee.fname);
console.log($scope.Employee);
var mydata = jQuery.parseJSON(JSON.stringify(response.data));
console.log(mydata);
}, function (response) {
console.log(response.status);
console.log(response.statusText);
});
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EditEmployee(int empid)
{
Employee employee = new Employee();
if (emplist.Count > 0)
{
foreach (Employee emp in emplist)
{
if (emp.empId == empid)
{
employee.empId = empid;
employee.fname = emp.fname;
employee.city = emp.city;
employee.mobile = emp.mobile;
employee.country = emp.country;
break;
}
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
List<Employee> elist = new List<Employee>();
elist.Add(employee);
return new JavaScriptSerializer().Serialize(elist);
}
This is I got from the response
Object
d:"[{"empId":103,"fname":"sujith","city":"trichy","mobile":"56456456","country":"India"}]"
proto : Object
how do I parse angular js object. I want to access like this: $scop.Employee.empId,$scope.Employee.fname
Thanks & Regards
arun
Are you sure that the object you are receiving is starting and ending with " " (double quotes)
Change the following line
$scope.Employee = response.data;
with
$scope.Employee = response.data.d[0];
Try this. This should work :
$scope.Edit = function (id) { console.log("edit id : " + id); $scope.Employee = {}; $scope.eid = id; var data = JSON.stringify({empid: $scope.eid}); var url = "/services/EmployeeService.asmx/EditEmployee"; $http.post(url, data).then(function (response) {
$scope.Employee = response.data.d[0];
console.log($scope.Employee.fname);
console.log($scope.Employee); }, function (response) {
console.log(response.status);
console.log(response.statusText); });
}
$scope.Edit = function (id) {
console.log("edit id : " + id);
$scope.Employee = {};
$scope.eid = id;
var data = JSON.stringify({ empid: $scope.eid });
var url = "/services/EmployeeService.asmx/EditEmployee";
$http.post(url, data).then(function (response) {
$scope.Employee = JSON.parse( response.data.d);
console.log("empid: " + $scope.Employee.empId);
console.log("fname: " + $scope.Employee.fname);
console.log("city: " + $scope.Employee.city);
console.log("country: " + $scope.Employee.country);
}, function (response) {
console.log(response.status);
console.log(response.statusText);
});
}
enter code here
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string EditEmployee(int empid)
{
Employee employee = new Employee();
if (emplist.Count > 0)
{
foreach (Employee emp in emplist)
{
if (emp.empId == empid)
{
employee.empId = empid;
employee.fname = emp.fname;
employee.city = emp.city;
employee.mobile = emp.mobile;
employee.country = emp.country;
break;
}
}
}
return new JavaScriptSerializer().Serialize(employee);
}
enter code here
thank you Vikas Thakur, Abhijeet Jaiswal, it helped me to solved it, now it is working, what mistake is in asmx webservice webmethod I should return Employee object as string, previously I wrongly add it to the list and return the list. the webmethod return type is string so it is not parsing. now it is parsing. thank you both of you helped me.

Chat application using signalr as wcf service

i have done the chat application using signalr client and chatsever implemented as class. Now i want to implement chat server as wcf service.
<link rel="stylesheet" href="Styles/jquery-ui.css" />
<script src="Scripts/jquery-1.8.2.js"></script>
<script src="Scripts/jquery-ui.js"></script>
<script type="text/javascript" src="Scripts/jquery.dialogextend.1_0_1.js"></script>
<script type="text/javascript" src="Scripts/jquery.signalR.js"></script>
<script type="text/javascript" src="Scripts/jQuery.tmpl.js"></script>
<script type="text/javascript" src="signalr/hubs"></script>
<script id="new-online-contacts" type="text/x-jquery-tmpl">
<div>
<ul>
{{each messageRecipients}}
<li id="chatLink${messageRecipientId}">${messageRecipientName}</li>
{{/each}}
</ul>
</div>
</script>
<script id="new-chatroom-template" type="text/x-jquery-tmpl">
<div id="chatRoom${chatRoomId}" class="chatRoom">
<ul id="messages${chatRoomId}" class="chatMessages">
</ul>
<form id="sendmessage${chatRoomId}" action="#">
<input type="text" id="newmessage${chatRoomId}" class="chatNewMessage"/>
<div class="clear"></div>
<input type="button" id="chatsend${chatRoomId}" value="Send" class="chatSend" OnClick="javascript:SRChat.sendChatMessage('${chatRoomId}')" />
<input type="button" id="chatend${chatRoomId}" value="End Chat" class="chatSend" OnClick="javascript:SRChat.endChat('${chatRoomId}')" />
</form>
</div>
</script>
<script id="new-chat-header" type="text/x-jquery-tmpl">
<div id="chatRoomHeader${chatRoomId}">
{{each messageRecipients}}
{{if $index == 0}}
${messageRecipientName}
{{else}}
, ${messageRecipientName}
{{/if}}
{{/each}}
<div>
</script>
<script id="new-message-template" type="text/x-jquery-tmpl">
<li class="message" id="m-${chatMessageId}">
<strong>${displayPrefix}</strong>
{{html messageText}}
</li>
</script>
<script id="new-notify-message-template" type="text/x-jquery-tmpl">
<li class="message" id="m-${chatMessageId}">
<strong>{{html messageText}}</strong>
</li>
</script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
SRChat.attachEvents();
});
SRChat = new function () {
var Username = GetParameterValues('Username');
function GetParameterValues(param) {
var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < url.length; i++) {
var urlparam = url[i].split('=');
if (urlparam[0] == param) {
return urlparam[1];
}
}
}
var chatRooms = 0;
var numRand = Username;
var senderId = numRand;
var senderName = 'User :' + numRand;
var sRChatServer;
window.onbeforeunload = function () {
if (chatRooms > 0)
return "All chat instances will be ended!";
};
this.attachEvents = function () {
$("#userNameLabel").html(senderName);
if ($.connection != null) {
jQuery.support.cors = true;
$.connection.hub.url = 'signalr/hubs';
sRChatServer = $.connection.sRChatServer;
$.connection.hub.start({ transport: 'auto' }, function () {
sRChatServer.server.connect(senderId, senderName).fail(function (e) {
alert(e);
});
});
sRChatServer.client.initiateChatUI = function (chatRoom) {
var chatRoomDiv = $('#chatRoom' + chatRoom.chatRoomId);
if (($(chatRoomDiv).length > 0)) {
var chatRoomText = $('#newmessage' + chatRoom.chatRoomId);
var chatRoomSend = $('#chatsend' + chatRoom.chatRoomId);
var chatRoomEndChat = $('#chatend' + chatRoom.chatRoomId);
chatRoomText.show();
chatRoomSend.show();
chatRoomEndChat.show();
}
else {
var e = $('#new-chatroom-template').tmpl(chatRoom);
var c = $('#new-chat-header').tmpl(chatRoom);
chatRooms++;
//dialog options
var dialogOptions = {
"id": '#messages' + chatRoom.chatRoomId,
"title": c,
"width": 360,
"height": 365,
"modal": false,
"resizable": false,
"close": function () { javascript: SRChat.endChat('' + chatRoom.chatRoomId + ''); $(this).remove(); }
};
// dialog-extend options
var dialogExtendOptions = {
"close": true,
"maximize": false,
"minimize": true,
"dblclick": 'minimize',
"titlebar": 'transparent'
};
e.dialog(dialogOptions).dialogExtend(dialogExtendOptions);
$('#sendmessage' + chatRoom.chatRoomId).keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('#chatsend' + chatRoom.chatRoomId).click();
return false;
}
});
}
};
sRChatServer.client.updateChatUI = function (chatRoom) {
var chatRoomHeader = $('#chatRoomHeader' + chatRoom.chatRoomId);
var c = $('#new-chat-header').tmpl(chatRoom);
chatRoomHeader.html(c);
};
sRChatServer.client.receiveChatMessage = function (chatMessage, chatRoom) {
sRChatServer.client.initiateChatUI(chatRoom);
var chatRoom = $('#chatRoom' + chatMessage.conversationId);
var chatRoomMessages = $('#messages' + chatMessage.conversationId);
var e = $('#new-message-template').tmpl(chatMessage).appendTo(chatRoomMessages);
e[0].scrollIntoView();
chatRoom.scrollIntoView();
};
sRChatServer.client.receiveLeftChatMessage = function (chatMessage) {
var chatRoom = $('#chatRoom' + chatMessage.conversationId);
var chatRoomMessages = $('#messages' + chatMessage.conversationId);
var e = $('#new-notify-message-template').tmpl(chatMessage).appendTo(chatRoomMessages);
e[0].scrollIntoView();
chatRoom.scrollIntoView();
};
sRChatServer.client.receiveEndChatMessage = function (chatMessage) {
var chatRoom = $('#chatRoom' + chatMessage.conversationId);
var chatRoomMessages = $('#messages' + chatMessage.conversationId);
var chatRoomText = $('#newmessage' + chatMessage.conversationId);
var chatRoomSend = $('#chatsend' + chatMessage.conversationId);
var chatRoomEndChat = $('#chatend' + chatMessage.conversationId);
chatRooms--;
var e = $('#new-notify-message-template').tmpl(chatMessage).appendTo(chatRoomMessages);
chatRoomText.hide();
chatRoomSend.hide();
chatRoomEndChat.hide();
e[0].scrollIntoView();
chatRoom.scrollIntoView();
};
sRChatServer.client.onGetOnlineContacts = function (chatUsers) {
var e = $('#new-online-contacts').tmpl(chatUsers);
var chatLink = $('#chatLink' + senderId);
e.find("#chatLink" + senderId).remove();
$("#chatOnlineContacts").html("");
$("#chatOnlineContacts").html(e);
};
}
};
this.sendChatMessage = function (chatRoomId) {
var chatRoomNewMessage = $('#newmessage' + chatRoomId);
if (chatRoomNewMessage.val() == null || chatRoomNewMessage.val() == "")
return;
var chatMessage = {
senderId: senderId,
senderName: senderName,
conversationId: chatRoomId,
messageText: chatRoomNewMessage.val()
};
chatRoomNewMessage.val('');
chatRoomNewMessage.focus();
sRChatServer.server.sendChatMessage(chatMessage).fail(function (e) {
alert(e);
});
return false;
};
this.endChat = function (chatRoomId) {
var chatRoomNewMessage = $('#newmessage' + chatRoomId);
var chatMessage = {
senderId: senderId,
senderName: senderName,
conversationId: chatRoomId,
messageText: chatRoomNewMessage.val()
};
chatRoomNewMessage.val('');
chatRoomNewMessage.focus();
sRChatServer.server.endChat(chatMessage).fail(function (e) {
//alert(e);
});
};
this.initiateChat = function (toUserId, toUserName) {
if (sRChatServer == null) {
alert("Problem in connecting to Chat Server. Please Contact Administrator!");
return;
}
sRChatServer.server.initiateChat(senderId, senderName, toUserId, toUserName).fail(function (e) {
alert(e);
});
};
};
//]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="userNameLabel">
</div>
<br />
<br />
<div id="chatRooms">
</div>
<div id="chatOnlineContacts">
</div>
</div>
</form>
</body>
My server side code is
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using SignalR.Hubs;
namespace SRChat
{
[HubName("sRChatServer")]
public class SRChatServer:Hub
{
#region Private Variables
private static readonly ConcurrentDictionary<string, MessageRecipient> _chatUsers = new ConcurrentDictionary<string, MessageRecipient>(StringComparer.OrdinalIgnoreCase);
private static readonly ConcurrentDictionary<string, ChatRoom> _chatRooms = new ConcurrentDictionary<string, ChatRoom>(StringComparer.OrdinalIgnoreCase);
#endregion
#region Public Methods
public bool Connect(string userId, string userName)
{
try
{
if (string.IsNullOrEmpty(userId) | string.IsNullOrEmpty(userName))
{
return false;
}
if (GetChatUserByUserId(userId) == null)
{
AddUser(userId, userName);
}
else
{
ModifyUser(userId, userName);
}
SendOnlineContacts();
return true;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in connecting to chat server!");
}
}
public override Task Disconnect()
{
try
{
DeleteUser(Context.ConnectionId);
return null;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in disconnecting from chat server!");
}
}
public bool InitiateChat(string fromUserId, string fromUserName, string toUserId, string toUserName)
{
try
{
if (string.IsNullOrEmpty(fromUserId) || string.IsNullOrEmpty(fromUserName) || string.IsNullOrEmpty(toUserId) || string.IsNullOrEmpty(toUserName))
{
return false;
}
var fromUser = GetChatUserByUserId(fromUserId);
var toUser = GetChatUserByUserId(toUserId);
if (fromUser != null && toUser != null)
{
if (!CheckIfRoomExists(fromUser, toUser))
{
//Create New Chat Room
ChatRoom chatRoom = new ChatRoom();
chatRoom.chatRoomInitiatedBy = fromUser.messageRecipientId;
chatRoom.chatRoomInitiatedTo = toUser.messageRecipientId;
chatRoom.messageRecipients.Add(fromUser);
chatRoom.messageRecipients.Add(toUser);
//create and save blank message to get new conversation id
ChatMessage chatMessage = new ChatMessage();
chatMessage.messageText = "Chat Initiated";
chatMessage.senderId = fromUser.messageRecipientId;
chatMessage.senderName = fromUser.messageRecipientName;
fromUser.chatRoomIds.Add(chatRoom.chatRoomId);
toUser.chatRoomIds.Add(chatRoom.chatRoomId);
//Create SignalR Group for this chat room and add users connection to it
Groups.Add(fromUser.connectionId, chatRoom.chatRoomId);
Groups.Add(toUser.connectionId, chatRoom.chatRoomId);
//Add Chat room object to collection
if (_chatRooms.TryAdd(chatRoom.chatRoomId, chatRoom))
{
//Generate Client UI for this room
Clients[fromUser.connectionId].initiateChatUI(chatRoom);
}
}
}
return true;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in starting chat!");
}
}
public bool EndChat(ChatMessage chatMessage)
{
try
{
ChatRoom chatRoom;
if (_chatRooms.TryGetValue(chatMessage.conversationId, out chatRoom))
{
if (_chatRooms[chatRoom.chatRoomId].chatRoomInitiatedBy == chatMessage.senderId)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", chatMessage.senderName);
if (_chatRooms.TryRemove(chatRoom.chatRoomId, out chatRoom))
{
Clients[chatRoom.chatRoomId].receiveEndChatMessage(chatMessage);
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoom.chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoom.chatRoomId);
Groups.Remove(messageReceipient.connectionId, chatRoom.chatRoomId);
}
}
}
}
else
{
MessageRecipient messageRecipient = GetChatUserByUserId(chatMessage.senderId);
if (messageRecipient != null && messageRecipient.chatRoomIds.Contains(chatRoom.chatRoomId))
{
chatRoom.messageRecipients.Remove(messageRecipient);
messageRecipient.chatRoomIds.Remove(chatRoom.chatRoomId);
if (chatRoom.messageRecipients.Count < 2)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", chatMessage.senderName);
if (_chatRooms.TryRemove(chatRoom.chatRoomId, out chatRoom))
{
Clients[chatRoom.chatRoomId].receiveEndChatMessage(chatMessage);
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoom.chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoom.chatRoomId);
Groups.Remove(messageReceipient.connectionId, chatRoom.chatRoomId);
}
}
}
}
else
{
chatMessage.messageText = string.Format("{0} left the chat.", chatMessage.senderName);
Groups.Remove(messageRecipient.connectionId, chatRoom.chatRoomId);
Clients[messageRecipient.connectionId].receiveEndChatMessage(chatMessage);
Clients[chatRoom.chatRoomId].receiveLeftChatMessage(chatMessage);
Clients[chatRoom.chatRoomId].updateChatUI(chatRoom);
}
}
}
}
else
{
throw new InvalidOperationException("Problem in ending chat!");
}
return true;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in ending chat!");
}
}
public bool SendChatMessage(ChatMessage chatMessage)
{
try
{
ChatRoom chatRoom;
if (_chatRooms.TryGetValue(chatMessage.conversationId, out chatRoom))
{
chatMessage.chatMessageId = Guid.NewGuid().ToString();
chatMessage.timestamp = DateTime.Now;
Clients[chatMessage.conversationId].receiveChatMessage(chatMessage, chatRoom);
return true;
}
else
{
throw new InvalidOperationException("Problem in sending message!");
}
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in sending message!");
}
}
private bool SendOnlineContacts()
{
try
{
OnlineContacts onlineContacts = new OnlineContacts();
foreach (var item in _chatUsers)
{
onlineContacts.messageRecipients.Add(item.Value);
}
Clients.onGetOnlineContacts(onlineContacts);
return false;
}
catch (Exception ex)
{
throw new InvalidOperationException("Problem in getting contacts!");
}
}
#endregion
#region Private Methods
private Boolean CheckIfRoomExists(MessageRecipient fromUser, MessageRecipient toUser)
{
foreach (string chatRoomId in fromUser.chatRoomIds)
{
Int32 count = (from mr in _chatRooms[chatRoomId].messageRecipients
where mr.messageRecipientId == toUser.messageRecipientId
select mr).Count();
if (count > 0)
{
return true;
}
}
foreach (string chatRoomId in toUser.chatRoomIds)
{
Int32 count = (from mr in _chatRooms[chatRoomId].messageRecipients
where mr.messageRecipientId == fromUser.messageRecipientId
select mr).Count();
if (count > 0)
{
return true;
}
}
return false;
}
private MessageRecipient AddUser(string userId, string userName)
{
var user = new MessageRecipient();
user.messageRecipientId = userId;
user.messageRecipientName = userName;
user.connectionId = Context.ConnectionId;
_chatUsers[userId] = user;
return user;
}
private MessageRecipient ModifyUser(string userId, string userName)
{
var user = GetChatUserByUserId(userId);
user.messageRecipientName = userName;
user.connectionId = Context.ConnectionId;
_chatUsers[userId] = user;
return user;
}
private Boolean DeleteUser(string userId, string userName)
{
var user = GetChatUserByUserId(userId);
if (user != null && _chatUsers.ContainsKey(user.messageRecipientId))
{
MessageRecipient messageRecipient;
return _chatUsers.TryRemove(user.messageRecipientId, out messageRecipient);
}
return false;
}
private Boolean DeleteUser(string connectionId)
{
var returnValue = false;
var user = GetChatUserByConnectionId(connectionId);
if (user != null && _chatUsers.ContainsKey(user.messageRecipientId))
{
MessageRecipient messageRecipient;
returnValue = _chatUsers.TryRemove(user.messageRecipientId, out messageRecipient);
//remoave from all groups and chatrooms
foreach (string chatRoomId in messageRecipient.chatRoomIds)
{
_chatRooms[chatRoomId].messageRecipients.Remove(messageRecipient);
Groups.Remove(messageRecipient.connectionId, chatRoomId);
//notify user left chat
ChatMessage chatMessage = new ChatMessage();
chatMessage.conversationId = chatRoomId;
chatMessage.senderId = messageRecipient.messageRecipientId;
chatMessage.senderName = messageRecipient.messageRecipientName;
if (_chatRooms[chatRoomId].chatRoomInitiatedBy == messageRecipient.messageRecipientId)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", messageRecipient.messageRecipientName);
ChatRoom chatRoom;
if (_chatRooms.TryRemove(chatRoomId, out chatRoom))
{
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoomId);
}
}
Clients[chatRoomId].receiveEndChatMessage(chatMessage);
}
}
else
{
if (_chatRooms[chatRoomId].messageRecipients.Count() < 2)
{
chatMessage.messageText = string.Format("{0} left the chat. Chat Ended!", messageRecipient.messageRecipientName);
ChatRoom chatRoom;
if (_chatRooms.TryRemove(chatRoomId, out chatRoom))
{
foreach (MessageRecipient messageReceipient in chatRoom.messageRecipients)
{
if (messageReceipient.chatRoomIds.Contains(chatRoomId))
{
messageReceipient.chatRoomIds.Remove(chatRoomId);
}
}
Clients[chatRoomId].receiveEndChatMessage(chatMessage);
}
}
else
{
chatMessage.messageText = string.Format("{0} left the chat.", messageRecipient.messageRecipientName);
Clients[chatRoomId].receiveLeftChatMessage(chatMessage);
}
}
}
}
return returnValue;
}
private MessageRecipient GetChatUserByUserId(string userId)
{
return _chatUsers.Values.FirstOrDefault(u => u.messageRecipientId == userId);
}
private MessageRecipient GetChatUserByConnectionId(string connectionId)
{
return _chatUsers.Values.FirstOrDefault(u => u.connectionId == connectionId);
}
#endregion
}
}
i want to implement this one as wcf service or web service. please help me in advance
I think the best way to achieve that is to create a windows managed service.(Cause you can't control the lifetime of your service when hosted in IIS with a per-call configuration).
So you should create a new windows service and host both your wcf service and signalr (it's only an idea but I think the code can looks like that):
public class HostWindowService : ServiceBase
{
public ServiceHost serviceHost = null;
public HostWindowService()
{
ServiceName = "WCFWindowsServiceSample";
}
public static void Main()
{
ServiceBase.Run(new HostWindowService());
}
protected override void OnStart(string[] args)
{
//host wcf service
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(WCFService));
serviceHost.Open();
//host signalr
Task.Run(() => SignalRHost());
}
private void SignalRHost()
{
try
{
SignalR = WebApp.Start("http://localhost:8080");
}
catch (TargetInvocationException)
{
WriteToConsole("A server is already running at " + "http://localhost:8080");
return;
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
References : How to: Host a WCF Service in a Managed Windows Service and Self-Hosting SignalR in a Windows Service

SignalR 2.0 Hub public method not accecible via Java Script

I'm trying to get list of connected users by using the following server code in SignalR hub. For store in-memory data I'm using following class:
public class UserInfo
{
public string ConnectionId { get; set; }
public string UserName { get; set; }
public string Role { get; set; }
}
When user connected I'm adding user to the list of connected users:
public override Task OnConnected()
{
if (Context.User.Identity.IsAuthenticated)
{
if (Context.User.IsInRole("User"))
{
ui.Add(new UserInfo { ConnectionId = Context.ConnectionId, UserName = Context.User.Identity.Name, Role = "User" });
}
else
{
ui.Add(new UserInfo { ConnectionId = Context.ConnectionId, UserName = Context.User.Identity.Name, Role = "Operator" });
}
}
return base.OnConnected();
}
Here is the way I'm getting list of currently connected users:
public IEnumerable<UserInfo> GetUsers()
{
var x = (from a in ui where a.Role == "User" select new UserInfo { UserName = a.UserName, ConnectionId = a.ConnectionId }).ToList();
return x;
}
public IEnumerable<UserInfo> GetOperators()
{
var y = (from a in ui where a.Role == "Operator" select new UserInfo { UserName = a.UserName, ConnectionId = a.ConnectionId }).ToList();
return y;
}
Unfortinately public method GetOperators/GetUsers not accessible and I did not receive data on client side:
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
//Here I'm calling hub public methods
chat.getOperators = function (data) {
alert(data);
};
chat.getUsers = function (data) {
alert(data);
};
// Create a function that the hub can call to broadcast messages.
chat.client.addChatMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
Your syntax for the calls to the server is wrong; this here:
chat.getUsers = function (data) {
alert(data);
};
will simply define chat.getUsers to be a function.
You probably want
chat.server.getUsers().done(function(data) {
console.log(data);
}).fail(function(error) {
console.log("failed to get data", error);
});
Take another look at the documentation.
please can you try this
//on your client action do a server call
chat.server.getOperators();
and
//on your client action do a server call
chat.server.getUsers();
instead of
chat.getOperators = function (data) {
alert(data);
};
chat.getUsers = function (data) {
alert(data);
};

Flex 3: Getting variables from URL

If I have an application located at http://sitename.com/myapp/ and i want to pass in a variable via the url (i.e. - http://sitename.com/myapp/?name=Joe), how can I get that name variable into a string var?
I use the class Adobe provided in this article.
package
{
import flash.external.*;
import flash.utils.*;
public class QueryString
{
private var _queryString:String;
private var _all:String;
private var _params:Object;
public function get queryString():String
{
return _queryString;
}
public function get url():String
{
return _all;
}
public function get parameters():Object
{
return _params;
}
public function QueryString()
{
readQueryString();
}
private function readQueryString():void
{
_params = {};
try
{
_all =
ExternalInterface.call("window.location.href.toString");
_queryString =
ExternalInterface.call("window.location.search.substring", 1);
if(_queryString)
{
var params:Array = _queryString.split('&');
var length:uint = params.length;
for (var i:uint=0,index:int=-1; i 0)
{
var key:String = kvPair.substring(0,index);
var value:String = kvPair.substring(index+1);
_params[key] = value;
}
}
}
}catch(e:Error) { trace("Some error occured.
ExternalInterface doesn't work in Standalone player."); }
}
}
}
UPDATE: An updated version of this class can also be found here, although I haven't tried this one.
UPDATE 2:
Here's an example on how to use the Querystring class:
public function CheckForIDInQuerystring():void
{
// sample URL: http://www.mysite.com/index.aspx?id=12345
var qs:QueryString = new QueryString;
if (qs.parameters.id != null)
{
// URL contains the "id" parameter
trace(qs.parameters.id);
}
else
{
// URL doesn't contain the "id" parameter
trace("No id found.");
}
}
Divide 'em with String.split() and conquer:
var url:String = "http://www.xxx.zzz/myapp?arg1=vae&arg2=victus";
var params:String = url.substr(url.lastIndexOf("?") + 1);
if (params.length == url.length) return; //no params
for each (var pair:String in params.split("&"))
{
trace("Got parameter:");
var nameValue:Array = pair.split("=");
trace("name: " + nameValue[0] + ", value: " + nameValue[1]);
}
Output:
Got parameter:
name: arg1, value: vae
Got parameter:
name: arg2, value: victus

Multiple Markers on a Google Map

I added a google map with two markers (i am just testing), the code is:
function load() {
var map = new GMap2(document.getElementById("map"));
var marker = new GMarker(new GLatLng(<%=coordinates%>));
var marker2 = new GMarker(new GLatLng(31.977211,35.951729));
var html="<%=maptitle%><br/>" +
"<%=text%>";
var html2="<img src='simplemap_logo.jpg' width='20' height='20'/> " +
"<%=maptitle%><br/>" +
"<%=text%>" + "Alper";
map.setCenter(new GLatLng(<%=coordinates%>), 5);
map.setMapType(G_HYBRID_MAP);
map.addOverlay(marker);
map.addOverlay(marker2);
map.addControl(new GLargeMapControl());
map.addControl(new GScaleControl());
map.addControl(new GMapTypeControl());
marker.openInfoWindowHtml(html);
marker2.openInfoWindowHtml(html2);
}
The problem is, only one markers text is showing (the white triangle with text inside it) the other is not visible, why?
Another thing, i have a table of Maps, its like: mapID, mapCoordinates, mapMarkerTitle, mapMarkerText, i can retrieve this table, but i want a way to be able to pass all its records to my javascript and create a Marker for each Map i have in my table, i know this is two much, but can anyone suggest or help me with the code? as i know nothing about javascript :D
The HTML OUTPUT is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
Untitled Page
</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAANgu3GlobW5KtQorgXrnJ_xTHM4EYhrvsce8mdg4KdiCoPfCQKxSOZ_5sjy4O31twg6cxfZqam24TCw"
type="text/javascript"></script>
<script type="text/javascript">
function load() {
var map = new GMap2(document.getElementById("map"));
var marker = new GMarker(new GLatLng(32.523251,35.816068));
var marker2 = new GMarker(new GLatLng(31.977211,35.951729));
var html="maen<br/>" +
" maen tamemi";
var html2="<img src='simplemap_logo.jpg' width='20' height='20'/> " +
"maen<br/>" +
" maen tamemi" + "Alper";
map.setCenter(new GLatLng(32.523251,35.816068), 5);
map.setMapType(G_HYBRID_MAP);
map.addOverlay(marker);
map.addOverlay(marker2);
map.addControl(new GLargeMapControl());
map.addControl(new GScaleControl());
map.addControl(new GMapTypeControl());
marker2.openInfoWindowHtml(html2);
marker.openInfoWindowHtml(html);
}
//]]>
</script>
<script type="text/javascript">
function pageLoad() {
}
</script>
</head>
<body onload = "load()">
<form name="form1" method="post" action="Xhome.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNDI5NDcxNTY4ZGTjxbb38769ZB2N9Ow9kAzPz2PIqA==" />
</div>
<div id="map" style="width:400px;height:300px" >
</div>
</form>
</body>
</html>
In response to the second part of your question:
i want a way to be able to pass all its records to my javascript and create a Marker for each Map i have in my table
I have (as an example - written a year or so ago) the following code:
In the code-behind I have something like this (c# I'm afraid):
[WebMethod]
public LatitudeLogitudeMessage[] GetPoints(string postCodes)
{
string[] postCodeArray = postCodes.Split(",".ToCharArray());
LatitudeLogitudeMessage[] pointArray =
new LatitudeLogitudeMessage[postCodeArray.Length];
int index = 0;
foreach (string postCode in postCodeArray)
{
pointArray[index] = GetPoint(postCode);
index++;
}
return pointArray;
}
LatitudeLogitudeMessage is a custom class that looks like this:
public class LatitudeLogitudeMessage
{
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
public string Message { get; set; }
public string Details { get; set; }
public string Address { get; set; }
public LatitudeLogitudeMessage(string addressToFind)
{
Address = addressToFind;
Details = addressToFind.Replace(",", ",<br />");
}
}
The GetPoint method bascially fills in those details.
In the code infront I then had:
PageMethods.GetPoints(address, showPoints);
Which calls the GetPoints method on the code behind, and passes the result to showPoints:
function showPoints(latLongs)
{
GLog.write("Showing points");
var points = [];
var latLngBounds = new GLatLngBounds();
for (var i = 0; i < latLongs.length; i++)
{
if ("" == latLongs[i].Message)
{
points[i] = new GLatLng(latLongs[i].Latitude, latLongs[i].Longitude);
var marker =
new GMarker(points[i], {title: latLongs[i].Details, clickable: false});
map.addOverlay(marker);
latLngBounds.extend(points[i]);
}
else
{
GLog.write(latLongs[i].Message);
}
}
if (points.length > 1)
{
var bounds = new GBounds(points);
var center = new GLatLng(
(latLngBounds.getSouthWest().lat()
+ latLngBounds.getNorthEast().lat()) /2.,
(latLngBounds.getSouthWest().lng()
+ latLngBounds.getNorthEast().lng()) /2.);
var newZoom = map.getBoundsZoomLevel(latLngBounds, map.getSize());
map.setCenter(center, newZoom);
}
else
{
map.setCenter(points[0], defaultZoomLevel);
}
}
So this takes the array of points, and iterates over them creating a marker as it goes, centering on the first item in the list (not clever, but it worked for me).
Try the Marker Manager API, it's easier to deal with. Here's the Google example:
function setupMap() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.setCenter(new GLatLng(41, -98), 4);
window.setTimeout(setupWeatherMarkers, 0);
}
}
function getWeatherMarkers(n) {
var batch = [];
for (var i = 0; i < n; ++i) {
batch.push(new GMarker(getRandomPoint(),
{ icon: getWeatherIcon() }));
}
return batch;
}
function setupWeatherMarkers() {
mgr = new GMarkerManager(map);
mgr.addMarkers(getWeatherMarkers(20), 3);
mgr.addMarkers(getWeatherMarkers(200), 6);
mgr.addMarkers(getWeatherMarkers(1000), 8);
mgr.refresh();
}
I don't think Google maps can show more than one info window at a time, so when you open the second one, the first one closes.
Edit: Markers also don't automatically open the information window automatically when you click on them. You need to attach a click handler to the marker that calls the showInfoWindowHtml method. I use a helper function that creates a marker and adds the click handler automatically.
function createMarkerHtml(point, title, html) {
var marker = new GMarker(point, { title: title });
GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); });
return marker;
}
map.addOverlay(createMarkerHtml(new GLatLng(<%=coordinates%>), "Marker 1", html));
map.addOverlay(createMarkerHtml(new GLatLng(31.977211,35.951729), "Marker 2", html2));

Resources