private void CreateResponderInstance() { // Try getting the app first if (_responderFirebaseApp == null) { _responderFirebaseApp = FirebaseApp.GetInstance(_appName); } // If it still doesn't exist create it if (_responderFirebaseApp == null) { try { AppOptions options = new AppOptions(); options.ProjectId = FirebaseConfig.ResponderProjectId; options.ServiceAccountId = FirebaseConfig.ResponderProjectEmail; options.Credential = GoogleCredential.FromJson(FirebaseConfig.ResponderJsonFile); _responderFirebaseApp = FirebaseApp.Create(options, _appName); } catch (System.ArgumentException aex) { _responderFirebaseApp = FirebaseApp.GetInstance(_appName); } } }
void Start() { reference = FirebaseDatabase.DefaultInstance.RootReference; FirebaseApp.GetInstance("https://project-75a5c-default-rtdb.firebaseio.com/"); //GetCount(); RaadAllData(); }
public FirebaseMessaging GetMessaging(App app) { var messaging = memoryCache.GetOrCreate(app.FirebaseProject, entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5); var firebaseApp = FirebaseApp.GetInstance(app.Id); if (firebaseApp == null) { var appOptions = new AppOptions { Credential = GoogleCredential.FromJson(app.FirebaseCredential) }; appOptions.ProjectId = app.FirebaseProject; firebaseApp = FirebaseApp.Create(appOptions); } entry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration { EvictionCallback = (key, value, reason, state) => { firebaseApp.Delete(); } }); return(FirebaseMessaging.GetMessaging(firebaseApp)); }); return(messaging); }
void Start() { reference = FirebaseDatabase.DefaultInstance.RootReference; auth = FirebaseAuth.DefaultInstance; //SignupButton.onClick.AddListener(() => Signup(nameText.text, surnameText.text, emailText.text, usernameText.text, passwordText.text)); // SignupButton.onClick.AddListener(() => StartCoroutine(Register(emailText.text, passwordText.text, usernameText.text))); // SigninButton.onClick.AddListener(() => LoginAction(emailText.text, passwordText.text)); FirebaseApp.GetInstance("https://project-75a5c-default-rtdb.firebaseio.com/"); var dropdown = transform.GetComponent <Dropdown>(); //dropdown.options.Clear(); List <string> items = new List <string>(); items.Add("หญิง"); items.Add("ชาย"); foreach (var item in items) { dropdown.options.Add(new Dropdown.OptionData() { text = item }); } DropdownItemSelected(dropdown); dropdown.onValueChanged.AddListener(delegate { DropdownItemSelected(dropdown); }); }
// private string getLocalId; /* * * public void OnGetScore() * { * GetLocalId(); * } * * private void UpdateScore() * { * scoreText.text = "Score: " + user.userScore; * } */ void Start() { reference = FirebaseDatabase.DefaultInstance.RootReference; auth = FirebaseAuth.DefaultInstance; //SignupButton.onClick.AddListener(() => Signup(nameText.text, surnameText.text, emailText.text, usernameText.text, passwordText.text)); // SignupButton.onClick.AddListener(() => StartCoroutine(Register(emailText.text, passwordText.text, usernameText.text))); // SigninButton.onClick.AddListener(() => LoginAction(emailText.text, passwordText.text)); FirebaseApp.GetInstance("https://project-75a5c-default-rtdb.firebaseio.com/"); }
public void CreateNamedInstance() { const string name = "MyApp"; var app = FirebaseApp.Create(TestOptions, name); Assert.Equal(name, app.Name); Assert.NotNull(app.Options); Assert.Same(app, FirebaseApp.GetInstance(name)); Assert.Throws <ArgumentException>(() => FirebaseApp.Create(TestOptions, name)); app.Delete(); Assert.Null(FirebaseApp.GetInstance(name)); }
private void InitFirebaseAuth() { var options = new FirebaseOptions.Builder() .SetApplicationId("1:751090211993:android:1f5f18b0b912f072") .SetApiKey("AIzaSyB7r1qu1F9XI3VTRGxs069D8imvs3xkbAg") .Build(); if (app == null) { app = FirebaseApp.InitializeApp(this, options); } auth = FirebaseApp.GetInstance(app); }
// Start is called before the first frame update void Start() { reference = FirebaseDatabase.DefaultInstance.RootReference; FirebaseApp.GetInstance("https://project-75a5c-default-rtdb.firebaseio.com/"); button1.onClick.AddListener(delegate { Profile1(); }); button2.onClick.AddListener(delegate { Profile2(); }); button3.onClick.AddListener(delegate { Profile3(); }); button4.onClick.AddListener(delegate { Profile4(); }); button5.onClick.AddListener(delegate { Profile5(); }); button6.onClick.AddListener(delegate { Profile6(); }); button7.onClick.AddListener(delegate { Profile7(); }); button8.onClick.AddListener(delegate { Profile8(); }); button9.onClick.AddListener(delegate { Profile9(); }); CheckOlder(); }
// Start is called before the first frame update void Start() { winText1.SetActive(false); winText2.SetActive(false); reference = FirebaseDatabase.DefaultInstance.RootReference; FirebaseApp.GetInstance("https://project-75a5c-default-rtdb.firebaseio.com/"); FirebaseDatabase.DefaultInstance.GetReference(LoginManager.localId).GetValueAsync().ContinueWith(task => { DataSnapshot snapshot = task.Result; s = snapshot.Child(AddmemberManager.buttonKey).Child("helpOtherHistory").Value.ToString(); history = Int32.Parse(s); history += 1; }); }
//private async Task<IActionResult> SendNotification(List<ReminderNotificationResponseModel> reminders) //{ // int count = 0; // bool status = false; // string message; // string serverKey = _configuration["Firebase:Server_Key"]; // string senderId = _configuration["Firebase:SenderId"]; // string fcmLink = "https://fcm.googleapis.com/fcm/send"; // foreach (ReminderNotificationResponseModel reminder in reminders) // { // var notificationData = new NotificationModel() // { // Notification = new NoteModel() // { // Title = reminder.Title, // Body = reminder.Desciption // }, // To = reminder.Token // }; // //var httpWebRequest = (HttpWebRequest)WebRequest.Create(fcmLink); // //httpWebRequest.ContentType = "application/json"; // //httpWebRequest.Headers.Add(string.Format("Authorization: Key={0}", serverKey)); // //httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); // //httpWebRequest.Method = "POST"; // //var json = JsonConvert.SerializeObject(notificationData); // //var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); // //var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // //string jsonMessage = JsonConvert.SerializeObject(notificationData); // //var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, fcmLink); // //request.Headers.TryAddWithoutValidation("Authorization", "key=" + serverKey); // //request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json"); // //HttpResponseMessage result; // //using(var client = new HttpClient()) // //{ // // result = await client.SendAsync(request); // //} // using (var client = new HttpClient()) // { // // client.BaseAddress = new Uri("https://fcm.googleapis.com/"); // // client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); // // client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={serverKey}"); // // client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={senderId}"); // // var json = JsonConvert.SerializeObject(notificationData); // // var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); // var request = new HttpRequestMessage // { // RequestUri = new Uri("https://fcm.googleapis.com/fcm/send"), // Method = System.Net.Http.HttpMethod.Post, // Headers = // { // { HttpRequestHeader.Authorization.ToString(), "Key="+serverKey }, // { HttpRequestHeader.ContentType.ToString(), "application/json" } // }, // Content = new StringContent(JsonConvert.SerializeObject(notificationData)) // }; // //request.Headers.Add("Content-Type", "application/json"); // //request.Headers.TryAddWithoutValidation("Authorization", _configuration["Firebase:Server_Key"]); // HttpResponseMessage httpResponse = await client.SendAsync(request); // if (httpResponse.IsSuccessStatusCode) // count++; // } // } // if (count == reminders.Count) // { // status = true; // message = "Reminder Notification Send Successfully"; // return Ok(new { status, message }); // } // else // { // message = "Unable to Send Notification"; // return Ok(new { status, message }); // } //} /// <summary> /// It Notify the user of upcoming note reminder /// </summary> /// <param name="reminders">contains all data to send notification</param> /// <returns></returns> private async Task <int> FirebaseNotification(List <ReminderNotificationResponseModel> reminders) { string result; int count = 0; var path = _environment.ContentRootPath; path += "\\firebase.json"; FirebaseApp app; try { app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(path) }, "FundooNotes"); } catch { app = FirebaseApp.GetInstance("FundooNotes"); } var fcm = FirebaseMessaging.GetMessaging(app); foreach (ReminderNotificationResponseModel reminder in reminders) { Message message = new Message() { Notification = new Notification { Title = reminder.Title, Body = reminder.Desciption }, Token = reminder.Token }; result = await fcm.SendAsync(message); count++; } return(count); }
private async Task <string> SendNotificationAsync(string title, string body) { var path = env.ContentRootPath; path = path + "\\Auth.json"; FirebaseApp app = null; try { app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(path) }, "sl-health-info"); } catch (Exception ex) { app = FirebaseApp.GetInstance("sl-health-info"); } var fcm = FirebaseAdmin.Messaging.FirebaseMessaging.GetMessaging(app); Message message = new Message() { Notification = new Notification { Title = title, Body = body }, Data = new Dictionary <string, string>() { { "click_action ", "FLUTTER_NOTIFICATION_CLICK" }, }, Topic = "allUsers" }; var result = await fcm.SendAsync(message); return(result); }
private static void AddFireBaseMessaging(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton(service => { var path = configuration.GetSection("Firebase.Settings")["PathToCredentials"]; FirebaseApp app; try { app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(path) }, "FBApp"); } catch (Exception) { app = FirebaseApp.GetInstance("FBApp"); } var messagingInstance = FirebaseMessaging.GetMessaging(app); return(messagingInstance); }); }
public KEFirebaseAdmin(String AppName) { try { if (FirebaseApp.GetInstance(name: AppName) == null) { string pathJSON = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"app_services.json", ""); string pathJSONFirebase = ""; using (StreamReader file = File.OpenText(pathJSON)) using (JsonTextReader reader = new JsonTextReader(file)) { JObject o2 = (JObject)JToken.ReadFrom(reader); try { pathJSONFirebase = o2[AppName].ToString(); } catch (Exception e) { throw new Exception(KEFirebaseErrorMessage.NO_APP); } } Console.WriteLine("pathJSONFirebase: " + pathJSONFirebase); string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, pathJSONFirebase, ""); FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(path), }, AppName); } _AppName = AppName; } catch (Exception e) { throw new Exception(e.Message); } }
void Start() { reference = FirebaseDatabase.DefaultInstance.RootReference; FirebaseApp.GetInstance("https://project-75a5c-default-rtdb.firebaseio.com/"); FirebaseDatabase.DefaultInstance.GetReference(LoginManager.localId).GetValueAsync().ContinueWith(task => { DataSnapshot snapshot = task.Result; passwordUser = snapshot.Child("User").Child("password").Value.ToString(); string s = snapshot.Child("User").Child("gender").Value.ToString(); gender = Int32.Parse(s); string s2 = snapshot.Child("User").Child("userName").Value.ToString(); name = s2; }); GetCount(); //print(count+"Start"); Invoke("AddButtons", 3); // AddButtons(); FirebaseDatabase.DefaultInstance.GetReference(LoginManager.localId) // หากข้อมูลมีการเปลี่ยนแหลงให้ทำการอ่านและแสดง .ValueChanged += HandleValueChanged; }
public static FirestoreWrapper GetFirestore(string appName) { var app = FirebaseApp.GetInstance(appName); return(_firestores.GetOrAdd(FirebaseFirestore.GetInstance(app), key => new Lazy <FirestoreWrapper>(() => new FirestoreWrapper(key))).Value); }
public static AuthWrapper GetAuth(string appName) { var app = FirebaseApp.GetInstance(appName); return(GetAuth(Firebase.Auth.FirebaseAuth.GetInstance(app))); }
public void GetInstanceWithInvalidName() { Assert.Throws <ArgumentException>(() => FirebaseApp.GetInstance(null)); Assert.Throws <ArgumentException>(() => FirebaseApp.GetInstance(string.Empty)); }
protected override IEnumerable <Prompt> Execute_Subclass() { // Make sure to connect to a EWS server if (!IsConnected) { return new List <Prompt> { CreateCannotConnectPrompt() } } ; //throw new NotImplementedException(); if (!DataAdapter.Server.IsRunning) { DataAdapter.StartServer(); } EnsureServerParameters(); var alarmReader = new AlarmItemReader { Address = this.EsAddress, UserName = this.UserName, Password = this.Password, AlarmTypesFilter = new List <string>(), }; if (app == null && FirebaseApp.GetInstance("[DEFAULT]") == null) { try { app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile(serviceAccountKeyLocation) .CreateScoped("https://www.googleapis.com/auth/firebase.messaging") }); } catch (Exception ex) { Logger.LogError(LogCategory.Processor, this.Name, $"Failed to connect to FCM service."); prompts.Add(ex.ToPrompt()); return(prompts); } } try { do { readAlarms(alarmReader); Thread.Sleep(10000); } while (!IsCancellationRequested); } catch (Exception ex) { Logger.LogError(LogCategory.Processor, "Update Processor Exception", ex.ToString()); } return(prompts); } void readAlarms(AlarmItemReader alarmReader) { var result = alarmReader.ReadData(); var lastUpdated = alarmReader.LastUpdate; if (result.Success) { var alarmList = result.DataRead.Where(x => x.State == (Ews.Common.EwsAlarmStateEnum.Active)).OrderByDescending(x => x.Transition); messaging = FirebaseMessaging.GetMessaging(FirebaseApp.GetInstance("[DEFAULT]")); if (alarmList.Count() > 0) { foreach (var alarm in alarmList) { if (!SendNotification(CreateMessage(alarm), messaging).Result) { prompts.Add(new Prompt { Message = "message sent unsuccessful" }); } } } } else { Logger.LogDebug(LogCategory.Processor, $"Alarm read failed."); } }
public void GetNonExistingInstance() { Assert.Null(FirebaseApp.GetInstance("non.existing")); }
public async Task <string> sendNotificationByTokens(string NotificationTypeMode, List <string> Tokens, Dictionary <String, String> data, Notification notification, string topic = null, string androidIcon = null, string androidColor = null, int apnsBadge = -1) { var returnStr = ""; try { var message = new MulticastMessage(); //type of notification needed if (NotificationTypeMode == NotificationType.DATA) { message.Data = data; } if (NotificationTypeMode == NotificationType.NOTIFICATION) { message.Notification = notification; } if (NotificationTypeMode == NotificationType.BOTH) { if (data != null) { message.Data = data; } message.Notification = notification; } else { throw (new Exception(KEFirebaseErrorMessage.WRONG_NOTIFICATION_TYPE_MODE)); } if (!Tokens.Any()) { throw (new Exception(KEFirebaseErrorMessage.EMPTY_TOKENS)); } message.Tokens = Tokens; if (!string.IsNullOrEmpty(androidIcon) || !string.IsNullOrEmpty(androidColor)) { message.Android = new AndroidConfig() { Notification = new AndroidNotification() { Icon = androidIcon == null ? "" : androidIcon, Color = androidColor == null ? "" : androidColor, } }; } //APNs Config if (apnsBadge != -1) { message.Apns = new ApnsConfig() { Aps = new Aps() { Badge = apnsBadge }, }; } BatchResponse response = await FirebaseMessaging.GetMessaging( FirebaseApp.GetInstance(name: _AppName) ).SendMulticastAsync(message); if (response.FailureCount > 0) { var failedTokens = new List <string>(); for (var i = 0; i < response.Responses.Count; i++) { if (!response.Responses[i].IsSuccess) { // The order of responses corresponds to the order of the registration tokens. failedTokens.Add(Tokens[i]); } } returnStr = string.Join(",\n ", failedTokens.ToArray()); Console.WriteLine("sendToDevicesList Failure for: "); Console.WriteLine($"List of tokens that caused failures: \n {returnStr}"); } returnStr = $"Sent batch message to app: {_AppName}, Success: {response.SuccessCount}, Failure: {response.FailureCount}"; } catch (Exception e) { var errorMsg = e.Message; Console.WriteLine("sendToDevicesList Failure sent message: " + errorMsg); string msg = e.Message; if (e.InnerException != null) { msg += " <br>@ " + e.InnerException.StackTrace; msg += " <br>@ " + e.InnerException.Message; if (e.InnerException.InnerException != null) { msg += " <br>@ " + e.InnerException.InnerException.StackTrace; msg += " <br>@ " + e.InnerException.InnerException.Message; } } returnStr = msg; } return(returnStr); }
public static AuthWrapper GetAuth(string appName) { var app = FirebaseApp.GetInstance(appName); return(_auths.GetOrAdd(Firebase.Auth.FirebaseAuth.GetInstance(app), key => new Lazy <AuthWrapper>(() => new AuthWrapper(key))).Value); }
public static FirestoreWrapper GetFirestore(string appName) { var app = FirebaseApp.GetInstance(appName); return(GetFirestore(FirebaseFirestore.GetInstance(app))); }
public async Task <string> sendNotificationByTopic(string NotificationTypeMode, String topic, Dictionary <String, String> data, Notification notification, string androidIcon = null, string androidColor = null, int apnsBadge = -1) { var returnStr = ""; try { var message = new Message(); //type of notification needed if (NotificationTypeMode == NotificationType.DATA) { message.Data = data; } if (NotificationTypeMode == NotificationType.NOTIFICATION) { message.Notification = notification; } if (NotificationTypeMode == NotificationType.BOTH) { if (data != null) { message.Data = data; } message.Notification = notification; } else { throw new Exception(KEFirebaseErrorMessage.WRONG_NOTIFICATION_TYPE_MODE); } if (topic != null) { message.Topic = topic; } else { throw new Exception(KEFirebaseErrorMessage.EMPTY_TOPIC); } if (!string.IsNullOrEmpty(androidIcon) || !string.IsNullOrEmpty(androidColor)) { message.Android = new AndroidConfig() { Notification = new AndroidNotification() { Icon = androidIcon == null ? "" : androidIcon, Color = androidColor == null ? "" : androidColor, } }; } //APNs Config if (apnsBadge != -1) { message.Apns = new ApnsConfig() { Aps = new Aps() { Badge = apnsBadge }, }; } string response = await FirebaseMessaging.GetMessaging( FirebaseApp.GetInstance(name: _AppName) ).SendAsync(message); returnStr = $"Successfully sent message to app: {_AppName} with topic: {topic}"; } catch (Exception ex) { var errorMsg = ex.Message; Console.WriteLine("sendNotificationByTopic Failed: " + errorMsg); string msg = ex.Message; if (ex.InnerException != null) { msg += " <br>@ " + ex.InnerException.StackTrace; msg += " <br>@ " + ex.InnerException.Message; if (ex.InnerException.InnerException != null) { msg += " <br>@ " + ex.InnerException.InnerException.StackTrace; msg += " <br>@ " + ex.InnerException.InnerException.Message; } } Console.WriteLine(returnStr + msg); throw new Exception(ex.Message); } return(returnStr); }