// When the app starts, check to make sure that we have
    // the required dependencies to use Firebase, and if not,
    // add them if possible.
    void Start()
    {
        dependencyStatus = FirebaseApp.CheckDependencies();
        if (dependencyStatus != DependencyStatus.Available)
        {
            FirebaseApp.FixDependenciesAsync().ContinueWith(task => {
                dependencyStatus = FirebaseApp.CheckDependencies();
                if (dependencyStatus != DependencyStatus.Available)
                {
                    Debug.LogError(
                        "Could not resolve all Firebase dependencies: " + dependencyStatus);
                }
            });
        }

        var appBucket = FirebaseApp.DefaultInstance.Options.StorageBucket;

        if (!String.IsNullOrEmpty(appBucket))
        {
            MyStorageBucket = String.Format("gs://{0}/", appBucket);
        }
    }
    void Awake()
    {
        //Using Firebase SDK
        //This is needed only for the unity editor
        FirebaseApp.DefaultInstance.SetEditorP12FileName("sweetseeds-abf2e299118d.p12");
        FirebaseApp.DefaultInstance.SetEditorServiceAccountEmail("*****@*****.**");
        FirebaseApp.DefaultInstance.SetEditorP12Password("notasecret");
        //--------------------------------------

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
            dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                InitializeFirebase();
            }
            else
            {
                Debug.LogError(
                    "Could not resolve all Firebase dependencies: " + dependencyStatus);
            }
        });
    }
Exemple #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("firebase-config.json"),
            });

            services.AddMvc(config =>
            {
                config.Filters.Add(typeof(ApiValidationFilterAttribute));
                config.EnableEndpointRouting = false;
            }).AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

            services.ConfigureDbContext(Configuration);
            services.ConfigureSwagger();
            services.ConfigureTokenAuth(Configuration);
            services.ConfigureCompression();
            services.ConfigureCors();
            services.ConfigureI18N();
            services.ConfigureHealthChecks(Configuration);
            services.ConfigureDetection();

            services.AddHttpContextAccessor();
            services.AddAutoMapper(typeof(Startup));

            // Creating the blob clients
            //CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Configuration.GetConnectionString("Azure"));
            //CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Adding the Azure blob clients as singletons
            //services.AddSingleton<CloudBlobClient>(blobClient);

            services.AddTransient <IUnitOfWork, UnitOfWork>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddTransient <IAccountService, AccountService>();
            services.AddTransient <ISettingService, SettingService>();
            services.AddTransient <IEmailService, EmailService>();
            services.AddTransient <ILogService, LogService>();
        }
Exemple #4
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseCors("MyPolicy");

            app.UseMvc();
            app.UseSwagger();
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Parking API V1"); });
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("D:\\FireBase\\perchedpeacockparking-firebase.json"),
            });
        }
Exemple #5
0
        void InitializeFirebase()
        {
            var app = FirebaseApp.InitializeApp(this);

            if (app == null)
            {
                var options = new FirebaseOptions.Builder()

                              .SetApplicationId("uber-clone-da636")
                              .SetApiKey("AIzaSyBpBjZCW6lj0r9KbfZ0ymvpzDziJvaJeu4")
                              .SetDatabaseUrl("https://uber-clone-da636.firebaseio.com")
                              .SetStorageBucket("uber-clone-da636.appspot.com")
                              .Build();

                app      = FirebaseApp.InitializeApp(this, options);
                database = FirebaseDatabase.GetInstance(app);
            }
            else
            {
                database = FirebaseDatabase.GetInstance(app);
            }
        }
Exemple #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "react-firebase-auth/build";
            });

            services.AddControllers();

            var pathToKey = Path.Combine(Directory.GetCurrentDirectory(), "keys", "firebase_admin_sdk.json");

            if (HostingEnvironment.IsDevelopment())
            {
                pathToKey = Path.Combine(Directory.GetCurrentDirectory(), "keys", "firebase_admin_sdk.local.json");
            }

            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromFile(pathToKey)
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                var firebaseProjectId             = Configuration["FirebaseProjectId"];
                options.Authority                 = $"https://securetoken.google.com/{firebaseProjectId}";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer   = true,
                    ValidIssuer      = $"https://securetoken.google.com/{firebaseProjectId}",
                    ValidateAudience = true,
                    ValidAudience    = firebaseProjectId,
                    ValidateLifetime = true
                };
            });
        }
