示例#1
0
 public CollectionReferenceWrapper(CollectionReference collectionReference)
 {
     _collectionReference = collectionReference;
 }
示例#2
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            //Access permission
            string path = AppDomain.CurrentDomain.BaseDirectory + @"token-file.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);

            //Create instent of collection
            FirestoreDb db = await FirestoreDb.CreateAsync("eteva-firestore-app");

            CollectionReference masterCollection = db.Collection("ProductMaster");

            //var productCount = masterCollection.GetSnapshotAsync().Result.Count();
            //Console.WriteLine($"Total recors in collection is {productCount}");

            var        filePath   = "E://SachinPawar//Second-Thought//SecondThought_POC//DataMigration_ProductMaster//Data//";
            var        jsonFiles  = Directory.EnumerateFiles(filePath);
            WriteBatch batch      = db.StartBatch();
            int        count      = 0;
            int        batchCount = 0;

            //var original = new List<string>();
            //var duplicate = new List<string>();
            Console.WriteLine("Data migration started in batches of 500 record each...");
            foreach (var jsonFile in jsonFiles)
            {
                try
                {
                    Console.WriteLine($"File : {jsonFile.Split("//")[jsonFile.Split("//").Length - 1]} ----------->");
                    var dataString    = File.ReadAllText(jsonFile);
                    var productMaster = JsonConvert.DeserializeObject <Product>(dataString);

                    foreach (var master in productMaster.Items)
                    {
                        #region To find duplicate records in a file

                        //if (original.Contains(master.TradeItem.Gtin))
                        //    duplicate.Add(master.TradeItem.Gtin);
                        //else
                        //    original.Add(master.TradeItem.Gtin);

                        #endregion

                        count += 1;
                        batch.Set(masterCollection.Document(master.TradeItem.Gtin), master);
                        if (count == 500)
                        {
                            batchCount++;
                            var result = await batch.CommitAsync();

                            Console.WriteLine($"Batch {batchCount} of {count} records are completed!");
                            batch = db.StartBatch();
                            count = 0;
                        }
                    }
                    if (count > 0)
                    {
                        var result = await batch.CommitAsync();

                        Console.WriteLine($"Batch {batchCount} of {count} records are completed!");
                        batch = db.StartBatch();
                    }
                    batchCount = 0;
                    //Console.WriteLine("Original record:" + original.Count());
                    //Console.WriteLine("Duplicate record:" + duplicate.Count());
                    //duplicate.ForEach(x => Console.WriteLine(x));
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Error({e.Message}) occure in batch no {batchCount} of file {jsonFile}");
                    count = 0;
                    continue;
                }
            }
            Console.WriteLine($"Data migration completed!");

            //var productCount = masterCollection.GetSnapshotAsync().Result.Count();
            //Console.WriteLine($"Total recors in collection is {productCount}");

            Console.ReadKey();
        }
 public async Task NodeDoubleClick(CollectionReference value)
 {
     await _applicationInteraction.ActivateDefaultCollectionView(value);
 }
 void InitializeFirestoreReferences()
 {
     userDocument      = AppDelegate.Database.GetDocument($"notes_app/{AppDelegate.UserUid}");
     foldersCollection = userDocument.GetCollection("folders");
 }
 public CollectionReferenceWrapper(CollectionReference collectionRef)
 {
     this.collectionRef = collectionRef;
 }
