public WebListener()
        {
            FirebaseConfig config = new FirebaseConfig {
                BasePath = "https://splatmap.firebase.com/clouds"
            }
            cloudsClient = new FirebaseClient(config);

            // start listening
            await cloudsClient.OnAsync("push", (sender, args) => {
                   System.Console.WriteLine(args.Data);
            });
        }
Пример #2
22
        public async Task UpdateFireblob(CloudBlobContainer blobContainer)
        {

            try
            {
                IFirebaseConfig config = new FirebaseConfig
                {
                    AuthSecret = "Gg5t1fSLC0WWPVM1VMoNxlM29qO1s53dEso7Jrfp",
                    BasePath = "https://ringtoneapp.firebaseio.com/"
                };

                IFirebaseClient client = new FirebaseClient(config);
                var list = blobContainer.ListBlobs();
                List<CloudBlockBlob> blobNames = list.OfType<CloudBlockBlob>().ToList();

                // SET
                var todo = new Todo();

                List<Todo> todoList = new List<Todo>();
                List<UploadDataModel> MetaList = new List<UploadDataModel>();
                foreach (var blb in blobNames)
                {
                    blb.FetchAttributes();
                    Todo td = new Todo();
                    td.name = blb.Name;
                    td.url = blb.Uri.AbsoluteUri.ToString();
                    if (blb.Metadata.Values.Count > 0)
                    {
                        td.Category = blb.Metadata.Values.ElementAt(0);
                        td.UserName = blb.Metadata.Values.ElementAt(1);
                        td.Number = blb.Metadata.Values.ElementAt(2);
                        td.Email = blb.Metadata.Values.ElementAt(3);
                        td.Comments = blb.Metadata.Values.ElementAt(4);
                    }
                    todoList.Add(td);
                }

                SetResponse response = await client.SetAsync(FirebaseContainer, todoList);
                List<Todo> setresult = response.ResultAs<List<Todo>>();
            }
            catch (Exception e)
            {

            }

            //GET
            //FirebaseResponse getresponse = await client.GetAsync("ringtones");
            //List<Todo> gettodo = response.ResultAs<List<Todo>>(); //The response will contain the data being retreived
        }
Пример #3
3
 public IFirebaseClient GetFirebaseClient()
 {
     var node = "https://dazzling-inferno-4653.firebaseio.com/";
     IFirebaseConfig config = new FirebaseConfig
     {
         AuthSecret = _firebaseSecret,
         BasePath = node
     };
     IFirebaseClient client = new FirebaseClient(config);
     return client;
 }
Пример #4
2
        private async void MainPage_OnLoaded(object sender, RoutedEventArgs e)
        {

            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = FirebaseSecret,
                BasePath = BasePath
            };

            _client = new FirebaseClient(config);

            await _client.OnAsync("chat",
                added: (s, args) =>
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        TextBox1.Text = args.Data + " -> 1(ADDED)";
                    });
                },
                changed: (s, args) =>
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        TextBox2.Text = string.Format("Data :{0}, Path: {1} -> 1(CHANGED)", args.Data, args.Path);
                    });
                },
                removed: (s, args) =>
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        TextBox3.Text = args.Path + " -> 1(REMOVED)";
                    });
                });

            await _client.OnAsync("chat",
                added: (s, args) =>
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        TextBox4.Text = args.Data + " -> 2(ADDED)";
                    });
                },
                changed: (s, args) =>
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        TextBox5.Text = string.Format("Data :{0}, Path: {1} -> 2(CHANGED)", args.Data, args.Path);
                    });
                },
                removed: (s, args) =>
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        TextBox6.Text = args.Path + " -> 2(REMOVED)";
                    });
                });
        }
Пример #5
1
		public PlatoRepository(IOptions<FirebaseAuth> fireOp,
							   IMemoryCache cache)
		{
			client=new FirebaseClient(new FirebaseConfig{
				AuthSecret=fireOp.Options.Secret,
				BasePath=fireOp.Options.Url
			});
			_chache=cache;
			
		}
        //CONSTRUCTOR
        public ProfileViewModel()
        {
            //Initializes the connection to the Firebase database
            config = new FirebaseConfig
            {
                AuthSecret = FirebaseSecret,
                BasePath = BasePath
            };

            client = new FirebaseClient(config);


            //Attempts to get the online copy
            try
            {
                getOnlineProfile();
            }

            //If it's unable to, use the local copy
            catch (Exception)
            {
                getLocalProfile();
            }
        }
        public string PushFireBaseData(string AuthSecret, string BasePath, string item)
        {
            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = AuthSecret,
                BasePath = BasePath
            };

            IFirebaseClient client = new FirebaseClient(config);

            var todo = new
            {
                name = "Execute PUSH",
                priority = 2
            };

            PushResponse response = client.Push(item, todo);

            string retorno = JsonConvert.SerializeObject(response).ToString();

            return retorno;
        }
        static void Main(string[] args)
        {
            IFirebaseConfig config = new FirebaseConfig
            {
                BasePath = "https://simplephonenotify.firebaseio.com/"
            };
            IFirebaseClient client = new FirebaseClient(config);
            Random ran = new Random();

            string input = "";
            while (!input.Equals("quit"))
            {
                Console.Write("Enter input: ");
                input = Console.ReadLine();
                Console.WriteLine(input);

                var item = new Item
                {
                    Name = input,
                    Amount = ran.Next(1, 30)
                };
                client.Push("items", item);
                Console.WriteLine(item);
            }

            Console.WriteLine("Finished");
            Console.WriteLine(input);
        }
