Firebase Realtime REST onDisconnect - c#

We are building a presence system for our Xamarin.Forms app that utilizes Firebase as it's backend.
Early in development we took the decision to use a wrapper library for the Realtime Database REST API (https://github.com/step-up-labs/firebase-database-dotnet) instead of using the native libraries for IOS & Android.
So far it has saved a great deal of time but now we are running into problems implementing a onDisconnect like system.
I have been digging in the Android and JS firebase libraries on github and found that the client libraries send a specific action parameter shown below. They seem to pass the constant "o" to indicate a onDisconnect push.
private static final String REQUEST_ACTION_ONDISCONNECT_PUT = "o";
...
#Override
public void onDisconnectPut(List<String> path, Object data, RequestResultCallback onComplete) {
this.hasOnDisconnects = true;
if (canSendWrites()) {
sendOnDisconnect(REQUEST_ACTION_ONDISCONNECT_PUT, path, data, onComplete);
} else {
onDisconnectRequestQueue.add(
new OutstandingDisconnect(REQUEST_ACTION_ONDISCONNECT_PUT, path, data, onComplete));
}
doIdleCheck();
}
Is there any way you can send this action parameter with the Firebase Realtime Database REST api?
Thank you for your time.
Cheers

The native Firebase Realtime Database SDKs for iOS, Android and Web use a persistent Web Socket to keep an open connection between each client and the server. The server uses this Web Socket to detect when the client disconnects, and when that happens it will execute any onDisconnect handlers that the client may have attached.
The Firebase Realtime Database's REST API is connectionless, as it uses regular HTTP(S) calls for the traffic between the client and server. There is no way to attach onDisconnect handlers through the REST API.

Related

Is there a way to send Cloud Messages or Push Notifications to a Flutter App from C#?

For my use case, a user from C# WinForm desktop application generates some data (creates a new document in a collection named "Requests" in Firestore). What I want is that whenever a new document is created/added in the Requests collection, a notification is sent to the Flutter app. I am looking for some guidelines for a workaround regarding this using C#.
I assume that you have already connected your C# software with firebase as backend. If that is the case then:
1- First connect your flutter app to firebase.
Follow this link to do so: Connect flutter app to firebase
2- Use this link to learn and create your first cloud function on firebase.
Create first cloud function from flutter app terminal
3- Now you are in the position to create a cloud function with which a notification will be generated to the device you want on the creation of document in the request collection.
4- Deploy this function on your firebase to send notification to your required device.
exports.sendFirstNotification =
functions.firestore.document('/Requests/{documentId}')
.onCreate(async (snap, context) => {
var name = "Bilal Saeed";
var myDeviceToken = snap.data().fcmToken;
// You need this token for push notification on a device.
// Each device has its own token.
// Access it in this function.
//If you are working on C# software then create your token from flutter app
//and save it on firestore. And access that token here and save it in myDeviceToken variable.
// Currently in this function its assumed that, the newly document created //in your Request collection contains the device token which is being //assigned to myDeviceToken variable.
await admin.messaging().send({
token: myDeviceToken,
notification: {
title: `Hi, you received first notification by the help of ${name}`,
body: " Upvote his answer if he really helped you!"
},
}).then(value => {
functions.logger.log("First notification sent to the device");
}).catch((e) =>{
functions.logger.log(e.toString());
});
});
Use this command from terminal to deploy your this function.
firebase deploy --only functions:sendFirstNotification
Now create the document from your C# software and you will get the notification on your flutter app mobile device on the creation of document in Requests Collection. Congrats!

How to connect my Xamarin app with local mySQL server?

I'm trying connect to mySQL server with code below: (just part of my whole code)
using MySql.Data.MySqlClient;
//...
public void ConnectToServer()
{
string ConnectionString =
"Server=DESKTOP-91JG566;Database=db_server;Uid=user;Pwd=123456A+;";
MySqlConnection cConn = new MySqlConnection(ConnectionString);
cConn.Open(); // this returns the exception
serverStatus = cConn.Ping() ? serverStatus = "connected" : serverStatus = "disconnected";
}
I'm using MySQL Workbench, there is my server with database https://i.stack.imgur.com/jxn84.jpg
The exception says: System.TypeInitializationException: 'The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.'
I have searched about it, and even though I enabled "SQL Server Debugging" in project properties, things are the same.
The problem might be caused because I have bad connection string, I am not sure.
My goal is to communicate with the server, query him, reveive orders etc...
As Jason already mentioned this is a horrible idea to do. Instead, I suggest you build some mini REST API or even use some of the serverless services out there.
When you have that REST API or Azure Function ready then you can communicate with them using your C# code, more precisely using HttpClient from the .NET.
Your mobile app will be the client which will "talk" to REST API, and REST API will proceed with your request and make the request to the DB, grab some data and return you JSON or XML which you can, later on, deserialize into C# objects and show to the user.
The most simple example is located on the MS Docs page here, so you can take a look.
Wishing you lots of luck with coding!

How to connect To Skype For Business using UCMA

I have a problem when I call LyncClient.Get() from a Windows Service project, knowing that it works well if I test on a console application.
var lyncClient = LyncClient.GetClient();
Dictionary<PublishableContactInformationType, object> statusData =
new Dictionary<PublishableContactInformationType, object>
{
{PublishableContactInformationType.LocationName, _position},
{PublishableContactInformationType.Availability, ContactAvailability.Busy}
};
The exception I get is:
Microsoft.Lync.Model.ClientNotFoundException: The host process is not running
at Microsoft.Lync.Model.LyncClient.EnsureOI ()
to Microsoft.Lync.Model.LyncClient.GetClient (Boolean sideBySideLync)
When doing research I read that in Windows service, we cannot get the Lync client by calling GetClient() because the service process and Lync process are in different sessions, that's why I'm trying to work with UCMA or UCWA but I do not understand how it works!
What I am trying to do in my application is to change the position of the skype user from a service. As it is not possible to do it with Lync Client SDK, I have to work with UCWA SDK but I can't find an example that i can follow him, A suggestion !
You are not talking about UCMA, you are talking about the Lync Client SDK.
You can think of the SDK's as such:
Lync Client SDK
This SDK allows you to remote control the standard "Lync Client". You can use this SDK to automate the Lync Client for a user to do whatever you can to do OR to extend the functionality of the Lync Client (kind-of limited). To use this SDK the Lync Client must be running in the user you wish to automate / extend. You can't really run it in a windows service context.
Also all Lync Client applications "share" the one Lync Client "session".
There is an option to run the Lync Client SDK in a "side by side" mode, but that mode is very very limited (i.e. no UI) and in most cases is not that useful.
UCMA
This SDK is a SIP endpoint SDK. It allows you to create and use two main type types of SIP endpoints:
User Endpoints
Trusted Application Endpoints
With sip endpoints you can do almost everything that a Lync Client SDK can do when automating the Lync Client (i.e. make calls, answer calls, set presence, subscribe to presence changes, etc, etc). There are some limitations, no video call support. Makes it harder to handle some situations.
UCMA allows you to create "trusted applications" that allow you to create sip endpoints used to extend S4B infrastructure. "trusted applications" / "trusted application endpoints" are "trusted" within S4B and are allowed to do things that you can't normally do with a simple UCMA application e.g. IVR
So it depends on what you are trying to do depends on what SDK you should use.
UCMA applications can be used in windows service applications.
UCWA is a web SDK version of UCMA (kind-of). The UCWA is a lot more limited than the UCMA SDK but UCWA works for Skype for Business Online whereas the UCMA doesn't directly work with Skype for Business Online. You can get UCMA working with Skype for Business Online using federation but that requires on-premise S4B setup federated to Skype for Business Online which is a lot of work.
Update:
To answer the comment question, location is part of the "presence". So what you need to do to set the location is to set the current presence with a location. For UCWA, see this MSDN link on setting the presence. Following the example, change which link you use to the "location" href and post something like:
{"location":"my new location"}
Why do you do it using a service? You could do it with a small console application that would be running in the background and invisible, and started at session startup.
This way you wouldn't need to know the user's login/password, you only need to poll in your code to wait for the Skype for Business client to be started (which I assume would be shortly after the session start)
Here is an example of what I mean :
class Program
{
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("Kernel32")]
private static extern IntPtr GetConsoleWindow();
const int SW_HIDE = 0;
static void Main(string[] args)
{
// Let's hide the console window first ...
IntPtr hwnd;
hwnd = GetConsoleWindow();
ShowWindow(hwnd, SW_HIDE);
// I recommend you start a separate thread from here, I removed it for the sake of simplicity
Boolean clientConnected = false;
while (!clientConnected)
{
try
{
LyncClient lyncClient = LyncClient.GetClient();
clientConnected = true;
// Do your stuff here...
}
catch (ClientNotFoundException ex)
{
// Client not found : the client is probably not running...
// There is nothing to do besides wait and expect to have the user starting his client...
clientConnected = false; // not needed, just to highlight the fact that we are not connected yet
}
// Don't forget to make your application sleep/do nothing on regular intervals to avoid taking 100% CPU time while you are polling
}
}
Of course users could manually kill the application by looking at their Task Manager, but most end users don't do that.

Massive SMS sender with c# and numbers from database

I have office program that I use for my work and there are a lot of partner information into database. One of column is Mobile Phone.
What I want to do is make is to connect my android phone to PC, run that office program and from there send one message to all partners from database.
How can I pass message and number to my android and then send sms?
I have read about sms sending from pc but I found something that works only with nokia phones, some programs, and something that is outdated.
My office program is made in c#/winfroms/firebird.
You have to write an api (Connection to users database and hande sending sms) with mvc and c# then you can write simple app in Android studio to send message to your api(with retrofit2 library). If you want more help. I can write some sudo code here.
If You have to send SMS by cell phone, you can get list of number by an api
MVC Api Controller to get Target Numbers from android:
public class SmsUsersController : ApiController
{
private Context db = new Context();
// GET: api/SmsUsers
public IQueryable<SmsUser> GetSmsUsers()
{
return db.SmsUsers;
}
}
and use retrofit to read api values:
http://square.github.io/retrofit/
Maybe a sms gateway can help you, https://github.com/ushahidi/SMSSync

C# windows service subscribed to webserver

I'm working on an intranet website.
All users should get desktop popups from the webserver whenever something new is posted on the website.
I was looking to make my own windows service that would subscribe to the server ( Making use of something like SignalR ) and then this service would show a simple popup notifying the user whenever the server sends out a message.
But instead of building this myself i was wondering if something like this isn't already out there. I've been looking around a bit but couldn't find anything.
I'm mainly a web developer and have never built a windows service or C# desktop application so i would prefer using some existing code.
Does anyone know of such a thing ?
For building a Windows Service try Top Shelf: http://docs.topshelf-project.com/en/latest/
In general it is easy as one, two, three...
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer(1000) {AutoReset = true};
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
public class Program
{
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name=> new TownCrier());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("Stuff");
x.SetServiceName("Stuff");
});
}
}
I'm working on an intranet website. All users should get desktop
popups from the webserver whenever something new is posted on the
website.
using timer is not a good technique over here as updates are not guaranteed in particular interval or session .but you can take that as an option based on the need.
I was looking to make my own windows service that would subscribe to
the server ( Making use of something like SignalR ) and then this
service would show a simple popup notifying the user whenever the
server sends out a message.
Yes exactly like a chat application that would frequently have messages and users get a pop up.ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.
But instead of building this myself i was wondering if something like
this isn't already out there. I've been looking around a bit but
couldn't find anything.
References for SignalR Link1,Link2,Link3
I'm mainly a web developer and have never built a windows service or
C# desktop application so i would prefer using some existing code.
Making C# desktop or windows service is not a big deal as you already are a programmer.Some existing codes for updations pop up is here.
for the signalr Server side, I would suggest you use a C# winform.
for the client side, you can use JavaScript inside any html file to 'receive' the message from the signalr Server, then you can popup an alert message or whatever you want, however, in this case you have to make sure the users are browsing that html file in a browser, otherwise the message won't be received.
there's no ready code since signalr support different types of servers as well as different types of clients, I believe you need to write your own code. Actually Signalr is quite easy to use, write your own code may be faster than using the others.
This question: SignalR Chat App in WinForm With Remote Clients looks like it might point you inthe right direction. Specifically this article:
https://damienbod.wordpress.com/2013/11/01/signalr-messaging-with-console-server-and-client-web-client-wpf-client/
you could probably use DesktopToast: https://github.com/emoacht/DesktopToast
or Growl: http://www.growlforwindows.com/

Categories