Exemple #7
0
    public void Start()
    {
        signInButton.interactable = false;

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(continuationAction: task =>
        {
            var result = task.Result;
            if (result != DependencyStatus.Available)
            {
                Debug.Log(result.ToString());
                IsFirebaseReady = false;
            }
            else
            {
                IsFirebaseReady = true;

                firebaseApp  = FirebaseApp.DefaultInstance;
                firebaseAuth = FirebaseAuth.DefaultInstance;
            }
            signInButton.interactable = IsFirebaseReady;
        });
    }
Exemple #8
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            Instance          = this;
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            FirebaseApp.InitializeApp(this);

            facebookService = new AndroidFacebookService();
            firebaseService = new AndroidFirebaseService();

            App.FacebookService = facebookService;
            App.FirebaseService = firebaseService;

            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
Exemple #9
0
    void Initialization()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            var dependencyStatus = task.Result;
            if (dependencyStatus == Firebase.DependencyStatus.Available)
            {
                Debug.Log("Db connection is success");

                usersDatabase = FirebaseDatabase.DefaultInstance.GetReference("Users");

                GetUserList();

                var userId = "-MWytmqNEBdrj5rD9HJN";
                usersDatabase.Child(userId).ValueChanged += GetUserDetails;
            }
            else
            {
                Debug.LogError(string.Format("Hata {0}", dependencyStatus));
            }
        });
    }
        public void CreateAppOptions()
        {
            var credential = GoogleCredential.FromAccessToken("token");
            var options    = new AppOptions()
            {
                Credential        = credential,
                ProjectId         = "test-project",
                ServiceAccountId  = "*****@*****.**",
                HttpClientFactory = new MockHttpClientFactory(new MockMessageHandler()),
            };
            var app = FirebaseApp.Create(options);

            Assert.Equal("[DEFAULT]", app.Name);

            var copy = app.Options;

            Assert.NotSame(options, copy);
            Assert.Same(credential, copy.Credential);
            Assert.Equal("test-project", copy.ProjectId);
            Assert.Equal("*****@*****.**", copy.ServiceAccountId);
            Assert.Same(copy.HttpClientFactory, options.HttpClientFactory);
        }
Exemple #11
0
    // Start is called before the first frame update
    async void Start()
    {
        if (MainController.init == false)
        {
            var dependencyStatus = await FirebaseApp.CheckAndFixDependenciesAsync();

            if (dependencyStatus == DependencyStatus.Available)
            {
                OnFirebaseInitialized.Invoke();
            }



            //below this comment is additional code, added to the original
            await FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(continuationAction: task =>
            {
                FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
            });

            MainController.init = true;
        }
    }
Exemple #12
0
    //in order for a player to connect to the database, make sure this step happens first to set up the database instance
    public void CheckForDependencies()
    {
        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
            var dependencyStatus = task.Result;
            //Checks to make sure Database is ready to go
            if (dependencyStatus == DependencyStatus.Available)
            {
                //Setting up the Default Instance for the Database
                app = FirebaseApp.DefaultInstance;
                app.SetEditorDatabaseUrl("https://monster-defender.firebaseio.com/");
                FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);

                Test();
            }
            else
            {
                Debug.LogError(string.Format(
                                   "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
                // Firebase Unity SDK is not safe to use here.
            }
        });
    }
        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);
            });
        }
    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(gameObject);
            return;
        }
        _instance = this;
        DontDestroyOnLoad(gameObject);

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
        {
            if (task.Result == DependencyStatus.Available)
            {
                InitializeFirebase();
            }
            else
            {
                Debug.Log("Failed to resolve firebase dependencies. Error: " + task.Result);
            }
        });
    }
Exemple #15
0
        void InitializeFirebase()
        {
            var app = FirebaseApp.InitializeApp(this);

            if (app == null)
            {
                var options = new FirebaseOptions.Builder()

                              .SetApplicationId("ja-tour-c085e")
                              .SetApiKey("AIzaSyCEg0zuWx4rXBuhgBqUyvVEn4PKudIuums")
                              .SetDatabaseUrl("https://ja-tour-c085e.firebaseio.com")
                              .SetStorageBucket("ja-tour-c085e.appspot.com")
                              .Build();

                app   = FirebaseApp.InitializeApp(this, options);
                mAuth = FirebaseAuth.Instance;
            }
            else
            {
                mAuth = FirebaseAuth.Instance;
            }
        }