Пример #9
0
 // GET: Sermon
 public ActionResult Sermon(string id)
 {
     FirebaseClient client = new FirebaseClient(config);
     var response = client.Get("/sermons");
     var json = JsonConvert.DeserializeObject(response.Body);
     var sermon = new Sermon();
     JToken selectedSermon = null;
     foreach (JToken item in ((JToken)(json)).Children())
     {
         var prop = ((JToken)(JsonConvert.DeserializeObject(((JProperty)(item)).Value.ToString()))).Children();
         foreach (var obj in prop)
         {
             var ser = (JProperty)(obj);
             if (ser.Name == "ID" && ser.Value.ToString() == id)
             {
                 selectedSermon = item;
             }
         }
     }
     var property = ((JToken)(JsonConvert.DeserializeObject(((JProperty)(selectedSermon)).Value.ToString()))).Children();
     foreach (var obj in property)
     {
         var ser = (JProperty)(obj);
         if (ser.Name == "Name")
         {
             sermon.Name = ser.Value.ToString();
         }
         else if (ser.Name == "About")
         {
             var tag = HTMLTagStripper.StripTagsCharArray(ser.Value.ToString());
             sermon.About = tag;
         }
         else if (ser.Name == "ID")
         {
             sermon.ID = ser.Value.ToString();
         }
         else if (ser.Name == "Art")
         {
             sermon.Art = ser.Value.ToString();
         }
         else if (ser.Name == "SmallArt")
         {
             sermon.SmallArt = ser.Value.ToString();
         }
         else if (ser.Name == "Audio")
         {
             sermon.Audio = ser.Value.ToString();
         }
     }
     this.ViewData.Add("ID", sermon.ID);
     this.ViewData.Add("name", sermon.Name);
     this.ViewData.Add("content", sermon.About);
     this.ViewData.Add("art", sermon.Art);
     this.ViewData.Add("smallArt", sermon.SmallArt);
     this.ViewData.Add("audio", sermon.Audio);
     return View();
 }
Пример #10
0
        private async void Load(object obj)
        {
            // https://github.com/rlamasb/Firebase.Xamarin
            // https://github.com/williamsrz/xamarin-on-fire/blob/master/XOF.Droid/Services/FirebaseService.cs
            
            string firebaseToken = UserSettings.GetFirebaseAuthToken();
            var firebase = new FirebaseClient("https://expensetrackermvp.firebaseio.com/");

            // Get one
            Expense exp = await firebase.Child("Expenses").Child("1").WithAuth(firebaseToken).OnceSingleAsync<Expense>();
            ExpenseCollection.Add(exp);
            
            /*var items = await firebase
              .Child("Expenses")
              .OrderByKey()
              .WithAuth(firebaseToken)                           
              .OnceAsync<Expense>();
                        
            foreach (var item in items)
            {
                Expense exp = item.Object;
                ExpenseCollection.Add(exp);                
            }*/





            /* Using custom api 
            string url = GetApiServiceURL("Expenses");
            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Other");
            var response = httpClient.GetAsync(url).Result;            

            if (response.IsSuccessStatusCode)
            {
                var content = response.Content;
                var responseContent = content.ReadAsStringAsync().Result;

                JArray json = JArray.Parse(responseContent);
                                
                foreach (JToken item in json)
                {

                    //string desc = JToken.Parse(JToken.Parse(responseContent)[0])["Description"].Value;
                    //Expense exp = new Expense();
                    //exp.Description = desc.Value<string>();
                            
                    Expense e = item.ToObject<Expense>();                   
                    
                    ExpenseCollection.Add(e);                    
                }
            }
            */

        }
Пример #11
0
 public IFirebaseClient GetFirebaseClient(string node)
 {
     IFirebaseConfig config = new FirebaseConfig
     {
         AuthSecret = _firebaseSecret,
         BasePath = node
     };
     IFirebaseClient client = new FirebaseClient(config);
     return client;
 }
Пример #12
0
 public static FireBaseRetorno GetFireBaseData(FireBaseEntrada Entrada)
 {
     IFirebaseConfig config = new FirebaseConfig{ AuthSecret = Entrada.AuthSecret, BasePath = Entrada.BasePath};
     IFirebaseClient client = new FirebaseClient(config);
     FirebaseResponse response = client.Get(Entrada.item.ToString());
      FireBaseRetorno retorno = new FireBaseRetorno {StatusCode = response.StatusCode.ToString(), Body = response.Body};
     retorno.StatusCode = response.StatusCode.ToString();
     retorno.Body = response.Body;
     return retorno;
 }
Пример #13
0
        private FirebaseManager ()
        {
            var config = new FirebaseConfig
            {
                AuthSecret = FirebaseSecret,
                BasePath = BasePath
            };

            _client = new FirebaseClient (config);
            GetNewestVideos(true);
        }
Пример #14
0
 public IFirebaseClient GetFirebaseClient()
 {
     //var node = "https://dazzling-inferno-4653.firebaseio.com/";
     var node = ConfigurationManager.AppSettings["FirebaseUrl"] ??
                CloudConfigurationManager.GetSetting("FirebaseUrl");
     IFirebaseConfig config = new FirebaseConfig
     {
         AuthSecret = _firebaseSecret,
         BasePath = node
     };
     IFirebaseClient client = new FirebaseClient(config);
     return client;
 }
Пример #15
0
        public async Task<string> retrieveSupportStringForId(int id)
        {
            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = "WtyRxZxUb94IPMpd0ho9VlCdvpTDz7yO7dGCY42F",
                BasePath = "https://globaltechsupport.firebaseio.com/"
            };

            FirebaseClient firebase = new FirebaseClient(config);
            string url = "https://globaltechsupport.firebaseio.com/" + id;
            FirebaseResponse response = await firebase.GetAsync(id.ToString());
            return response.ResultAs<string>();
        }