示例#6
0
        static void Main(string[] args)
        {
            FirestoreDb         db      = FirestoreDb.Create("cicero-box");
            CollectionReference queue   = db.Collection("queue");
            CollectionReference results = db.Collection("results");

            ComputeServer.AuthToken = "*****@*****.**";

            while (true)
            {
                Console.WriteLine($"Loop at {DateTime.Now.ToString()}.");

                var docs = queue.GetSnapshotAsync();
                docs.Wait();

                var numDocs = docs.Result.Count;

                Console.WriteLine($"{numDocs.ToString()} documents in queue.");

                if (numDocs == 0)
                {
                    Thread.Sleep(3000);
                    continue;

                    /*
                     * var circleA = new Circle(new Point3d(0, 1, 0), 1.5).ToNurbsCurve();
                     * var circleB = new Circle(new Point3d(0, -1, 0), 1.75).ToNurbsCurve();
                     *
                     * var joinedCircles = Rhino.Compute.CurveCompute.CreateBooleanUnion(new Curve[] {circleA, circleB});
                     * Console.WriteLine(joinedCircles[0].GetLength().ToString());
                     */
                }
                ;

                var id   = docs.Result[0].Id;
                var data = docs.Result[0].GetValue <string>("payload");

                string[] dataToWrite = { id, data };

                Console.WriteLine(data);

                var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\cicero\\";
                System.IO.File.WriteAllLines(path + "current.dat", dataToWrite);

                var rhinoIsDone = false;
                var loopCount   = 0;

                var res = queue.Document(id).DeleteAsync();
                res.Wait();

                while (!rhinoIsDone)
                {
                    if (System.IO.File.Exists(path + "svg\\" + id + ".svg"))
                    {
                        rhinoIsDone = true;
                    }

                    if (loopCount > 30)
                    {
                        break;
                    }

                    Console.WriteLine("Rhino is computing...");
                    loopCount++;
                    Thread.Sleep(1000);
                }

                //Dispatch svg to database.
                var svgDoc  = results.Document(id);
                var svgData = loopCount > 30 ? "The system failed to generate a solution, please try again." : System.IO.File.ReadAllText(path + "svg\\" + id + ".svg");

                Dictionary <string, object> docData = new Dictionary <string, object>
                {
                    { "svg", svgData }
                };

                var x = svgDoc.SetAsync(docData);
                x.Wait();

                Console.WriteLine($"Dispatched results for {id} to firestore.");

                Thread.Sleep(3000);
            }
        }
示例#7
0
 public FirestoreFeedStore(string projectId)
 {
     _firestore = FirestoreDb.Create(projectId);
     _feeds     = _firestore.Collection("feeds");
 }
        public async Task <ActionResult> Create(ClinicSettings settings)
        {
            string ClinicMobileNumber = GlobalSessionVariables.ClinicMobileNumber;

            try
            {
                List <SelectListItem> whofirst = new List <SelectListItem>()
                {
                    new SelectListItem {
                        Text = "Chemist", Value = "Chemist"
                    },
                    new SelectListItem {
                        Text = "Cashier", Value = "Cashier"
                    },
                };
                ViewBag.WHOFIRSTS = whofirst;

                if (ModelState.IsValid)
                {
                    string Path = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json";
                    Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
                    FirestoreDb db = FirestoreDb.Create("greenpaperdev");

                    Query         QrefSettings = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("settings");
                    QuerySnapshot snapSettings = await QrefSettings.GetSnapshotAsync();

                    if (snapSettings.Count == 0)
                    {
                        CollectionReference         col1  = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("settings");
                        Dictionary <string, object> data1 = new Dictionary <string, object>
                        {
                            { "bill_sms", settings.bill_sms },
                            { "reminder_sms", settings.reminder_sms },
                            { "fee1", settings.fee1 },
                            { "fee2", settings.fee2 },
                            { "fee3", settings.fee3 },
                            { "inventoryon", settings.inventoryon },
                            { "days1", settings.days1 },
                            { "days2", settings.days2 },
                            { "days3", settings.days3 },
                            { "whofirst", settings.whofirst },
                            { "consultationfee", settings.consultationfee }
                        };

                        await col1.Document().SetAsync(data1);
                    }
                    else
                    {
                        ViewBag.Message = "Settings already exists for Clinic.";
                        return(View(settings));
                    }

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View(settings));
                }
            }
            catch
            {
                return(View(settings));
            }
        }
示例#9
0
 private static CollectionReferenceDTO Convert(CollectionReference doc) =>
 new CollectionReferenceDTO
 {
     Id   = doc.Id,
     Path = doc.Path
 };