Exemple #16
0
        void InitializeFirebase()
        {
            var app = FirebaseApp.InitializeApp(this);

            if (app == null)
            {
                var options = new FirebaseOptions.Builder()

                              .SetApplicationId("uber-clone-8af91")
                              .SetApiKey("AIzaSyCXC1uk2DWYP10GJYU2r4vlN-U43Vu5F_g")
                              .SetDatabaseUrl("https://uber-clone-8af91.firebaseio.com")
                              .SetStorageBucket("uber-clone-8af91.appspot.com")
                              .Build();

                app      = FirebaseApp.InitializeApp(this, options);
                database = FirebaseDatabase.GetInstance(app);
            }
            else
            {
                database = FirebaseDatabase.GetInstance(app);
            }
        }
Exemple #17
0
        public void OrderByPriorityStringNumerics()
        {
            string json = @"
{  
    'users':{  
        'gracehop':{  
            '.priority': '1',
            'name':'Grace Hopper'
        },
        'physicsmarie':{  
            '.priority': 2,
            'name':'Marie Curie'
        },
        'adalovelave':{  
            '.priority': '3',
            'name':'Ada Lovelace'
        },
    }
}
";

            using (FirebaseApp app = AppFactory.FromJson(json))
            {
                ManualResetEvent done = new ManualResetEvent(false);

                var root  = app.Child("users");
                var query = root.OrderByPriority().Once("value", (snap, child, context) =>
                {
                    var list = snap.Children.ToList();
                    Assert.AreEqual("gracehop", list[0].Key);
                    Assert.AreEqual("physicsmarie", list[1].Key);
                    Assert.AreEqual("adalovelave", list[2].Key);

                    done.Set();
                });

                Assert.IsTrue(done.WaitOne(TimeSpan.FromSeconds(10)), "callback did not fire");
            }
        }
        public void OrderedAndLimited()
        {
            using (FirebaseApp app = AppFactory.Dinosaurs())
            {
                List <Tuple <string, int> > expected = new List <Tuple <string, int> >
                {
                    new Tuple <string, int>("bruhathkayosaurus", 55),
                    new Tuple <string, int>("linhenykus", 80),
                    new Tuple <string, int>("pterodactyl", 93),
                };

                List <Tuple <string, int> > actual = new List <Tuple <string, int> >();

                ManualResetEvent loaded = new ManualResetEvent(false);

                var fbRef = app.Child("/scores")
                            .OrderByValue()
                            .LimitToLast(expected.Count)
                            .On("value", (snap, childPath, context) =>
                {
                    Assert.IsTrue(snap.HasChildren);
                    Assert.AreEqual(expected.Count, snap.NumChildren);
                    actual.AddRange(
                        snap.Children.Select(child => new Tuple <string, int>(child.Key, child.Value <int>())));
                    loaded.Set();
                });

                Assert.IsTrue(loaded.WaitOne(TimeSpan.FromSeconds(5)), "Failed to load snapshot");

                Assert.AreEqual(expected.Count, actual.Count);

                for (int i = 0; i < expected.Count; i++)
                {
                    Assert.AreEqual(expected[i].Item1, actual[i].Item1);
                    Assert.AreEqual(expected[i].Item2, actual[i].Item2);
                }
            }
        }
Exemple #19
0
        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app
                .UseDeveloperExceptionPage()
                .UseGraphQLPlayground(new GraphQLPlaygroundOptions()
                {
                    Path = "/playground", GraphQLEndPoint = "/"
                })
                .UseGraphQLVoyager(new GraphQLVoyagerOptions()
                {
                    Path = "/voyager", GraphQLEndPoint = "/"
                });

                FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.FromFile(System.IO.Directory.GetCurrentDirectory() + "/.firebase/dev.json")
                });
            }
            else
            {
                FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.GetApplicationDefault()
                });
            }

            app
            .UseAuthentication()
            .UseGraphQL(options =>
            {
                options.Path             = "/";
                options.ExposeExceptions = Environment.IsDevelopment();
            })
            .UseDefaultFiles()
            .UseStaticFiles();
        }
