Exemplo n.º 1
0
        string FirebaseDatabaseService.SetChildValueByAutoId(string nodeKey, object obj, Action onSuccess, Action <string> onError)
        {
            DatabaseReference rootRef          = Database.DefaultInstance.GetRootReference();
            DatabaseReference nodeRef          = rootRef.GetChild(nodeKey);
            string            objectJsonString = JsonConvert.SerializeObject(obj);
            NSError           jsonError        = null;
            NSData            nsData           = NSData.FromString(objectJsonString);
            NSObject          nsObj            = NSJsonSerialization.Deserialize(nsData, NSJsonReadingOptions.AllowFragments, out jsonError);

            DatabaseReference newChildRef = nodeRef.GetChildByAutoId();

            newChildRef.SetValue(nsObj, (NSError error, DatabaseReference reference) =>
            {
                if (error == null)
                {
                    if (onSuccess != null)
                    {
                        onSuccess();
                    }
                }
                else if (onError != null)
                {
                    onError(error.Description);
                }
            });

            return(newChildRef.Key);
        }
Exemplo n.º 2
0
        public void Save(BaseShow show)
        {
            var dictionnary = GetDictionnaryFromObject(show);

            showRefence.GetChildByAutoId().SetValue(dictionnary);
            // favoriteService.AddItem(show);
        }
Exemplo n.º 3
0
        void InsertarEnFireBase()
        {
            object[]          alcoholKeys   = { "Nombre", "Edad", "Correo", "Password", "Sexo", "rutaImagen" };
            object[]          alcoholValues = { txtNombreRegistro.Text, txtEdadRegistro.Text, txtCorreoRegistro.Text, txtContraRegistro.Text, txtSexoRegistro.Text, "holis" };
            var               qs2           = NSDictionary.FromObjectsAndKeys(alcoholValues, alcoholKeys, alcoholKeys.Length);
            DatabaseReference rootNode      = Database.DefaultInstance.GetRootReference();
            DatabaseReference productosNode = rootNode.GetChild("0").GetChild("Usuarios");
            DatabaseReference productoNode  = productosNode.GetChildByAutoId();

            productoNode.SetValue <NSDictionary>(qs2);
        }
        public string Create(T obj)
        {
            DatabaseReference objNode;

            if (string.IsNullOrEmpty(obj.Id))
            {
                objNode = _dbGroupNode.GetChildByAutoId();
                obj.Id  = objNode.Key;
            }
            else
            {
                objNode = _dbGroupNode.GetChild(obj.Id);
            }

            var updates = Encoder.EncodeObject(obj);

            objNode.UpdateChildValues(updates);

            return(obj.Id);
        }
Exemplo n.º 5
0
        void SetOrderInFireBase()
        {
            object[]          alcoholKeys   = { "Fecha", "TotalProductos", "TotalPrecio", "Repartidor", "Status", "Direccion", "Descripcion" };
            object[]          alcoholValues = { DateTime.Now.Date.ToString(), TotalProducts().ToString(), CalcularPrecioTotal(), "Martin Franciso Jimenez Sanchez", 0, "Cima del Sol 153, Lomas del Sol,37150, Leon GTO", ProductsDesc() };
            var               qs2           = NSDictionary.FromObjectsAndKeys(alcoholValues, alcoholKeys, alcoholKeys.Length);
            DatabaseReference rootNode      = Database.DefaultInstance.GetRootReference();
            DatabaseReference productosNode = rootNode.GetChild("0").GetChild("Pedidos").GetChild(DataPersistanceClass.persona.Id);
            DatabaseReference productoNode  = productosNode.GetChildByAutoId();


            pedido               = new Pedido();
            pedido.Id            = productoNode.Key;
            pedido.Repartidor    = "Martin Franciso Jimenez Sanchez";
            pedido.IdUser        = DataPersistanceClass.persona.Id;
            pedido.Date          = DateTime.Now.ToString();
            pedido.Address       = "Cima del Sol 153, Lomas del Sol,37150, Leon GTO";
            pedido.IdStatus      = 0;
            pedido.TotalPrice    = double.Parse(CalcularPrecioTotal());
            pedido.TotalProducts = TotalProducts();
            pedido.Products      = productos;
            productoNode.SetValue <NSDictionary>(qs2);
        }
 public string Push()
 {
     return(databaseReference.GetChildByAutoId().Key);
 }