示例#10
0
        public async Task AddResponseMessageAsync(CollectionReference messages, string msg)
        {
            var x = await messages.ListDocumentsAsync().ToListAsync();

            await messages.Document((x.Count + 1).ToString()).UpdateAsync("content", msg);
        }
 public FirestoreBookStore(string projectId)
 {
     _firestore = FirestoreDb.Create(projectId);
     _books     = _firestore.Collection("Books");
 }
示例#12
0
        private static async Task ListenForChanges(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_listen_for_changes]
            CollectionReference citiesRef = db.Collection("cities");
            Query query = db.Collection("cities").WhereEqualTo("State", "CA");

            FirestoreChangeListener listener = query.Listen(snapshot =>
            {
                foreach (DocumentChange change in snapshot.Changes)
                {
                    if (change.ChangeType.ToString() == "Added")
                    {
                        Console.WriteLine("New city: {0}", change.Document.Id);
                    }
                    else if (change.ChangeType.ToString() == "Modified")
                    {
                        Console.WriteLine("Modified city: {0}", change.Document.Id);
                    }
                    else if (change.ChangeType.ToString() == "Removed")
                    {
                        Console.WriteLine("Removed city: {0}", change.Document.Id);
                    }
                }
            });

            // [END fs_listen_for_changes]

            // Create a new document at cities/MTV to demonstrate realtime listener
            Console.WriteLine("Creating document");
            DocumentReference           docRef     = db.Collection("cities").Document("MTV");
            Dictionary <string, object> cityObject = new Dictionary <string, object>
            {
                { "Name", "Mountain View" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 80000 }
            };
            await docRef.CreateAsync(cityObject);

            await Task.Delay(1000);

            // Modify the cities/MTV document to demonstrate detection of the 'Modified change
            Console.WriteLine("Modifying document");
            Dictionary <string, object> city = new Dictionary <string, object>
            {
                { "Name", "Mountain View" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 90000 }
            };
            await docRef.SetAsync(city);

            await Task.Delay(1000);

            // Modify the cities/MTV document to demonstrate detection of the 'Modified change
            Console.WriteLine("Deleting document");
            await docRef.DeleteAsync();

            await Task.Delay(1000);

            // Stop the listener when you no longer want to receive updates.
            Console.WriteLine("Stopping the listener");
            await listener.StopAsync();
        }
示例#13
0
 public CommerceService(FirestoreClient firestoreClient)
 {
     FirestoreClient = firestoreClient;
     ShopsCollection = firestoreClient.DataBase.Collection("Commerce");
 }
示例#14
0
        private static async Task QueryCreateExamples(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_query_create_examples]
            CollectionReference citiesRef = db.Collection("cities");
            await citiesRef.Document("SF").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "San Francisco" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 860000 },
                { "Regions", new ArrayList {
                      "west_coast", "norcal"
                  } }
            });

            await citiesRef.Document("LA").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Los Angeles" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 3900000 },
                { "Regions", new ArrayList {
                      "west_coast", "socal"
                  } }
            });

            await citiesRef.Document("DC").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Washington D.C." },
                { "State", null },
                { "Country", "USA" },
                { "Capital", true },
                { "Population", 680000 },
                { "Regions", new ArrayList {
                      "east_coast"
                  } }
            });

            await citiesRef.Document("TOK").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Tokyo" },
                { "State", null },
                { "Country", "Japan" },
                { "Capital", true },
                { "Population", 9000000 },
                { "Regions", new ArrayList {
                      "kanto", "honshu"
                  } }
            });

            await citiesRef.Document("BJ").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Beijing" },
                { "State", null },
                { "Country", "China" },
                { "Capital", true },
                { "Population", 21500000 },
                { "Regions", new ArrayList {
                      "jingjinji", "hebei"
                  } }
            });

            Console.WriteLine("Added example cities data to the cities collection.");
            // [END fs_query_create_examples]
        }