Exemple #20
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ApplicationDbContext context,
                              RoleManager <ApplicationRole> roleManager,
                              UserManager <ApplicationUser> userManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            //app.UseCookiePolicy();

            app.UseAuthentication();

            SeedDatabase.Initialize(app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope().ServiceProvider);
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.GetApplicationDefault(),
            });
            app.UseMvc(routes =>
            {
                #region admin
                routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}");
                #endregion
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.AddHttpContextAccessor();
            services.AddScoped <ICurrentUserService, CurrentUserService>();

            services.AddScoped <IFirebaseService, FirebaseService>();

            FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromStream(
                    new MemoryStream(
                        Convert.FromBase64String(
                            Configuration["FirebaseServiceAccount"])))
            });

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, ApplicationRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            if (environment.IsProduction())
            {
                services.AddApplicationInsightsTelemetry();
            }
            services.AddSpaStaticFiles(configuration => configuration.RootPath = "ClientApp/IveArrivedAngular/dist/IveArrivedAngular");

            services.AddControllers()
            .AddJsonOptions(config => config.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

            services.AddSwaggerDocument();

            services.AddTransient <IFileService, FileService>();
        }
Exemple #22
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "Login" layout resource
            SetContentView(Resource.Layout.Login);

            // Call to "wire up" all our controls autoamticlly
            this.WireUpViews();
            btnSignIn.SetOnClickListener(this);
            btnSignOut.SetOnClickListener(this);
            btnRevokeAccess.SetOnClickListener(this);

            // Setup our firebase options then init
            FirebaseOptions o = new FirebaseOptions.Builder()
                                .SetApiKey(GetString(Resource.String.ApiKey))
                                .SetApplicationId(GetString(Resource.String.ApplicationId))
                                .SetDatabaseUrl(GetString(Resource.String.DatabaseUrl))
                                .Build();

            fa = FirebaseApp.InitializeApp(this, o, Application.PackageName);

            // Configure Google Sign In
            GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
                                      .RequestIdToken(GetString(Resource.String.ServerClientId))
                                      .RequestId()
                                      .RequestEmail()
                                      .Build();

            // Build our api client
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                               .EnableAutoManage(this, this)
                               .AddApi(Auth.GOOGLE_SIGN_IN_API, gso)
                               .Build();

            // Get the auth instance so we can add to it
            mAuth = FirebaseAuth.GetInstance(fa);
        }
Exemple #23
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            instance = instance ?? this;

            global::Xamarin.Forms.Forms.Init(instance, bundle);

            var senderId = "537007328900";

            var options = new FirebaseOptions.Builder()
                          .SetApplicationId("1:537007328900:android:08ab18baae5590c0")
                          .SetApiKey("AIzaSyDo1EkVamjhpceWdXcmxAPRYqbLEtMNLTw")
                          .SetGcmSenderId(senderId)
                          .Build();

            try
            {
                FirebaseApp.InitializeApp(instance, options);
            }
            catch (Exception) { }

            Task.Run(() =>
            {
                var instanceID = FirebaseInstanceId.Instance;
                instanceID.DeleteInstanceId();
                var iid1 = instanceID.Token;
                var iid2 = instanceID.GetToken(senderId, Firebase.Messaging.FirebaseMessaging.InstanceIdScope);
                Console.WriteLine("Iid1: {0}, iid2: {1}", iid1, iid2);
            });

            FirebaseMessaging.Instance.SubscribeToTopic("global");

            LoadApplication(new Piolhos.App.App());
        }