Пример #16
0
        private static void Main()
        {
            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = FirebaseSecret,
                BasePath = BasePath
            };

            _client = new FirebaseClient(config); //Uses JsonNet default

            EventStreaming();
            //Crud();

            System.Console.Read();
        }
        public string DeleteFireBaseData(string AuthSecret, string BasePath, string item)
        {
            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = AuthSecret,
                BasePath = BasePath
            };

            IFirebaseClient client = new FirebaseClient(config);

            FirebaseResponse response = client.Delete(item);

            string retorno = JsonConvert.SerializeObject(response).ToString();

            return retorno;
        }
Пример #18
0
        protected override void FinalizeSetUp()
        {
            _expected = new Todo
            {
                name = "Do your homework!",
                priority = 1
            };

            _firebaseRequestManagerMock = MockFor<IRequestManager>();

            _expectedResponse = new HttpResponseMessage
            {
                Content = new StringContent(_expected.ToJson()),
                StatusCode = HttpStatusCode.OK
            };
            _failureResponse = new HttpResponseMessage {
                Content = new StringContent("error"),
                StatusCode = HttpStatusCode.InternalServerError
            };

            _firebaseClient = new FirebaseClient(_firebaseRequestManagerMock.Object);
        }
Пример #19
0
 public FirebaseRepo(FirebaseClient client, string path)
 {
     _childQuery = client.Child(path);
 }
Пример #20
0
 public SupermarketRegViewModel()
 {
     firebase             = new FirebaseClient(AppConstant.URLData);
     OnSupermarketCommand = new Command(SupermarketRegiestration);
     UserDataCollection   = new UserData();
 }
Пример #21
0
        public async Task SecondConnectionWithoutSlash()
        {
            // This integration test will write from _config but read from a second Firebase connection to
            // the same DB, but with a BasePath which does not contain the unnecessary trailing slash.
            IFirebaseConfig config2 = new FirebaseConfig
            {
                AuthSecret = FirebaseSecret,
                BasePath = BasePathWithoutSlash,
            };
            var client2 = new FirebaseClient(config2);

            await _client.PushAsync("todos/get/pushAsync", new Todo
            {
                name = "SecondConnectionWithoutSlash",
                priority = 3
            });

            Thread.Sleep(400);

            var response = await client2.GetAsync("todos/get/");
            Assert.NotNull(response);
            Assert.IsTrue(response.Body.Contains("name"));
            Assert.IsTrue(response.Body.Contains("SecondConnectionWithoutSlash"));
        }
Пример #22
0
 public Firebase()
 {
     fbClient = new FirebaseClient("https://objectivo-fe34c.firebaseio.com/");
 }
Пример #23
0
 public FbClient()
 {
     fb = Authenticate().Result;
 }
Пример #24
0
 public FoodItemService()
 {
     client = new FirebaseClient("https://estoreapp-7a3b9.firebaseio.com/");
 }
Пример #25
0
        private async void PopulateList()
        {
            progressBar.Visibility = ViewStates.Visible;
            string fileName_myQs         = "myqs_" + myAttributes.cfid.ToString() + "_" + myAttributes.typeid.ToString();
            string fileName_myCareerFair = myAttributes.cfid.ToString();

            var firebase = new FirebaseClient(FirebaseURL);

            var myQs = await firebase.Child("qs").Child(fileName_myQs).OnceAsync <StudentQ>();

            var myCareerFair = await firebase.Child("careerfairs").Child(fileName_myCareerFair).OnceAsync <Company>();

            if (myQs.Count == 0)
            {
                NoQsPresent fragment  = new NoQsPresent();
                Bundle      arguments = new Bundle();
                arguments.PutString("Sender", "CurrentQs");
                fragment.Arguments = arguments;

                Android.Support.V4.App.FragmentTransaction trans = FragmentManager.BeginTransaction();
                trans.Replace(Resource.Id.qs_root_frame, fragment);
                trans.Commit();
            }

            List <string> mItems     = new List <string>();
            List <int>    companyIds = new List <int>();
            List <string> mPositions = new List <string>();
            List <string> mWaitTimes = new List <string>();
            List <bool>   favs       = new List <bool>();
            int           position   = -1;

            foreach (var q in myQs)
            {
                position = position + 1;
                mItems.Add(q.Object.company);
                mPositions.Add(q.Object.position);

                foreach (var company in myCareerFair)
                {
                    if (company.Object.name == mItems[position])
                    {
                        long     partialWaitTime = Convert.ToInt64(company.Object.waittime);
                        long     totalWaitTime   = partialWaitTime * (Convert.ToInt32(mPositions[position]) - 1); // -1 because they are already in the line
                        TimeSpan ts       = TimeSpan.FromTicks(totalWaitTime);
                        string   waittime = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
                        mWaitTimes.Add(waittime);
                    }
                }
            }

            string fileName_favorites = "fav_" + myAttributes.cfid.ToString() + "_" + myAttributes.typeid.ToString();
            var    myFavs             = await firebase.Child("favorites").Child(fileName_favorites).OnceAsync <Favorite>();

            for (int i = 0; i <= mItems.Count - 1; i++)
            {
                foreach (var fav in myFavs)
                {
                    if (mItems[i] == fav.Object.name)
                    {
                        favs.Add(fav.Object.isFavorite);
                        companyIds.Add(Convert.ToInt32(fav.Object.companyid));
                    }
                }
            }

            QsListViewAdapter adapter = new QsListViewAdapter(mContainer.Context, mItems, "CurrentQs", favs, companyIds, mWaitTimes, mPositions);

            mListView.Adapter      = adapter;
            progressBar.Visibility = ViewStates.Invisible;
        }