示例#15
0
        public void DropCollection()
        {
            _databaseInteractions.DropCollection(SelectedCollection);

            SelectedCollection = null;
        }
示例#16
0
 public static void CreateOrder()
 {
     FirebaseFirestore   db    = FirebaseFirestore.GetInstance(App);
     CollectionReference users = db.Collection("Users");
 }
示例#17
0
        private async Task InitializeAsync(ulong id, CollectionReference playerCollection)
        {
            PlayerCollection = playerCollection;
            PlayerDoc        = PlayerCollection.Document(id.ToString());

            var playerDocSnap = await PlayerDoc.GetSnapshotAsync();

            if (!playerDocSnap.Exists)
            {
                await PlayerDoc.CreateAsync(new Dictionary <string, object>()
                {
                    { "boost", 0 },
                    { "demo-count", 0 },
                    { "death-count", 0 },
                    { "demo-rate", (DemoData.MinDemoChance + DemoData.MaxDemoChance) / 2 },
                    { "avoid-rate", (DemoData.MinAvoidChance + DemoData.MaxAvoidChance) / 2 },
                    { "avoid-count", 0 },
                    { "miss-count", 0 }
                });

                playerDocSnap = await PlayerDoc.GetSnapshotAsync();
            }

            if (!playerDocSnap.ContainsField("avoid-count"))
            {
                await PlayerDoc.UpdateAsync("avoid-count", 0);

                await PlayerDoc.UpdateAsync("miss-count", 0);
            }

            if (!playerDocSnap.TryGetValue("avoid-count", out int avoidCount))
            {
                avoidCount = 0;
            }

            if (!playerDocSnap.TryGetValue("miss-count", out int missCount))
            {
                missCount = 0;
            }

            if (!playerDocSnap.TryGetValue("boost-used", out int boostUsed))
            {
                boostUsed = 0;
            }

            Data = new DemoData(
                playerDocSnap.GetValue <int>("boost"),
                playerDocSnap.GetValue <int>("demo-count"),
                playerDocSnap.GetValue <int>("death-count"),
                playerDocSnap.GetValue <double>("demo-rate"),
                playerDocSnap.GetValue <double>("avoid-rate"),
                avoidCount,
                missCount);

            RecentMessages = new List <DbMessage>();

            var recentMsgSnap = await PlayerDoc.Collection("recent-messages").GetSnapshotAsync();

            if (recentMsgSnap.Count > 0)
            {
                foreach (var message in recentMsgSnap)
                {
                    //content, createTime
                    if (!message.TryGetValue("content", out string content))
                    {
                        content = "";
                    }
                    if (!message.TryGetValue("create-time", out DateTime createTime))
                    {
                        createTime = new DateTime(0);
                    }
                    if (!message.TryGetValue("is-successful-command", out bool isSuccessfulCommand))
                    {
                        isSuccessfulCommand = false;
                    }

                    RecentMessages.Add(await DbMessage.CreateAsync(content, createTime, isSuccessfulCommand, id, PlayerCollection, message.Id));
                }
            }
        }
 public void UpdateView(CollectionReference collectionReference)
 {
     CollectionListView.UpdateGridColumns(collectionReference);
 }
示例#19
0
 public async Task AddMessagingErrorAsync(MessagingError messagingError, CancellationToken cancellationToken)
 {
     CollectionReference collection = m_db.Collection(ErrorsCollection);
     await collection.AddAsync(messagingError, cancellationToken : cancellationToken);
 }
        private CollectionReference GetCollection(FirestoreDb db, string collectionName)
        {
            CollectionReference collection = db.Collection(collectionName);

            return(collection);
        }
示例#21
0
 public ProductService(FirestoreClient firestoreClient)
 {
     FirestoreClient    = firestoreClient;
     ProductsCollection = firestoreClient.DataBase.Collection("Products");
 }
 public CollectionReferenceWrapper(CollectionReference collectionReference)
 {
     _collectionReference = collectionReference ?? throw new ArgumentNullException(nameof(collectionReference));
 }