Exemple #24
0
        // Actually start the game, once we've verified that everything
        // is working and we have the firebase prerequisites ready to go.
        void StartGame()
        {
            // FirebaseApp is responsible for starting up Crashlytics, when the core app is started.
            // To ensure that the core of FirebaseApp has started, grab the default instance which
            // is lazily initialized.
            FirebaseApp app = FirebaseApp.DefaultInstance;

            // Remote Config data has been fetched, so this applies it for this play session:
            Firebase.RemoteConfig.FirebaseRemoteConfig.ActivateFetched();

            CommonData.prefabs    = FindObjectOfType <PrefabList>();
            CommonData.mainCamera = FindObjectOfType <CameraController>();
            CommonData.mainGame   = this;
            Firebase.AppOptions ops = new Firebase.AppOptions();
            CommonData.app = Firebase.FirebaseApp.Create(ops);

            // Setup database url when running in the editor
#if UNITY_EDITOR
            if (CommonData.app.Options.DatabaseUrl == null)
            {
                CommonData.app.SetEditorDatabaseUrl("https://YOUR-PROJECT-ID.firebaseio.com");
            }
#endif

            Screen.orientation = ScreenOrientation.Landscape;

            musicPlayer = CommonData.mainCamera.GetComponentInChildren <AudioSource>();

            CommonData.gameWorld = FindObjectOfType <GameWorld>();

            // Set up volume settings.
            MusicVolume = PlayerPrefs.GetInt(StringConstants.MusicVolume, MaxVolumeValue);
            // Set the music to ignore the listeners volume, which is used for sound effects.
            CommonData.mainCamera.GetComponentInChildren <AudioSource>().ignoreListenerVolume = true;
            SoundFxVolume = PlayerPrefs.GetInt(StringConstants.SoundFxVolume, MaxVolumeValue);

            stateManager.PushState(new States.Startup());
        }
Exemple #25
0
        /// <summary>
        /// Configure the <see cref="IUnityContainer"/>.
        /// </summary>
        /// <param name="container">The <see cref="IUnityContainer"/>.</param>
        public void ConfigureContainer(IUnityContainer container)
        {
            this.container = container;

            // setup firebase
            var firebaseApp = FirebaseApp.Create((new AppOptions
            {
                Credential = GoogleCredential.FromFile(Environment.GetEnvironmentVariable("GOOGLE_CREDENTIAL"))
            }));

            container.RegisterInstance(firebaseApp, new SingletonLifetimeManager());
            container.RegisterInstance(FirebaseMessaging.DefaultInstance,
                                       new SingletonLifetimeManager());

            // setup database
            var dbCreds = ReadDatabaseCredentials();

            if (dbCreds == null)
            {
                Console.WriteLine("Failed to connect to database. Exiting...");
                Environment.Exit(1);
            }

            var mongoClient = new MongoClient(
                $"mongodb://{dbCreds.Username}:{dbCreds.Password}@{dbCreds.Host}/{dbCreds.Database}");
            var db = mongoClient.GetDatabase(dbCreds.Database);

            container.RegisterInstance(db, new SingletonLifetimeManager());

            // repositories
            container.RegisterType(typeof(ILogger <>), typeof(MongoLogger <>),
                                   new ContainerControlledLifetimeManager());
            container.RegisterType <ITopicRepository, MongoTopicRepository>(new ContainerControlledLifetimeManager());

            // services
            container.RegisterType <ITopicsService, TopicsService>(new ContainerControlledLifetimeManager());
            container.RegisterType <IMessageService, FirebaseMessageService>(new ContainerControlledLifetimeManager());
        }
Exemple #26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string currentDirectory = Directory.GetCurrentDirectory();
            string path             = Path.Combine(currentDirectory, "etutorapp-25808-firebase-adminsdk-exwmv-656a0fd3f9.json");

            Console.WriteLine(path);
            Console.WriteLine("\n");

            string json = File.ReadAllText(path, Encoding.UTF8);

            var firebase = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(json)
            });

            Console.WriteLine(firebase.Name);

            FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;

            Message message = new Message
            {
                Notification = new Notification
                {
                    Title = "Simple Notification",
                    Body  = "Part of the body"
                },
                Token =
                    "crhm711-RDw:APA91bFtsuksmqhOzzGe7efmkRJIG7kknhZb31XsUJZszB1mkd3suKggOiTU6UShSUMKD4PT_SXz4E7VMeZDsk_kZbj1uUx005chJlcIe1dXINroX_T7tJmjNPiKuEfyVGZwCnLw2jAE"
            };

            var result = messaging.SendAsync(message);

            Task.WaitAll();

            Console.WriteLine($"RESULT MESSAGE: {result.Result}");
        }
 public void Init(Action completion)
 {
     dependencyStatus = FirebaseApp.CheckDependencies();
     if (dependencyStatus != DependencyStatus.Available)
     {
         FirebaseApp.FixDependenciesAsync().ContinueWith(task =>
         {
             dependencyStatus = FirebaseApp.CheckDependencies();
             if (dependencyStatus == DependencyStatus.Available)
             {
                 if (NumberOpens > 2)
                 {
                     Firebase.Messaging.FirebaseMessaging.TokenReceived   += OnTokenReceived;
                     Firebase.Messaging.FirebaseMessaging.MessageReceived += OnMessageReceived;
                 }
                 else
                 {
                     NumberOpens++;
                 }
                 if (completion != null)
                 {
                     completion.Invoke();
                 }
             }
             else
             {
                 Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
             }
         });
     }
     else
     {
         if (completion != null)
         {
             completion.Invoke();
         }
     }
 }