Exemplo n.º 7
0
        partial void AddUser_TouchUpInside(NSObject sender)
        {
            double fare = 0;

            if (lblPassword.ToString() == null || lblPassword.ToString().Length <= 0)
            {
                CallAlert("Error adding the user", "Do not leave the password in blank.");
            }
            else if (lblEmail.ToString() == null || lblEmail.ToString().Length <= 0)
            {
                CallAlert("Error adding the user", "Do not leave the email in blank.");
            }
            if (Double.TryParse(lblAmount.Text, out fare))
            {
                fare = Double.Parse(lblAmount.Text);
            }
            string position = lblPosition.Text;
            string name     = lblName.Text;
            string rfid     = lblRfid.Text;
            string role     = "user";

            if (switchAdmin.On)
            {
                role = "administrator";
            }
            if (fare <= 0 || fare.ToString() == null || fare.ToString().Length <= 0)
            {
                CallAlert("Error adding the user", "The amount can't be lower than one.");
            }
            else if (rfid == null || rfid.Length <= 0)
            {
                CallAlert("Error adding the user", "The rfid can't be in blank.");
            }
            else if (position.Length <= 0 || position == null || name == null || name.Length <= 0)
            {
                CallAlert("Error adding the user", "Do not leave empty fields.");
            }
            else
            {
                Auth.DefaultInstance.CreateUser(lblEmail.Text, lblPassword.Text, HandleAuthResult);
            }

            void HandleAuthResult(User user, NSError error)
            {
                if (error != null)
                {
                    AuthErrorCode errorCode;
                    if (IntPtr.Size == 8) // 64 bits devices
                    {
                        errorCode = (AuthErrorCode)((long)error.Code);
                    }
                    else // 32 bits devices
                    {
                        errorCode = (AuthErrorCode)((int)error.Code);
                    }

                    // Posible error codes that CreateUser method could throw
                    switch (errorCode)
                    {
                    case AuthErrorCode.InvalidEmail:
                        CallAlert("Error", "Please insert a valid email");
                        break;

                    case AuthErrorCode.EmailAlreadyInUse:
                        CallAlert("Error", "Email is already in use");
                        break;

                    case AuthErrorCode.OperationNotAllowed:
                        CallAlert("Error", "Operation not allowed");
                        break;

                    case AuthErrorCode.WeakPassword:
                        CallAlert("Error", "Insecure password, please try again");
                        break;

                    default:
                        // Print error
                        break;
                    }
                }
                else
                {
                    //Generates a auto id for the team members node.
                    DatabaseReference adduserNode = userNode.GetChildByAutoId();
                    //Generates an auto id for the rfid node.
                    DatabaseReference addrfidNode = rfidNode.GetChildByAutoId();
                    //Sets the keys and values for the node.
                    object[] rfid_keys = { "id", "status", "tag" };
                    object[] rfid_val  = { addrfidNode.Key, 0, lblRfid.Text };
                    //Join the key with the nodes.
                    var rfid_data = NSDictionary.FromObjectsAndKeys(rfid_val, rfid_keys, rfid_keys.Length);
                    addrfidNode.SetValue(rfid_data);
                    //Sets the keys and values for the node.
                    object[] keys   = { "authid", "fare", "id", "name", "position", "rfid", "roles" };
                    object[] values = { user.Uid, fare, adduserNode.Key, name, position, addrfidNode.Key, role };
                    var      data   = NSDictionary.FromObjectsAndKeys(values, keys, keys.Length);
                    adduserNode.SetValue(data);
                    //Return to the main view.
                    this.NavigationController.PopViewController(true);
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Method that initialize all the buttons contained in the cell.
        /// All the buttons work with anonymous functions or delegates.
        /// </summary>
        /// <param name="cell">Cell.</param>
        public void initilizeButton(CollectionCellViewController cell)
        {
            //Event that delete an employee. It prompts an alert as confirmation to proceed with the delete.
            cell.BtnDelete.TouchUpInside += delegate {
                try
                {
                    var alert = UIAlertController.Create("Delete employee", "Are you sure you want to delete this employee?", UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("Delete", UIAlertActionStyle.Destructive, delegate
                    {
                        //Looks for a user in the team_members node.
                        DatabaseReference userNode_temp = userNode.GetChild(cell.Id);
                        userNode_temp.RemoveValue();
                        //Sets the value to null.
                        userNode_temp.SetValue <NSObject>(null);
                        object[] nodes       = { $"team_members/{cell.Id} " };
                        object[] nodesValues = { null };
                        var childUpdates     = NSDictionary.FromObjectsAndKeys(nodesValues, nodes, nodes.Length);
                        //Updates the child to delete the information from the firebase database.
                        root.UpdateChildValues(childUpdates);

                        InitializeFirebase();
                    }));
                    alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
                    PresentViewController(alert, true, null);
                }
                catch (Exception ex) {}
            };

            //Method to check if the user is online or offline.
            cell.BtnGoOnline.TouchUpInside += delegate {
                try
                {
                    if (cell.Status == "Online")
                    {
                        //If the user is online then it looks for the child related to the user id.
                        DatabaseReference onlineNode = tempNode.GetChild(cell.Id);
                        //Executes a single event to try to get the value from that node.
                        onlineNode.ObserveSingleEvent(DataEventType.Value, (snapshot) =>
                        {
                            string fecha = DateTime.Now.ToString();
                            if (snapshot.ChildrenCount > 0)
                            {
                                //Gets the value of the response from firebase.
                                var onlineUser = snapshot.GetValue <NSDictionary>();
                                //tt_values gets the values of the child node from onlineUser.
                                var tt_values = onlineUser.Values;
                                //Creates a node in timetracking with the following information /timetracking/{user.id}/{autogenkey}/
                                DatabaseReference tt_node = timetrackingNode.GetChild(cell.Id).GetChild(onlineUser.Keys[0].ToString());
                                //Create an object with the fields that the node must have.
                                object[] timetracking_key = { "end_date", "start_date", "status", "uid_worker" };
                                //Gets the information from the temp_entrance.
                                var start_date = tt_values[0].ValueForKey(new NSString("start_date"));
                                var status     = tt_values[0].ValueForKey(new NSString("status"));
                                var uid_worker = tt_values[0].ValueForKey(new NSString("uid_worker"));
                                //Adds the information from temp_entrance to the object timetracking_value.
                                object[] timetracking_value = { fecha, start_date, 1, uid_worker };
                                //Create a dictonary containing the keys, values and the length of the object.
                                var data = NSDictionary.FromObjectsAndKeys(timetracking_value, timetracking_key, timetracking_key.Length);
                                //Adds the information to the timetracking node.
                                tt_node.SetValue <NSDictionary>(data);
                                //Deletes the information from the temp_entrance node.
                                tempNode.GetChild(cell.Id).SetValue <NSDictionary>(null);
                                int index = lst_employees.FindIndex(x => x.Id.Contains(cell.Id));
                                lst_employees[index].Status = "Offline";
                                CheckIfOnline();
                            }
                            else
                            {
                                int index = lst_employees.FindIndex(x => x.Id.Contains(cell.Id));
                                lst_employees[index].Status = "Offline";
                                CheckIfOnline();
                            }
                        });
                    }
                    if (cell.Status == "Offline")
                    {
                        string fecha = DateTime.Now.ToString();
                        //Create a key object containing the user_id as key.
                        object[] k  = { cell.Id };
                        object[] vs = { null };
                        var      da = NSDictionary.FromObjectsAndKeys(vs, k, k.Length);
                        //Adds the child node to the temp_entrance table.
                        tempNode.UpdateChildValues(da);
                        //Obtained the information from the created node.
                        DatabaseReference subNode = tempNode.GetChild(cell.Id);
                        //Generated an autoid as child of the node created with the user id.
                        DatabaseReference subNode2 = subNode.GetChildByAutoId();
                        //Created objects with the required fields, and information.
                        object[] keys   = { "end_date", "start_date", "status", "uid_worker" };
                        object[] values = { "", new NSString(fecha), 0, cell.Id };
                        //Created a dictionary with the value, keys and its length.
                        var data = NSDictionary.FromObjectsAndKeys(values, keys, keys.Length);
                        //Adds the value to the child node.
                        subNode2.SetValue <NSDictionary>(data);
                        int index = lst_employees.FindIndex(x => x.Id.Contains(cell.Id));
                        lst_employees[index].Status = "Online";
                        CheckIfOnline();
                    }
                }
                catch (Exception ex)
                {
                }
            };
        }