示例#23
0
        public ActionResult Create(CRM crm)
        {
            List <SelectListItem> clinictype = new List <SelectListItem>()
            {
                new SelectListItem {
                    Text = "Alopathy", Value = "Alopathy"
                },
                new SelectListItem {
                    Text = "Homeopathy", Value = "Homeopathy"
                },
                new SelectListItem {
                    Text = "Ayurvedic", Value = "Ayurvedic"
                },
                new SelectListItem {
                    Text = "Dental", Value = "Dental"
                },
                new SelectListItem {
                    Text = "Other", Value = "Other"
                },
            };

            ViewBag.CLINICTYPE = clinictype;

            List <SelectListItem> status = new List <SelectListItem>()
            {
                new SelectListItem {
                    Text = "Active", Value = "Active"
                },
                new SelectListItem {
                    Text = "Closed", Value = "Closed"
                },
                new SelectListItem {
                    Text = "Not Started", Value = "Not Started"
                },
            };

            ViewBag.STATUS = status;

            string Path = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
            FirestoreDb db = FirestoreDb.Create("greenpaperdev");


            try
            {
                CollectionReference         col1  = db.Collection("CRM");
                Dictionary <string, object> data1 = new Dictionary <string, object>
                {
                    { "referedby", crm.referedby },
                    { "referedon", DateTime.UtcNow },
                    { "clinictype", crm.clinictype },
                    { "address1", crm.address1 },
                    { "address2", crm.address2 },
                    { "address3", crm.address3 },
                    { "city", crm.city },
                    { "state", crm.state },
                    { "pin", crm.pin },
                    { "country", "India" },
                    { "clinicname", crm.clinicname },
                    { "doctorname", crm.doctorname },
                    { "contact", crm.contact },
                    { "nextmeetingdate", DateTime.SpecifyKind(crm.nextmeetingdate, DateTimeKind.Utc) },
                    { "comments", crm.comments },
                    { "status", crm.status }
                };

                col1.AddAsync(data1);


                // TODO: Add insert logic here
                //var result = await fireBaseClient.Child("Students").PostAsync(std);

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                return(View());
            }
        }
        public async Task DropCollection()
        {
            await _databaseInteractions.DropCollection(SelectedCollection);

            SelectedCollection = null;
        }
        public void NodeDoubleClick(CollectionReference value)
        {
            var documentSet = IoC.Get <IDocumentSet>();

            documentSet.OpenDocument <CollectionExplorerViewModel, CollectionReference>(value);
        }
示例#26
0
        public async Task <Maybe <string> > ExportAs(
            IScreen context,
            CollectionReference collectionReference,
            IList <DocumentReference> selectedDocuments = null)
        {
            if (collectionReference == null)
            {
                return(null);
            }

            var exportOptions = new CollectionExportOptions(collectionReference.IsFilesOrChunks, selectedDocuments?.Count);

            var dialogHostIdentifier = AppConstants.DialogHosts.Shell;

            if (context is Wpf.Framework.Shell.IDocument document)
            {
                dialogHostIdentifier = document.DialogHostIdentifier;
            }
            var result = await Show.Dialog(dialogHostIdentifier).For(exportOptions);

            if (result.Action is "cancel")
            {
                return(null);
            }

            var itemsToExport = result.Model.GetSelectedRecordsFilter() == 0
                ? collectionReference.Items
                : selectedDocuments;
            var referenceName = collectionReference.Name;

            Maybe <string> maybePath = null;

            switch (result.Model.GetSelectedExportFormat())
            {
            case 0:
                maybePath = await ExportToJson(itemsToExport, referenceName);

                break;

            case 1:
                maybePath = await ExportToExcel(itemsToExport, referenceName);

                break;

            case 2:
                maybePath = await ExportToCsv(itemsToExport, referenceName);

                break;

            case 3:
                maybePath = await ExportStoredFiles(itemsToExport);

                break;
            }

            if (maybePath.HasValue)
            {
                var builder = NotificationInteraction.Default()
                              .HasMessage($"{result.Model.ExportFormat} saved in:\n{maybePath.Value.ShrinkPath(128)}");

                if (Path.HasExtension(maybePath.Value))
                {
                    builder.Dismiss().WithButton("Open",
                                                 async button =>
                    {
                        await _applicationInteraction.OpenFileWithAssociatedApplication(maybePath.Value);
                    });
                }

                builder.WithButton("Reveal in Explorer",
                                   async button => { await _applicationInteraction.RevealInExplorer(maybePath.Value); })
                .Dismiss().WithButton("Close", button => { });

                builder.Queue();
            }

            return(maybePath);
        }