Пример #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChildQuery"/> class.
 /// </summary>
 /// <param name="client"> The client. </param>
 /// <param name="pathFactory"> The path to the child node.  </param>
 public ChildQuery(FirebaseClient client, Func <string> pathFactory)
     : this(null, pathFactory, client)
 {
 }
Пример #27
0
        private async void button3_Click(object sender, EventArgs e)
        {
            string a;

            if (!String.IsNullOrEmpty(textBox1.Text))
            {
                DialogResult dialogResult = new DialogResult();
                dialogResult = MessageBox.Show(isim + " İsmini onaylıyor musun? ", "Onaylama", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dialogResult == DialogResult.Yes)
                {
                    try
                    {
                        Random           random   = new Random();
                        int              IDD1     = random.Next(1000000, 9999999);
                        FirebaseClient   client2  = new FirebaseClient(config);
                        FirebaseResponse response = await client2.GetAsync("Chat/Users/");

                        IlkGiris control2 = response.ResultAs <IlkGiris>();
                        a = control2.Kayitlar;
                        //   MessageBox.Show(a);
                        if (a.Contains(textBox1.Text.ToLower()))
                        {
                            MessageBox.Show("Isim kullaniliyor! ");
                        }
                        else
                        {
                            isim = textBox1.Text;
                            var userControl = new UserControl
                            {
                                Username = textBox1.Text,
                                Datetime = DateTime.Now.ToString(),
                                Friends  = "Bos",
                                ID       = IDD1.ToString()
                            };
                            IDD = IDD1.ToString();
                            var Kayit = new IlkGiris {
                                Kayitlar = a + " " + textBox1.Text.ToLower()
                            };
                            FirebaseClient client = new FirebaseClient(config);
                            SetResponse    set    = await client.SetAsync("Chat/" + textBox1.Text.ToLower() + "/", userControl);

                            UserControl control = set.ResultAs <UserControl>();
                            SetResponse set2    = await client.SetAsync("Chat/Users/", Kayit);

                            IlkGiris giris = set2.ResultAs <IlkGiris>();
                            MessageBox.Show("Kaydiniz Basari ile Olusturuldu! ");
                            this.Hide();
                        }
                    }
                    catch (Exception dd)
                    {
                        MessageBox.Show(dd.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("Kayıt işlemi iptal ediliyor.");
                    textBox1.Text = "";
                }
            }
            else
            {
                MessageBox.Show("Bir isim koymalısın! ");
            }
        }
Пример #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ParameterQuery"/> class.
 /// </summary>
 /// <param name="parent"> The parent of this query. </param>
 /// <param name="parameterFactory"> The parameter. </param>
 /// <param name="client"> The owning client. </param>
 protected ParameterQuery(FirebaseQuery parent, Func <string> parameterFactory, FirebaseClient client)
     : base(parent, client)
 {
     this.parameterFactory = parameterFactory;
     this.separator        = (this.Parent is ChildQuery) ? "?" : "&";
 }
Пример #29
0
 private string ConstructMembershipPath(string subPath = null)
 {
     return($"{OrleansMembershipPath}/{this.deploymentId}{(subPath == null ? string.Empty : "/" + FirebaseClient.ToCamelCase(subPath))}");
 }
Пример #30
0
        //private static bool ChooseAppoinment(int totalSimTime, Appointment appointment)
        //{

        //    return false;
        //}

        private static async Task InitializeFirebase()
        {
            //this will fill the appointmentList with Appointment objects, filled with the appointments from firebase
            //it will also subscribe our company/team to the database

            System.Diagnostics.Debug.WriteLine("ENTER InitializeFirebase");

            //******************** Initialization ***************************//
            client = new FirebaseClient("https://cpts323battle.firebaseio.com/");
            HttpClient            httpclient = new HttpClient();
            string                selectedkey = "", responseString;
            FormUrlEncodedContent content;
            HttpResponseMessage   response;

            //******************** Get initial list of Prospect ***********************//
            var Appointments = await client
                               .Child("appointments")//Prospect list
                               .OnceAsync <Appointment>();

            foreach (var appointment in Appointments)
            {
                System.Diagnostics.Debug.WriteLine($"OA1:{appointment.Key}:->{appointment.Object.acepted}");
                //create a list of appointments
                //smart selection to improve your profit
                selectedkey = appointment.Key;

                //create Appointment object, set all of its memebers, and add it to the appointmentList
                Appointment ap = new Appointment()
                {
                    prospect    = appointment.Object.prospect,
                    destination = appointment.Object.destination,
                    pointList   = appointment.Object.pointList,
                    InitialTime = appointment.Object.InitialTime,
                    acepted     = appointment.Object.acepted,
                    vaccinated  = appointment.Object.vaccinated,
                    active      = appointment.Object.active,
                    key         = appointment.Key,
                };

                appointmentList.Add(ap);
            }

            //make an observer for the appointments in his firebase, when they are changed this should automatically detect it
            SubscribeToAppointmentListChanges();

            //next step is to subscribe our company/team name to his firebase
            //this will add our company to the database everytime it runs, so keep it commented out so you dont spam his firebase
            var company      = new Company
            {
                companyName = "Blue Team",
                status      = "active"
            };
            var dictionary   = new Dictionary <string, string>
            {
                { "companyName", company.companyName },
                { "status", company.status }
            };

            content  = new FormUrlEncodedContent(dictionary);
            response = await httpclient.PostAsync("https://us-central1-cpts323battle.cloudfunctions.net/reportCompany", content);

            responseString = await response.Content.ReadAsStringAsync();

            Response data    = Newtonsoft.Json.JsonConvert.DeserializeObject <Response>(responseString);

            System.Diagnostics.Debug.WriteLine(data.message);
            System.Diagnostics.Debug.WriteLine(data.companyId);
            companyId = data.companyId;

            //next step is to create our vans and add them to our firebase
            //first create the local Van objects and add them to the "vans" list
            Random rand      = new Random();

            for (int i = 0; i < numVans; i++)
            {
                Van van = new Van
                {
                    Position = refillLocation,
                    Vid      = "Van " + i,
                    CarPlate = rand.Next(100000, 999999).ToString(), //use a random number for the plate
                    Vials    = 6                                     //whats the max vials a van can hold at a time?
                };
                vans.Add(van);
            }
            vans[0].routeColor = Color.Blue;
            vans[1].routeColor = Color.ForestGreen;
            vans[2].routeColor = Color.Pink;
            vans[3].routeColor = Color.Black;
            vans[4].routeColor = Color.Yellow;
            vans[5].routeColor = Color.Red;

            //this part adds the newly created vans to our firebase
            client2 = new FirebaseClient("https://proj-109d4-default-rtdb.firebaseio.com/");
            HttpClient httpclient2 = new HttpClient();

            for (int i = 0; i < numVans; i++)
            {
                var child2 = client2.Child("Vans");
                var fbVan  = await child2.PostAsync(vans[i]);

                vans[i].key = fbVan.Key;
            }
        }
Пример #31
0
 public FireBaseHelper()
 {
     firebase = new FirebaseClient("https://stunning-grin-700.firebaseio.com/");
 }
        public EditDetailsActivity()
        {
            InitializeComponent();

            firebase = new FirebaseClient("https://mia-database-45d86.firebaseio.com");
        }
Пример #33
0
        private async Task <int> loginAsync()
        {
            //firebase
            var auth           = firebaseConfigurations.SecretKey;
            var firebaseClient = new FirebaseClient(
                "<URL>",
                new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth)
            });
            var firebase = new FirebaseClient(firebaseConfigurations.BasePath);


            try
            {
                //username query
                var accountQuery = await firebase
                                   .Child("Accounts")
                                   .OrderByKey()
                                   .StartAt(tempAccountHolder.id)
                                   .LimitToFirst(1)
                                   .OnceAsync <Account>();


                //no account exists
                if (accountQuery.Count == 0)
                {
                    //email check
                    try
                    {
                        //email query
                        var emailQuery = await firebase
                                         .Child("Accounts")
                                         .OrderBy("email")
                                         .StartAt(tempAccountHolder.id)
                                         .LimitToFirst(1)
                                         .OnceAsync <Account>();


                        //if there are no emails
                        if (emailQuery.Count == 0)
                        {
                            return(0);
                        }

                        var a = tempAccountHolder;
                        foreach (var account in emailQuery)
                        {
                            if (account.Object.password == tempAccountHolder.password && account.Object.email == tempAccountHolder.id)
                            {
                                return(1);
                            }
                            else
                            {
                                return(0);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                        return(-1);
                    }
                }

                //there is a username
                foreach (var account in accountQuery)
                {
                    /*
                     *   return of 1 means successfull
                     *   return of 0 means unseccessfull sign in
                     *   return of -1 means got exception
                     */
                    //get account

                    if (account.Object.password == tempAccountHolder.password && account.Object.id == tempAccountHolder.id)
                    {
                        return(1);
                    }
                    else
                    {
                        return(0);
                    }
                }
            }
            catch (Exception)
            {
                return(-1);
            }

            return(-1);
        }
Пример #34
0
        async Task addMatch()
        {
            try {
                long mTime;
                if (GlobalVariables.regionalPointer == "2017calb")
                {
                    mTime = laFinals + matchTime;
                }
                else if (GlobalVariables.regionalPointer == "2017nvlv")
                {
                    mTime = lvFinals + matchTime;
                }
                else if (GlobalVariables.regionalPointer == "2017cmptx")
                {
                    mTime = txFinals + matchTime;
                }
                else
                {
                    mTime = txFinals + matchTime;
                }

                Console.WriteLine("Match Time: " + mTime);

                var db    = new FirebaseClient(GlobalVariables.firebaseURL);
                var match = new TableauMatchShedule();

                int i = 1;

                foreach (var robot in red)
                {
                    var matchID = robot.Text + "-" + matchNoEntry.Text;

                    await db.Child(GlobalVariables.regionalPointer)
                    .Child("matchList")
                    .Child(matchID)
                    .PutAsync(new TableauMatchShedule()
                    {
                        matchID     = matchID,
                        matchNumber = matchNoEntry.Text,
                        alliance    = "Red",
                        alliancePos = i++,
                        teamNumber  = Convert.ToInt32(robot.Text),
                        matchTime   = mTime
                    });
                }

                i = 1;
                foreach (var robot in blue)
                {
                    var matchID = robot.Text + "-" + matchNoEntry.Text;

                    await db.Child(GlobalVariables.regionalPointer)
                    .Child("matchList")
                    .Child(matchID)
                    .PutAsync(new TableauMatchShedule()
                    {
                        matchID     = matchID,
                        matchNumber = matchNoEntry.Text,
                        alliance    = "Blue",
                        alliancePos = i++,
                        teamNumber  = Convert.ToInt32(robot.Text),
                        matchTime   = mTime
                    });
                }

                // Depreciated

                /*
                 * match.Red = new int[3];
                 * match.Blue = new int[3];
                 * for (int i = 0; i < 3; i++) {
                 *      match.Red[i] = Convert.ToInt32(red[i].Text);
                 *      match.Blue[i] = Convert.ToInt32(blue[i].Text);
                 * }
                 * match.matchNumber = matchNoEntry.Text;
                 * if (GlobalVariables.regionalPointer == "2017calb")
                 *      match.matchTime = laFinals + matchTime;
                 * else if (GlobalVariables.regionalPointer == "2017nvlv")
                 *      match.matchTime = lvFinals + matchTime;
                 * else if (GlobalVariables.regionalPointer == "2017cmptx")
                 *      match.matchTime = txFinals + matchTime;
                 * else
                 *      match.matchTime = txFinals + matchTime;
                 *
                 * Console.WriteLine("Match Time: " + match.matchTime);
                 *
                 * var db = new FirebaseClient(GlobalVariables.firebaseURL);
                 *
                 * var upload = db
                 *                      .Child(GlobalVariables.regionalPointer)
                 *                      .Child("matchList")
                 *                      .Child(matchNoEntry.Text)
                 *                      .PutAsync(match);
                 */

                await DisplayAlert("Success", "Match Successfully Added", "OK").ContinueWith((a) => {
                    Navigation.PopPopupAsync();
                });
            } catch (Exception ex) {
                Console.WriteLine("addMatch Error: " + ex.Message);
            }
        }
Пример #35
0
 public FirebaseService()
 {
     firebase = new FirebaseClient("https://xamarinfirebase-a0848.firebaseio.com/");
 }
Пример #36
0
 public FirebaseHelper()
 {
     firebaseClient = new FirebaseClient(DBRef);
 }
 public FoodItemService()
 {
     client = new FirebaseClient("https://foodorderingapp-7b2d1-default-rtdb.firebaseio.com/");
 }
Пример #38
0
        private async void FormLihatHasil_Load(object sender, EventArgs e)
        {
            var auth     = "cQOwBdt0Ep4K2IyU6wwzkW8wAMOTXz78Qqo1FmRG";
            var firebase = new FirebaseClient(
                "https://proyek-pemira-hme.firebaseio.com/",
                new FirebaseOptions
            {
                AuthTokenAsyncFactory = () => Task.FromResult(auth)
            });

            var pemilih = await firebase
                          .Child("DatabaseHME")
                          .OrderByKey()
                          .LimitToFirst(1000)
                          .OnceAsync <Data>();

            int pilihan1cakahim   = 0;
            int pilihan2cakahim   = 0;
            int pilihan3cakahim   = 0;
            int pilihan1casenator = 0;
            int pilihan2casenator = 0;
            int pilihan3casenator = 0;

            foreach (var massa in pemilih)
            {
                int value  = massa.Object.Cakahim;
                int value2 = massa.Object.Casenator;

                if (value == 0)
                {
                    pilihan3cakahim += 1;
                }
                else if (value == 1)
                {
                    pilihan1cakahim += 1;
                }
                else if (value == 2)
                {
                    pilihan2cakahim += 1;
                }

                if (value2 == 0)
                {
                    pilihan3casenator += 1;
                }
                else if (value2 == 1)
                {
                    pilihan1casenator += 1;
                }
                else if (value2 == 2)
                {
                    pilihan2casenator += 1;
                }
            }

            pemilihNo1.Text           = "PILIHAN 1: " + pilihan1cakahim.ToString();
            pemilihNo2.Text           = "PILIHAN 2: " + pilihan2cakahim.ToString();
            tidakDatangCakahim.Text   = "TIDAK DATANG: " + pilihan3cakahim.ToString();
            pemilihYa.Text            = "PEMILIH YA: " + pilihan1casenator.ToString();
            pemilihTidak.Text         = "PEMILIH TIDAK: " + pilihan2casenator.ToString();
            tidakDatangCasenator.Text = "TIDAK DATANG: " + pilihan3casenator.ToString();
            Bunifupie(pilihan1cakahim, pilihan2cakahim, pilihan3cakahim, pilihan1casenator, pilihan2casenator, pilihan3casenator);
        }
Пример #39
0
 public OrderService()
 {
     client = new FirebaseClient("https://storemanagement-82a44-default-rtdb.firebaseio.com/");
 }
Пример #40
0
 public DBFirebase()
 {
     client = new FirebaseClient("https://approximatefirebase.firebaseio.com/");
 }
Пример #41
0
 public FirebaseHelper()
 {
     firebase = new FirebaseClient("https://project-3cb9f-default-rtdb.firebaseio.com/");
 }
        /** This function is called before the page is displayed.
         */
        protected override async void OnAppearing()
        {
            try
            {
                var location = await Geolocation.GetLastKnownLocationAsync();

                if (location == null)
                {
                    location = await Geolocation.GetLocationAsync(new GeolocationRequest
                    {
                        DesiredAccuracy = GeolocationAccuracy.Medium,
                        Timeout         = TimeSpan.FromSeconds(30)
                    });
                }
                else
                {
                    Pin currentLocation = new Pin()
                    {
                        Type     = PinType.SavedPin,
                        Label    = "Me",
                        Address  = "Here",
                        Position = new Position(location.Latitude, location.Longitude),
                        Tag      = "id_Me",
                    };
                    // Add the pin and load the map at this location
                    map.Pins.Add(currentLocation);
                    map.MoveToRegion(MapSpan.FromCenterAndRadius(currentLocation.Position, Distance.FromMeters(5000)));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Something is wrong: {e.Message}");
            }


            FirebaseClient firebaseClient = new FirebaseClient("https://application-green-quake-default-rtdb.firebaseio.com/");

            //Load the pin data into a list
            var list = (await firebaseClient
                        .Child("Stations")
                        .OnceAsync <Station>()).Select(item => new Station
            {
                description = item.Object.description,
                label       = item.Object.label,
                latitude    = item.Object.latitude,
                longitude   = item.Object.longitude,
            }).ToList();

            // For each entry in the data create and place a pin.
            foreach (var obj in list)
            {
                Pin stationLocations = new Pin()
                {
                    Type     = PinType.SavedPin,
                    Label    = obj.label,
                    Address  = obj.description,
                    Position = new Position(obj.latitude, obj.longitude),
                };
                map.Pins.Add(stationLocations);
            }
        }
 public FireBaseService()
 {
     clients                  = new List <Client>();
     firebaseClient           = new FirebaseClient(databaseURL);
     firebaseObjectClientList = new List <FirebaseObject <Client> >();
 }
Пример #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthQuery"/> class.
 /// </summary>
 /// <param name="parent"> The parent.  </param>
 /// <param name="tokenFactory"> The authentication token factory. </param>
 /// <param name="client"> The owner. </param>
 public AuthQuery(FirebaseQuery parent, Func <string> tokenFactory, FirebaseClient client) : base(parent, () => "auth", client)
 {
     this.tokenFactory = tokenFactory;
 }
Пример #45
0
        public async Task<ActionResult> Index()
        {
                //initialize dropbox auth options
            var options = new Options
            {
                ClientId = "rnizd2wt4vhv4cn",
                ClientSecret = "k8exfknbce45n5g",
                RedirectUri = "https://fedup.azurewebsites.net/Incident"
                //RedirectUri = "http://localhost:49668/Incident"
            };

                // Initialize a new Client (without an AccessToken)
            var dropboxClient = new Client(options);

                // Get the OAuth Request Url
            var authRequestUrl = await dropboxClient.Core.OAuth2.AuthorizeAsync("code");

            if (Request.QueryString["code"] == null)
            {
                    // Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
                Response.Redirect(authRequestUrl.ToString());
            }
                //get authcode from querstring param
            var authCode = Request.QueryString["code"];

            // Exchange the Authorization Code with Access/Refresh tokens
            var token = await dropboxClient.Core.OAuth2.TokenAsync(authCode);

            // Get account info
            var accountInfo = await dropboxClient.Core.Accounts.AccountInfoAsync();
            Console.WriteLine("Uid: " + accountInfo.uid);
            Console.WriteLine("Display_name: " + accountInfo.display_name);
            Console.WriteLine("Email: " + accountInfo.email);

            // Get root folder without content
            var rootFolder = await dropboxClient.Core.Metadata.MetadataAsync("/", list: false);
            Console.WriteLine("Root Folder: {0} (Id: {1})", rootFolder.Name, rootFolder.path);

            // Get root folder with content
            rootFolder = await dropboxClient.Core.Metadata.MetadataAsync("/", list: true);
            foreach (var folder in rootFolder.contents)
            {
                Console.WriteLine(" -> {0}: {1} (Id: {2})",
                    folder.is_dir ? "Folder" : "File", folder.Name, folder.path);
            }

            // Initialize a new Client (with an AccessToken)
            var client2 = new Client(options);

            // Find a file in the root folder
            var file = rootFolder.contents.FirstOrDefault(x => x.is_dir == false);
            var files = rootFolder.contents.ToList();

            // Download a file
            
            foreach (var item in files)
            {
                var tempFile = Path.GetTempFileName();
                if (item.path.Substring(item.path.Length - 4) == ".mp3")
                {
                    using (var fileStream = System.IO.File.OpenWrite(tempFile))
                    {

                        await client2.Core.Metadata.FilesAsync(item.path, fileStream);

                        fileStream.Flush();
                        fileStream.Close();
                    }

                    int length = item.path.Length;
                    string destination = item.path.Substring(0, length - 4) + ".mp3";
                    destination = AppDomain.CurrentDomain.BaseDirectory + destination.Substring(1);
                    System.IO.File.Copy(tempFile, destination, true);
                }
            }


            List<incident> Incidents = new List<incident>();

            IFirebaseConfig config = new FirebaseConfig
            {
                AuthSecret = "0dwRwB8V2QmJTM9NbKtWfqlys91LwZguvE67oS1f",
                BasePath = "https://fedup.firebaseio.com/"
            };

                //initialize new firebase client
            IFirebaseClient client = new FirebaseClient(config);

            bool hasNext = true;
            int counter = 1;
            do
            {
                try
                {
                    //pull current row
                    FirebaseResponse response = await client.GetAsync(counter.ToString());

                    //parse our json object
                    incident jsonObject = JsonConvert.DeserializeObject<incident>(response.Body);

                    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
                    dtDateTime = dtDateTime.AddSeconds(jsonObject.timestamp).ToLocalTime();

                    jsonObject.newTimeStamp = dtDateTime;

                    Incidents.Add(jsonObject);
                }
                catch
                {
                    hasNext = false;
                    break;
                }
                counter++;
            }
            while (hasNext);

            ViewBag.Incidents = Incidents;

            return View();
        }
Пример #46
0
        public async Task Execute(IJobExecutionContext context)
        {
            Article[] articles = { };
            var       client   = new HttpClient();
            var       request  = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri("https://covid-19-news.p.rapidapi.com/v1/covid?q=covid&lang=en&media=True"),
                Headers    =
                {
                    { "x-rapidapi-key",  "c947943dd5mshd3da70c50ce7bb9p175bd6jsndb5705073769" },
                    { "x-rapidapi-host", "covid-19-news.p.rapidapi.com"                       },
                },
            };

            using (var response = await client.SendAsync(request))
            {
                response.EnsureSuccessStatusCode();
                var body = await response.Content.ReadAsStringAsync();

                Rootobject rootdata = JsonConvert.DeserializeObject <Rootobject>(body);
                articles = rootdata.articles;
            }

            //setting content in email
            var content = "";
            var num     = 1;

            foreach (var i in articles)
            {
                content += "<h1>" + num + ". " + i.title + "</h1><br>";
                content += "<a href=" + i.link + "><img src=" + i.media + " /></a>";
                content += i.summary;
                num     += 1;
            }

            //retrieving email from firebase
            var firebaseClient = new FirebaseClient("https://spaceandgo-938a9.firebaseio.com/"); //USE FOR LINKING TO DATABASE

            //Retrieve data from Firebase
            var dbLogins = await firebaseClient
                           .Child("Email")
                           .OnceAsync <Form>();

            var emailList = new List <string>();

            foreach (var login in dbLogins)
            {
                emailList.Add((login.Object.FromEmail));
            }

            //sending email
            var message = new MailMessage();

            foreach (string i in emailList)
            {
                message.To.Add(new MailAddress(i));
            }

            message.From       = new MailAddress("*****@*****.**"); // replace with valid value
            message.Subject    = "Space & Go";
            message.Body       = content;
            message.IsBodyHtml = true;

            using (var smtp = new SmtpClient())
            {
                var credential = new NetworkCredential
                {
                    UserName = "******", // replace with valid value
                    Password = "******"            // replace with valid value
                };

                smtp.Credentials = credential;
                smtp.Host        = "smtp.gmail.com";
                smtp.Port        = 587;
                smtp.EnableSsl   = true;
                await smtp.SendMailAsync(message);
            }
        }
Пример #47
0
        private async void button1_Click(object sender, EventArgs e)
        {
            IFirebaseClient client = new FirebaseClient(config);
            // get new response object
            FirebaseResponse response = client.Get("");
            JObject          o        = JObject.Parse(response.Body);

            // Clear existing datatable
            DPath.Clear();
            DValue.Clear();
            DName.Clear();
            DResponsibility.Clear();
            dt.Clear();
            AddValtoList(o);
            //var result = !(txtsearchbox.Text.Contains(','));//false แปลว่าพบ , แต่ true แปลว่าไม่มีต้องแทรกให้
            string searchval;

            searchval = txtsearchbox.Text + ',';
            try
            {
                List <string> slist = searchval.Split(',').ToList();
                //อันนี้ทำงานได้

                /*List<string> filterlist = (from d in DPath
                 *                         where d.Contains(slist[0].Trim().ToString())
                 *                         select d).ToList();
                 */
                // จับคู่มันด้วย Zip()

                /*
                 * List<Tuple<string, string>> filterlisttuple = DPath
                 *      .Zip(DValue, (k, v) => new { k, v })
                 *      .Where(x => x.k.Contains(slist[0].Trim().ToString()) && x.k.Contains(slist[1].Trim().ToString()))
                 *      .Select(x => Tuple.Create(x.k, x.v))
                 *      .ToList();
                 */
                //linq แบบใช้ class
                List <Filter> filter = DPath
                                       .Zip(DValue, (k, v) => new { k, v })
                                       .Where(x => x.k.Contains(slist[0].Trim().ToString()) && x.k.Contains(slist[1].Trim().ToString()))
                                       .Select(x => new Filter {
                    Path = x.k, Value = x.v
                })
                                       .ToList();

                for (int i = 0; i < filter.Count(); i++)
                {
                    // loop data to object
                    dr               = dt.NewRow();
                    dr["#"]          = i + 1;
                    dr["Activities"] = filter[i].Path.Replace("Activities.", "").Replace("Task.", "").Replace("_", ".").ToString();
                    if (dr["Activities"].ToString().Contains("กลั่นกรอง"))
                    {
                        dr["Responsibility"] = "ผู้กลั่นกรอง";
                    }
                    else
                    {
                        dr["Responsibility"] = "ผู้อนุมัติ";
                    }
                    dr["Action By"] = filter[i].Value.ToString();

                    dt.Rows.Add(dr);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.WriteLine("error here");
            }
            finally
            {                }
            //MessageBox.Show(txtsearchbox.Text);
            dataGridView1.DataSource = dt;
        }
Пример #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChildQuery"/> class.
 /// </summary>
 /// <param name="parent"> The parent.  </param>
 /// <param name="pathFactory"> The path to the child node.  </param>
 /// <param name="client"> The owner. </param>
 public ChildQuery(FirebaseQuery parent, Func <string> pathFactory, FirebaseClient client)
     : base(parent, client)
 {
     this.pathFactory = pathFactory;
 }
 /*Willie Start*/
 public DatabaseSystem()
 {
     _firebaseClient = new FirebaseClient("https://activitygroup-74f7f.firebaseio.com/");
 }
Пример #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FirebaseQuery"/> class.
 /// </summary>
 /// <param name="parent"> The parent of this query. </param>
 /// <param name="client"> The owning client. </param>
 protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client)
 {
     this.Client = client;
     this.Parent = parent;
 }
        public HttpResponseMessage Get(string AuthSecret, string BasePath, string command)
        {
            try
            {
                IFirebaseConfig config = new FirebaseConfig
                {
                    AuthSecret = AuthSecret,
                    BasePath = BasePath
                };

                IFirebaseClient client = new FirebaseClient(config);

                FirebaseResponse response;

                if (String.IsNullOrWhiteSpace(command))
                    response = client.Get("/");
                else
                    response = client.Get("/"+command.ToString());

                return Request.CreateResponse(HttpStatusCode.OK, response); ;
            }
            catch (KeyNotFoundException)
            {
                string mensagem = string.Format("Não foi possível criptografar a entrada: ", command);
                HttpError error = new HttpError(mensagem);
                return Request.CreateResponse(HttpStatusCode.NotFound, error);
            }
        }