I try to create simple chat room using websockets and Fleck library. Now I can send messages to all users. Here is my code:
FleckLog.Level = LogLevel.Info;
var allsockets = new List<IWebSocketConnection>();
var server = new WebSocketServer("ws://localhost:8181");
server.Start(socket =>
{
socket.OnOpen = () =>
{ //See socket.ConnectionInfo.* for additional informations
Console.WriteLine(String.Empty);
Console.WriteLine("[NEW CLIENT CONNECTION]======================");
Console.WriteLine("GUID: " + socket.ConnectionInfo.Id);
Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress);
Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort);
Console.WriteLine("=============================================");
Console.WriteLine(String.Empty);
allsockets.Add(socket);
};
socket.OnClose = () =>
{
Console.WriteLine(String.Empty);
Console.WriteLine("[DISCONNECTED CLIENT]=======================");
Console.WriteLine("GUID: " + socket.ConnectionInfo.Id);
Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress);
Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort);
Console.WriteLine("=============================================");
Console.WriteLine(String.Empty);
allsockets.Remove(socket);
};
socket.OnMessage = (message) =>
{
//TODO: Json.Net Deserialize
Console.WriteLine("[JSON MESSAGE] " + message);
allsockets.ToList().ForEach(s => s.Send(message));
};
});
Client code (java script):
// Websocket Endpoint url
var URL = 'ws://localhost:8181';
var chatClient = null;
function connect () {
chatClient = new WebSocket(URL);
chatClient.onmessage = function (event) {
var messagesArea = document.getElementById("messages");
var jsonObj = JSON.parse(event.data);
var message = "<"+ jsonObj.user + "> " + jsonObj.message + "\r\n";
messagesArea.value = messagesArea.value + message;
messagesArea.scrollTop = messagesArea.scrollHeight;
};
}
function disconnect () {
chatClient.close();
}
function sendMessage() {
var user = document.getElementById("userName").value.trim();
if (user === "")
alert ("Please enter your name!");
var inputElement = document.getElementById("messageInput");
var message = inputElement.value.trim();
if (message !== "") {
var jsonObj = {"user" : user, "message" : message};
chatClient.send(JSON.stringify(jsonObj));
inputElement.value = "";
}
inputElement.focus();
}
How to add to this code secure layer WSS?
Thank you very much!
Have you checked https://github.com/statianzo/Fleck ?
You need to have an certificate and update your client url with wss://
Related
My XF app crash when user try to open any screen after finishing update data in one specific screen, the others works well.
Only I got is :
"08-20 23:41:19.211 W/art (15347): JNI RegisterNativeMethods: attempt to register 0 native methods for android.runtime.JavaProxyThrowable".
No HokeyApp message received in my email and no extra information appears so I can solve the problem, just crash and close the app.
I tried to decrease the amount of requests to local database, tried to follow step by step the execution process so I could get any clue about causes.
Task act = Task.Run(async () => await App.DataService.UpdateItemAsync(CP, ToServer, "Contact_Party/EditContact_Party/" + CP.Id));
await act.ContinueWith(async (antecedent) =>
{
foreach (var sam in specialty)
{
if (CP.Id > 0)
{
sam.Cntct_SEQ = CP.Id;
}
else
{
sam.Tmp_Cntct_SEQ = CP.Cntct_SEQ;
}
if (sam.Id == 0)
{
if (sam.Cntct_Spec_SEQ == 0)
await App.DataService.CreateItemAsync(sam, ToServer, "Contact_Specialty/AddContact_Specialty");
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
}, TaskContinuationOptions.None);
Below is the other code or the final step in Update data...
public async Task<T> UpdateItemAsync<T>(T item, bool ToServer, string url) where T : BaseModel, new()
{
try
{
HttpResponseMessage hrm = new HttpResponseMessage();
if (!CrossConnectivity.Current.IsConnected)
ToServer = false;
if (ToServer)
{
RestURL = PrimaryRestURL;
RestURL += url;
var content = JsonConvert.SerializeObject(item);
content = content.Replace("null", " ");
try
{
hrm = await _client.PutAsync(RestURL, new StringContent(content, System.Text.Encoding.UTF8, "application/json"));
RestURL = PrimaryRestURL;
}
catch (Exception hre)
{
RestURL = PrimaryRestURL;
ContentPage page = new ContentPage();
string inner = "", source = "", trace = "", data = "";
if (hre.InnerException != null)
inner = hre.InnerException.Message;
data = hre.Data.ToString();
source = hre.Source;
trace = hre.StackTrace;
string msg = "RestURL: " + RestURL + "\n\n Data: " + data + "\n\n Message: " + hre.Message + "\n\n Source: " + source + "\n\n Trace: " + trace + "\n\n Inner Message: " + inner;
await page.DisplayAlert("Error", msg, "Ok");
}
if (hrm.StatusCode == System.Net.HttpStatusCode.OK || hrm.StatusCode == System.Net.HttpStatusCode.NoContent)
{
item.Updated = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Completed");
}
else
{
item.Changed = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Error connection to server");
}
}
else
{
item.Changed = true;
await database.UpdateAsync(item);
DependencyService.Get<IMessage>().LongAlert("Completed");
}
}
catch (Exception xc)
{
ContentPage page = new ContentPage();
string inner = "", source = "", trace = "", data = "";
if (xc.InnerException != null)
inner = xc.InnerException.Message;
data = xc.Data.ToString();
source = xc.Source;
trace = xc.StackTrace;
string msg = "RestURL: " + RestURL + "\n\n Data: " + data + "\n\n Message: " + xc.Message + "\n\n Source: " + source + "\n\n Trace: " + trace + "\n\n Inner Message: " + inner;
await page.DisplayAlert("Error", msg, "Ok");
}
return item;
}
Finally, I solved the issue, it was because I wanted to make the process of updating in a task so being continues with sub updates, after implementeing each update process alone it work ... the code that produced the issue is:
Task act = Task.Run(async () => await App.DataService.UpdateItemAsync(CP, ToServer, "Contact_Party/EditContact_Party/" + CP.Id));
await act.ContinueWith(async (antecedent) =>
{
foreach (var sam in specialty)
{
if (CP.Id > 0)
{
sam.Cntct_SEQ = CP.Id;
}
else
{
sam.Tmp_Cntct_SEQ = CP.Cntct_SEQ;
}
if (sam.Id == 0)
{
if (sam.Cntct_Spec_SEQ == 0)
await App.DataService.CreateItemAsync(sam, ToServer, "Contact_Specialty/AddContact_Specialty");
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
else
{
await App.DataService.UpdateItemAsync(sam, ToServer, "Contact_Specialty/EditContact_Specialty/" + sam.Id);
}
}
}, TaskContinuationOptions.None);
I am using PushSharp 4.0.10.0 library to send the notification on iOS devices but it's not working. I have debugged it and found there is some ApnsConfiguration connection problem.
I am using this code to send the notificaiton:
public IHttpActionResult Notify()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpContent requestContent = Request.Content;
string errorMessage = "Some error occured.please try again later";
HttpStatusCode responseCode = HttpStatusCode.Unauthorized;
string requestParameter = requestContent.ReadAsStringAsync().Result;
string tokan = "";
var r = Request;
var header = r.Headers;
try
{
if (requestParameter != null)
{
PushNotificationModel complaintModel = JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/xyz.pem"));
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
appleCert, "xyz");
// Create a new broker
var push = new ApnsServiceBroker(config);
int DeviceType = 1;
string deviceId = Convert.ToString(complaintModel.deviceToken);
string message = "New notification!!";
Guid complaintId = complaintModel.ComplaintId;
string detail = complaintModel.detail;
try
{
//System.Web.Hosting.HostingEnvironment.MapPath("~/Images/User/")
// var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/CTPwd.pem"));
push.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
message = ex.Message;
}
else
{
message = "Not an APNSException";
}
// Mark it as handled
return true;
});
};
try
{
push.OnNotificationSucceeded += (notification) =>
{
message = "New Notification";
};
push.Start();
string appleJsonFormat = "{\"aps\": {\"alert\":" + '"' + message + '"' + ",\"sound\": \"default\"}}";
//string appleJsonFormat = "{\"aps\": {\"alert\": " + "Hello World" + ",\"sound\": \"default\"}}";
push.QueueNotification(new ApnsNotification
{
DeviceToken = deviceId,
Payload = JObject.Parse(appleJsonFormat)
});
push.Stop();
}
catch(Exception ex)
{
}
I have searched on google, but did not find any relevant answer. Is there any syntax problem ?
Thanks in advance.
Please use .P12 file format for push notification happy coding:)
New to MassTransit and still playing around with some of the tutorial projects. I'm going to have a service that will run for maybe 20 minutes and I need to do something when it's done. Because it can take so long I don't want to follow the request/response pattern and await the response, holding up the thread. I think my other option is the create another queue just for the consumer to publish to when the job is done. I've looked at this post: MassTransit3 how to make request from consumer, but I'm not sure how to implement this. My projects, again from this tutorial, looks like this:
Publisher:
static void Main(string[] args)
{
var bus = Bus.Factory.CreateUsingRabbitMq(x =>
x.Host(new Uri("rabbitmq://localhost/"), h => {}));
var busHandle = bus.Start();
var text = ""'
Console.WriteLine("Publisher");
while(text != "quit")
{
Console.Write("Enter a message: ");
text = Console.ReadLine();
var message = new SomethingHappenedMessage()
{
What = text,
When = DateTime.Now
}
bus.Publish(message);
}
busHandle.Stop();
}
Subscriber:
static void Main(string[] args)
{
var bus = Bus.Factory.CreateUsingRabbitMq(x =>
{
var host = x.Host(new Uri("rabbitmq://localhost"), h => {});
x.ReceiveEndpoint(host, "MtPubSubExample_TestSubscriber", e =>
e.Consumer<SomethingHappenedConsumer>());
});
Console.WriteLine("Subscriber");
var busHandle = bus.Start();
Console.ReadKey();
busHandle.Stop();
}
Consumer:
class SomethingHappenedConsumer : IConsumer<ISomethingHappened>
{
public Task Consume(ConsumeContext<ISomethingHappened> context)
{
Console.Write("TXT: " + context.Message.What);
Console.Write(" SENT: " + context.Message.When);
Console.Write(" PROCESSED: " + DateTime.Now);
Console.WriteLine(" (" + System.Threading.Thread.CurrentThread.ManagedThreadId + ")");
return Task.FromResult(0);
}
}
How would I go about creating a callback queue in the consumer?
In your consumer, just Bus.Publish(new ResponseMessage()); (or whatever you call your response) and have your publisher register a consumer for that message type. You publisher doesn't appear to have been bound to a queue, just so make up a queue name and bind it to a queue as well.
Thanks again to #Travis for the help. Just wanted to show the final code I ended up with for anyone in the future. The messaging looks funny for the response but it is correctly posting back to the publisher.
Publisher:
static void Main(string[] args)
{
var bus = Bus.Factory.CreateUsingRabbitMq(x =>
{
var host = x.Host(new Uri("rabbitmq://localhost/"), h => { });
x.ReceiveEndpoint(host, "MtPubSubExample_TestPublisher", e =>
e.Consumer<ResponseConsumer>());
});
var busHandle = bus.Start();
var text = "";
Console.WriteLine("Publisher");
while(text != "quit")
{
Console.Write("Enter a message: ");
text = Console.ReadLine();
var message = new SomethingHappenedMessage()
{
What = text,
When = DateTime.Now
};
bus.Publish(message);
}
busHandle.Stop();
}
Response Consumer:
class ResponseConsumer : IConsumer<IResponse>
{
public Task Consume(ConsumeContext<IResponse> context)
{
Console.WriteLine("RESPONSE MESSAGE: " + context.Message.Message);
return Task.FromResult(0);
}
}
Subscriber:
static void Main(string[] args)
{
var bus = Bus.Factory.CreateUsingRabbitMq(x =>
{
var host = x.Host(new Uri("rabbitmq://localhost/"), h => { });
x.ReceiveEndpoint(host, "MtPubSubExample_TestSubscriber", e =>
e.Consumer<SomethingHappenedConsumer>());
});
Console.WriteLine("Subscriber");
var busHandle = bus.Start();
Console.ReadKey();
busHandle.Stop();
}
Subscriber Consumer:
class SomethingHappenedConsumer : IConsumer<ISomethingHappened>
{
private IBusControl bus = Bus.Factory.CreateUsingRabbitMq(x =>
x.Host(new Uri("rabbitmq://localhost/"), h => { }));
public Task Consume(ConsumeContext<ISomethingHappened> context)
{
var now = DateTime.Now;
Console.Write("TXT: " + context.Message.What);
Console.Write(" SENT: " + context.Message.When);
Console.Write(" PROCESSED: " + now);
Console.WriteLine(" (" + System.Threading.Thread.CurrentThread.ManagedThreadId + ")");
var response = new ResponseMessage()
{
Message = "The request was processed at " + now
};
bus.Publish(response);
return Task.FromResult(0);
}
}
In my application i want users to be able to login with facebook and twitter.
For facebook i see there is a procedure ready for that ParseFacebookUtils but there isn't anything like that for Twitter so im making my own.
I have create an implementation for logging in with twitter:
void LoginToTwitter ()
{
var auth = new OAuth1Authenticator(
"<authkey>",
"<authsecret>",
new Uri("https://api.twitter.com/oauth/request_token"),
new Uri("https://api.twitter.com/oauth/authorize"),
new Uri("https://api.twitter.com/oauth/access_token"),
new Uri("http://twitter.com/"));
auth.Completed += GetTwitterData;
var ui = auth.GetUI(Activity);
StartActivity(ui);
}
async public void GetTwitterData( object sender, AuthenticatorCompletedEventArgs e )
{
var request = new OAuth1Request(
"GET",
new Uri("https://api.twitter.com/1.1/account/verify_credentials.json "),
null,
e.Account);
await request.GetResponseAsync().ContinueWith(t =>
{
var res = t.Result;
var resString = res.GetResponseText();
Console.WriteLine("Result Text: " + resString);
var jo = Newtonsoft.Json.Linq.JObject.Parse(resString);
var imageUrl = new Java.Net.URL((string)jo["profile_image_url"]);
var twitterId = jo["id"];
var accessToken = e.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(e.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds( expiresIn );
var userRealName = e.Account.Properties["screen_name"];
}, UIScheduler);
}
And now the only thing left is to associate there data With a new user or if the user exist to logg him in.
I see ParseFacebookUtils creates a randomly username for each user. In order for me to do something like that i must first check if the random generated username doesn't already exist, is it a good idea to use twitter username for that?
Also facebook stores something called authData of type authData with content like this:
{"facebook": {"access_token":"some_token","expiration_date":"some_date","id":"some_id"}}
How i can create something like that for twitter? i have already generate the required fields
I have successfully Login with twitter on Xamarin.Android with Parse.com
Here is how i manage to do it in case is useful to someone else, you will need components Xamarin.auth and RestSharp:
void LoginToTwitter ()
{
var auth = new OAuth1Authenticator(
"some_key",
"some_key",
new Uri("https://api.twitter.com/oauth/request_token"),
new Uri("https://api.twitter.com/oauth/authorize"),
new Uri("https://api.twitter.com/oauth/access_token"),
new Uri("https://mobile.twitter.com/"));
//save the account data in the authorization completed even handler
auth.Completed += GetTwitterData;
var ui = auth.GetUI(Activity);
StartActivity(ui);
}
public async void GetTwitterData( object sender, AuthenticatorCompletedEventArgs e )
{
//use the account object and make the desired API call
if (e.IsAuthenticated)
Console.WriteLine("Logged in");
var request = new OAuth1Request(
"GET",
new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"),
null,
e.Account, true);
await request.GetResponseAsync().ContinueWith(t =>
{
if (!t.IsFaulted && !t.IsCanceled){
var res = t.Result;
var resString = res.GetResponseText();
//Console.WriteLine("Result Text: " + resString);
var jo = Newtonsoft.Json.Linq.JObject.Parse(resString);
imageUrl = new Java.Net.URL((string)jo["profile_image_url"]);
var twitterId = jo["id"];
}
}, UIScheduler);
var userID = e.Account.Properties["user_id"];
var name = e.Account.Properties["screen_name"];
var oauth_consumer_key = e.Account.Properties["oauth_consumer_key"];
var oauth_consumer_secret = e.Account.Properties["oauth_consumer_secret"];
var oauth_token = e.Account.Properties["oauth_token"];
var oauth_token_secret = e.Account.Properties["oauth_token_secret"];
var authData = new Dictionary<string,string>();
authData.Add("user_id",userID.ToString());
authData.Add("screen_name",name.ToString());
authData.Add("oauth_consumer_key",oauth_consumer_key.ToString());
authData.Add("oauth_consumer_secret",oauth_consumer_secret.ToString());
authData.Add("oauth_token",oauth_token.ToString());
authData.Add("oauth_token_secret",oauth_token_secret.ToString());
await ParseLoginOrCreate(authData);
}
public async Task<ParseUser> ParseLoginOrCreate(Dictionary<string,string> authInfo)
{
var rest = new RestSharp.RestClient ("https://api.parse.com");
var req = new RestSharp.RestRequest ("1/users/", RestSharp.Method.POST);
req.AddHeader ("X-Parse-Application-Id", "some_key");
req.AddHeader ("X-Parse-REST-API-Key", "some_key");
req.AddHeader ("Content-Type", "application/json");
var payload = "{ \"authData\": { \"twitter\": { ";
payload += "\"id\": \"" + authInfo["user_id"] + "\", ";
payload += "\"screen_name\": \"" + authInfo["screen_name"] + "\", ";
payload += "\"consumer_key\": \"" + authInfo["oauth_consumer_key"] + "\", ";
payload += "\"consumer_secret\": \"" + authInfo["oauth_consumer_secret"] + "\", ";
payload += "\"auth_token\": \"" + authInfo["oauth_token"] + "\", ";
payload += "\"auth_token_secret\": \"" + authInfo["oauth_token_secret"] + "\" ";
payload += "} } }";
req.AddParameter("application/json", payload, RestSharp.ParameterType.RequestBody);
RestSharp.IRestResponse res = null;
var result = await Task<JContainer>.Run(()=>{
res = rest.Execute(req);
var content = res.Content;
return JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JContainer>(content);
});
var sessionToken = (String)result["sessionToken"];
var objectId = (String)result["objectId"];
if (res.StatusCode == System.Net.HttpStatusCode.Created)
{
req = new RestSharp.RestRequest ("1/users/" + objectId, RestSharp.Method.PUT);
req.AddHeader ("X-Parse-Application-Id", "some_key");
req.AddHeader ("X-Parse-REST-API-Key", "some_key");
req.AddHeader ("X-Parse-Session-Token", sessionToken);
req.AddHeader ("Content-Type", "application/json");
req.AddParameter("application/json", "{ \"username\": \"" + authInfo["screen_name"] + "\" }", RestSharp.ParameterType.RequestBody);
result = await Task<JContainer>.Run(() => {
res= rest.Execute(req);
var content = res.Content;
return JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JContainer>(content);
});
}
await ParseUser.BecomeAsync (sessionToken);
return ParseUser.CurrentUser;
}
I have problem with signalR with multiple client and async background task.
Here is my Scenario:
I have multiple clients doing multiple downloads.. they can download files simultaneously, I use signalR to send them the progress of there download. I handled it fine but the problem is when a single user invokes the Disconnect Method or he leaves or refresh its page, signalR will Disconnect all its client not only the one who is disconnecting which will interrupt the progress report for other client. How will I resolve this issue.?? Is there Any other way handling it??
additional:
private async Task WriteRecords([DataSourceRequest] DataSourceRequest dataRequest,int countno, VMEXPORT[] arrVmExport, bool createHeaderyn, string filePath )
{
string fileName = filePath.Replace(System.Web.HttpContext.Current.Server.MapPath("~/") + "Csv\\", "").Replace(".csv", "");
int datapage = (countno / 192322)+1;
for (int i = 1; i <= datapage; )
{
dataRequest.Page = i;
dataRequest.PageSize = 192322;
var write = _serviceAgent.FetchByRole("", "", CurrentUser.Linkcd, CurrentUser.Rolecd).ToDataSourceResult(dataRequest);
await Task.Run(()=>write.Data.Cast<AGENT>().WriteToCSV(new AGENT(), createHeaderyn, arrVmExport, filePath));
createHeaderyn = false;
i = i + 1;
double percentage = (i * 100) / datapage;
SendProgress(percentage, countno,fileName);
}
}
Here is the set up in my BaseController which calls the hub context:
public void SendNotification(string fileNametx, bool createdyn)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHubHelper>();
context.Clients.User(CurrentUser.Usernm + '-' + CurrentUser.GUID)
.receiveNotification("Export", CurrentUser.Usernm, "info", fileNametx, createdyn);
}
public void SendProgress(double recordCount, int totalCount,string fileName)
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHubHelper>();
context.Clients.User(CurrentUser.Usernm + '-' + CurrentUser.GUID).reportProgress(recordCount, totalCount,fileName);
}
And Here is my controller Method:
public async Task<ActionResult> _Export([DataSourceRequest] DataSourceRequest dataRequest, string columns,int countno, string menunm)
{
var fileNametx = AgentsPrompttx + DateTime.Now.ToString(GeneralConst.L_STRING_DATE4) + ".csv";
SendNotification(fileNametx, false);
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/") + "Csv\\";
var vmexport = new JavaScriptSerializer().Deserialize<VMEXPORT[]>(columns);
dataRequest.GroupingToSorting();
dataRequest.PageSize = 0; // set to zero
await WriteRecords(dataRequest,countno, vmexport, true, filePath + fileNametx);
SendNotification(fileNametx, true);
return File(filePath + fileNametx, WebConst.L_CONTENTTYPE_APP_OCTET, fileNametx);
}
JavaSciprt:
init: function (element) {
var self = this;
self.msgno = undefined;
self.sfiHubConnection = $.connection.signalRHubHelper;
self.initSignalRClients();
$.connection.hub.logging = true;
$.connection.hub.start({ transport: "longPolling" }).done(function () {
setTimeout(function () {
self.sfiHubConnection.server.getAllStatus();
self.sfiHubConnection.server.brodcastLogIn($('#usernm').text());
}, 1000);
}).fail(function () {
alert("signal Failed")
});
},
triggerReconnect: function () {
var self = this;
$.connection.hub.stateChanged(function (change) {
if (change.newState === $.signalR.connectionState.disconnected) {
$.connection.hub.stop();
self.init();
}
});
},
deleteFile: function (controllertx, filenametx) {
$('#close_dl_link').on('click', function () {
$.get(GetAppPath() + controllertx + '/_DeleteFile/?Filenametx='+filenametx, function () {
return true;
});
});
},
initSignalRClients: function () {
var self = this;
self.sfiHubConnection = $.connection.signalRHubHelper
self.sfiHubConnection.client.setOnline = function (usernm) {
if ($('#user_kgrid').data('kendoGrid') != undefined)
$('#user_kgrid').data('kendoGrid').tbody.find('td:contains("' + usernm + '")').eq(0).parent('tr').find('td:contains("Offline")').html('<span><i class="icon-ok-sign"></i></span> Online')
};
self.sfiHubConnection.client.receiveNotification = function (controller, totx, type, fileNametx, createdyn) {
if (totx == $('#usernm').text()) {
if (!createdyn) {
self.init();
var fileId=fileNametx.replace(".csv","")
var icon = "icon-download";
var title = fileId +':'+ ' <span id="' + fileId + '"></span> <br>';
var message = "Creating file kindly wait..";
var delay = 0;
SfiNotify(icon, title, message, 'info', "", "", "", "", delay);
}
else if (createdyn && fileNametx !== "") {
console.log("download available: "+fileNametx)
var elementid = fileNametx.replace(".csv", "");
$('#' + elementid).parents(".alert").each(function () {
$(this).remove();
});
var icon = "icon-download";
var title = " File ready for download !<br>" + "<strong>" + fileNametx + "</strong><br>";
var message = "Click here to download the file!";
var url = GetAppPath() + controller + '/_Download/?filenametx=' + fileNametx;
var delay = 0;
SfiNotify(icon, title, message, 'info', url, "", "", "", delay);
if ($('#close_dl_link').length > 0) {
self.deleteFile(controller, fileNametx);
}
}
}
else
return false;
};
self.sfiHubConnection.client.reportProgress = function (recordCount, totalRecord, fileName) {
var progress = recordCount + "% of " + totalRecord;
console.log("PROGRESS FOR: " + fileName + "TOTAL: "+recordCount);
if ($('#' + fileName).length > 0) {
if (recordCount > 100)
return false;
$('#' + fileName).text(progress);
}
else if($('#' + fileName).length == 0)
{
if (recordCount > 100)
return false;
var icon = "icon-download";
var title = ' Processing Records <span id=' + fileName + '>' + progress + '</span> <br>';
var message = "Creating file kindly wait..";
var delay = 0;
SfiNotify(icon, title, message, 'info', "", "", "", "", delay);
}
};