示例#27
0
        // code borrowed from https://cloud.google.com/firestore/docs/quickstart-servers#cloud-console
        public static async Task Main(string[] args)
        {
            var projectName  = "blazor-sample";
            var authFilePath = "PATH/TO/blazor-sample-auth.json";

            // environment variable could be configured differently, but for the sample simply hardcode it
            // the Firestore library expects this environment variable to be set
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", authFilePath);
            FirestoreDb firestoreDb = FirestoreDb.Create(projectName);

            // this section creates two document in the users-collection, alovelace and aturing
            CollectionReference         usersCollection = firestoreDb.Collection("users");
            DocumentReference           docRef          = usersCollection.Document("alovelace");
            Dictionary <string, object> user            = new Dictionary <string, object>
            {
                { "First", "Ada" },
                { "Last", "Lovelace" },
                { "Born", 1815 }
            };
            await docRef.SetAsync(user);

            docRef = usersCollection.Document("aturing");
            user   = new Dictionary <string, object>
            {
                { "First", "Alan" },
                { "Middle", "Mathison" },
                { "Last", "Turing" },
                { "Born", 1912 }
            };
            await docRef.SetAsync(user);

            // this section will fetch all users from the users-collection and print them to the console
            QuerySnapshot snapshot = await usersCollection.GetSnapshotAsync();

            foreach (DocumentSnapshot document in snapshot.Documents)
            {
                Console.WriteLine("User: {0}", document.Id);
                Dictionary <string, object> documentDictionary = document.ToDictionary();
                Console.WriteLine("First: {0}", documentDictionary["First"]);
                if (documentDictionary.ContainsKey("Middle"))
                {
                    Console.WriteLine("Middle: {0}", documentDictionary["Middle"]);
                }
                Console.WriteLine("Last: {0}", documentDictionary["Last"]);
                Console.WriteLine("Born: {0}", documentDictionary["Born"]);
                Console.WriteLine();
            }

            // all users will be fetched and send to the lambda callback, when users-collection is modified the changes will be send here in real-time
            // not only the change will be send when collection is modified, the entire collection will be returne
            FirestoreChangeListener firestoreChangeListener = usersCollection
                                                              .Listen((snapshot) =>
            {
                foreach (DocumentSnapshot document in snapshot.Documents)
                {
                    Console.WriteLine("User: {0}", document.Id);
                    Dictionary <string, object> documentDictionary = document.ToDictionary();
                    Console.WriteLine("First: {0}", documentDictionary["First"]);
                    Console.WriteLine("Last: {0}", documentDictionary["Last"]);
                    Console.WriteLine();
                }
            });

            // give some time for the 'Listen' function to be invoked
            await Task.Delay(2000);

            Console.WriteLine("Enter first name:");
            var firstName = Console.ReadLine();

            Console.WriteLine("Enter last name:");
            var lastName = Console.ReadLine();

            Console.WriteLine();

            user = new Dictionary <string, object>
            {
                { "First", firstName },
                { "Last", lastName }
            };
            await usersCollection.AddAsync(user);

            // give some time for the 'Listen' function to be invoked
            await Task.Delay(2000);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            await firestoreChangeListener.StopAsync();
        }