Exemple #28
0
        protected override void OnCreate(Bundle bundle)
        {
            base.Window.RequestFeature(WindowFeatures.ActionBar);

            base.SetTheme(Resource.Style.AppTheme_Main);
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

#if (!CUSTOM)
            FirebaseApp.InitializeApp(this);
#endif
            Xamarin.Essentials.Platform.Init(this, bundle);
            Rg.Plugins.Popup.Popup.Init(this, bundle);
            UserDialogs.Init(this);
            HUDTutorial.MainActivity = this;
            global::Xamarin.Forms.Forms.Init(this, bundle);

            OxyPlot.Xamarin.Forms.Platform.Android.PlotViewRenderer.Init();
            Xamarin.Forms.DependencyService.Register <AndroidNotificationService>();
            Xamarin.Forms.DependencyService.Register <HUDTutorial>();
            DependencyService.Register <CustomFirebaseRemoteConfig>();

            _theApp = new App();
            LoadApplication(_theApp);

            Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity = this;

            MessagingCenter.Subscribe <BudgetDataGridPage>(this, "Landscape", Page =>
            {
                RequestedOrientation = ScreenOrientation.Landscape;
            });
            MessagingCenter.Subscribe <BudgetDataGridPage>(this, "Portrait", Page =>
            {
                RequestedOrientation = ScreenOrientation.Portrait;
            });
        }
Exemple #29
0
        public void Basic()
        {
            string json = @"
{
    aaa: {
        test: 1
    },
    bbb: {
        test: '1'
    },
    ccc: {
        test: 3
    },
    ddd: {
    },
    eee: {
        test: {
            other: 'value'
        }
    },
    fff: 'value'
}
";

            using (FirebaseApp app = AppFactory.FromJson(json))
            {
                ManualResetEvent done = new ManualResetEvent(false);

                app.Child("/").OrderByChild("test").EqualTo(3).Once("value", (snap, child, context) =>
                {
                    Assert.AreEqual(1, snap.NumChildren);
                    Assert.AreEqual("ccc", snap.Children.First().Key);
                    done.Set();
                });

                Assert.IsTrue(done.WaitOne(TimeSpan.FromSeconds(5)));
            }
        }
Exemple #30
0
    private static int authPhases = 0;//1=authenticated; 0=none; -1=trying


    public static void Setup()
    {
        if (setupReady)
        {
            return;
        }

        FirebaseApp.LogLevel = LogLevel.Debug;

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task =>
        {
            var dependencyStatus = task.Result;
            if (dependencyStatus == DependencyStatus.Available)
            {
                // Create and hold a reference to your FirebaseApp,
                // where app is a Firebase.FirebaseApp property of your application class.
                FirebaseApp app = FirebaseApp.DefaultInstance;
                // Set a flag here to indicate whether Firebase is ready to use by your app.
                setupReady = true;
                // user default
                SetUserId(Application.buildGUID);

                //analytics
                FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
                FirebaseAnalytics.SetSessionTimeoutDuration(new TimeSpan(0, 30, 0));

                // listeners
                DynamicLinks.DynamicLinkReceived += OnDynamicLink;
            }
            else
            {
                Debug.LogError(System.String.Format(
                                   "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
                // Firebase Unity SDK is not safe to use here.
            }
        }
                                                                            );
    }
Exemple #31
0
 public FirebaseQuery(FirebaseApp app, FirebasePath path)
 {
     _app = app;
     _path = path;
     _filters = new List<ISubscriptionFilter>();
 }