示例#28
0
        public async Task Listening2()
        {
            CollectionReference collection = db.Collection("testecsharp");
            Query query = collection.WhereGreaterThan("age", 5).OrderByDescending("age");

            FirestoreChangeListener listener = collection.Listen(snapshot =>
            {
                Console.WriteLine($"Callback received query snapshot");
                Console.WriteLine($"Count: {snapshot.Count}");
                Console.WriteLine("Changes:");
                string name = ""; int age = 0;
                foreach (DocumentChange change in snapshot.Changes)
                {
                    DocumentSnapshot document = change.Document;
                    Console.WriteLine($"{document.Reference.Id}: ChangeType={change.ChangeType}; OldIndex={change.OldIndex}; NewIndex={change.NewIndex})");
                    if (document.Exists)
                    {
                        if (document.ContainsField("name"))
                        {
                            name = document.GetValue <string>("name");
                        }
                        if (document.ContainsField("age"))
                        {
                            age = document.GetValue <int>("age");
                        }
                        Console.WriteLine($"  Document data: Name={name}; age={age}");
                    }
                }
                Console.WriteLine();
            });

            Console.WriteLine("Creating document for Sophie (age = 7)");
            DocumentReference doc1Ref = await collection.AddAsync(new { name = "Sophie", age = 7 });

            Console.WriteLine($"Sophie document ID: {doc1Ref.Id}");
            await Task.Delay(1000);

            Console.WriteLine("Creating document for James (age = 10)");
            DocumentReference doc2Ref = await collection.AddAsync(new { name = "James", age = 10 });

            Console.WriteLine($"James document ID: {doc2Ref.Id}");
            await Task.Delay(1000);

            Console.WriteLine("Modifying document for Sophie (set age = 11, higher than age for James)");
            await doc1Ref.UpdateAsync("age", 11);

            await Task.Delay(1000);

            Console.WriteLine("Modifying document for Sophie (set age = 12, no change in position)");
            await doc1Ref.UpdateAsync("age", 12);

            await Task.Delay(1000);

            Console.WriteLine("Modifying document for James (set age = 4, below threshold for query)");
            await doc2Ref.UpdateAsync("age", 4);

            await Task.Delay(1000);

            Console.WriteLine("Deleting document for Sophie");
            await doc1Ref.DeleteAsync();

            await Task.Delay(1000);

            Console.WriteLine("Stopping listener");
            await listener.StopAsync();
        }
示例#29
0
      public async Task <ActionResult> Login(User user)
      {
          //string Path = AppDomain.CurrentDomain.BaseDirectory + @"myfastingapp-bd6ec.json";
          string Path = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json";

          Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
          FirestoreDb db         = FirestoreDb.Create("greenpaperdev");
          string      message    = string.Empty;
          string      clinicPlan = "";


          if (user.clinicmobilenumber == "" || user.clinicmobilenumber == null)
          {
              //Query Qref = db.Collection("Students").WhereEqualTo("StudentName","Suvidhi");
              Query         Qref = db.Collection("SuperUsers").WhereEqualTo("UserId", user.mobile_number).WhereEqualTo("Password", user.password).Limit(1);
              QuerySnapshot snap = await Qref.GetSnapshotAsync();

              if (snap.Count > 0)
              {
                  foreach (DocumentSnapshot docsnap in snap)
                  {
                      SuperUser superuser = docsnap.ConvertTo <SuperUser>();
                      if (docsnap.Exists)
                      {
                          GlobalSessionVariables.UserRoles = "SuperAdmin";
                          FormsAuthentication.SetAuthCookie(superuser.UserName + "-" + superuser.UserName, superuser.RememberMe);

                          return(RedirectToAction("Index"));
                      }
                      else
                      {
                          message = "Username and/or password is incorrect.";
                      }
                  }
              }
              else
              {
                  message = "Username and/or password is incorrect.";
              }
          }
          else
          {
              //DocumentReference docref = db.Collection("clinics").Document("");
              //DocumentSnapshot docsnap = await docref.GetSnapshotAsync();

              //Query Qref = db.Collection("clinics").WhereEqualTo("clinicmobilenumber", user.clinicmobilenumber).Limit(1);
              Query         Qref       = db.Collection("clinics").WhereEqualTo("clinic_code", user.clinicmobilenumber).Limit(1);
              QuerySnapshot snapClinic = await Qref.GetSnapshotAsync();

              if (snapClinic.Count > 0)
              {
                  DocumentSnapshot docsnapClinic = snapClinic.Documents[0];

                  Clinic clinic = docsnapClinic.ConvertTo <Clinic>();
                  clinicPlan = clinic.selected_plan;

                  GlobalSessionVariables.ClinicMobileNumber   = clinic.clinicmobilenumber;
                  GlobalSessionVariables.ClinicDocumentAutoId = docsnapClinic.Id;

                  QuerySnapshot snapUser = await docsnapClinic.Reference.Collection("user").WhereEqualTo("mobile_number", user.mobile_number).GetSnapshotAsync();

                  if (snapUser.Count > 0)
                  {
                      foreach (DocumentSnapshot docsnapUsers in snapUser)
                      {
                          User          userLoggedIn     = docsnapUsers.ConvertTo <User>();
                          QuerySnapshot snapUserPassword = await docsnapClinic.Reference.Collection("user").WhereEqualTo("mobile_number", user.mobile_number).WhereEqualTo("password", user.password).GetSnapshotAsync();

                          if (snapUserPassword.Count > 0)
                          {
                              Session["sessionid"] = System.Web.HttpContext.Current.Session.SessionID;

                              CollectionReference         col1  = db.Collection("clinics").Document(docsnapClinic.Id).Collection("logins");
                              Dictionary <string, object> data1 = new Dictionary <string, object>
                              {
                                  { "userid", user.mobile_number },
                                  { "sessionid", System.Web.HttpContext.Current.Session.SessionID },
                                  { "loggedin", true },
                                  { "creationate", DateTime.UtcNow }
                              };

                              await col1.Document().SetAsync(data1);


                              DocumentSnapshot docsnapUser = snapUserPassword.Documents[0];

                              User userForRoles = docsnapUser.ConvertTo <User>();
                              GlobalSessionVariables.UserRoles = string.Join(",", userForRoles.user_roles);


                              FormsAuthentication.SetAuthCookie(userLoggedIn.mobile_number + "-" + userLoggedIn.name, user.RememberMe);
                              //if(User.IsInRole("Receptionist"))
                              if (userForRoles.user_roles.Contains("Receptionist"))
                              {
                                  return(RedirectToAction("Index", "Appointment"));
                              }
                              else if (userForRoles.user_roles.Contains("Admin"))
                              {
                                  return(RedirectToAction("Index", "User"));
                              }
                              else
                              {
                                  return(RedirectToAction("Waiting", "Appointment"));
                              }
                          }
                          else
                          {
                              message = "Password for user " + user.mobile_number + " is incorrect.";
                          }
                      }
                  }
                  else
                  {
                      message = "User Id " + user.mobile_number + " does not exist for " + clinic.clinicname + " Clinic.";
                  }
              }
              else
              {
                  message = "Sorry,Clinic mobile number is not valid.";
              }
          }

          ViewBag.Message = message;

          //UsersEntities usersEntities = new UsersEntities();
          //int? userId = usersEntities.ValidateUser(user.Username, user.Password).FirstOrDefault();

          //string message = string.Empty;
          //switch (userId.Value)
          //{
          //    case -1:
          //        message = "Username and/or password is incorrect.";
          //        break;
          //    case -2:
          //        message = "Account has not been activated.";
          //        break;
          //    default:
          //        FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
          //        return RedirectToAction("Profile");
          //}

          //ViewBag.Message = message;
          //if (user.Username == "administrator" && user.Password == "jAy@4231")
          //{
          //    FormsAuthentication.SetAuthCookie(user.Username, user.RememberMe);
          //    return RedirectToAction("Index");
          //}


          return(View(user));
      }