Beispiel #1
0
        public bool FollowerRegister(int id, string emailAddress, string firstName, string lastName, string company = "", string apikey = "")
        {
            if (User.Identity.Name != null)
                if (!OPIMsys.Filters.ApiKeyHandler.ApiKeyToUser(apikey, Request))
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Forbidden));
            if (!Roles.IsUserInRole("ReportAPI") && !Roles.IsUserInRole("ApiReadUser"))
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Forbidden));
            AccountApiKey apiUser = OPIMsys.Filters.ApiKeyHandler.KeyToAccount(apikey, Request);
            if (!Roles.IsUserInRole("ReportAPI"))
                if (id != apiUser.CompanyId)
                    throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Forbidden));

            OPIMsys.RegexUtilities regUtil = new RegexUtilities();
            if (!regUtil.IsValidEmail(emailAddress))
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Conflict));
            if(db.CompanyFollowers.Where(a => a.EmailAddress == emailAddress).Count() > 0)
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Conflict));
            Company comp = db.Companies.Find(id);
            if (comp == null)
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            CompanyFollower follow = new CompanyFollower();
            follow.EmailAddress = emailAddress;
            follow.FirstName = firstName;
            follow.LastName = lastName;
            follow.CompanyName = company;
            comp.CompanyFollowers.Add(follow);
            db.SaveChanges();
            return true;
        }
        private bool ValidarCampos()
        {
            if (iDTipoDocumentoComboBox.SelectedIndex == -1)
            {
                errorProvider1.SetError(iDTipoDocumentoComboBox, "Debe seleccionar un tipo de documento");
                iDTipoDocumentoComboBox.Focus();
                return false;
            }
            errorProvider1.SetError(iDTipoDocumentoComboBox, "");
            
            if (documentoTextBox.Text == "")
            { 
                errorProvider1.SetError(documentoTextBox, "Debe ingresar un numero de documento");
                documentoTextBox.Focus();
                return false;
            }
            errorProvider1.SetError(documentoTextBox, "");
            
            if (nombresContactoTextBox.Text == "")
            {
                errorProvider1.SetError(nombresContactoTextBox, "Debe ingresar un nombre de contacto");
                nombresContactoTextBox.Focus();
                return false;
            }
            errorProvider1.SetError(nombresContactoTextBox, "");
            
            if (apellidosContactoTextBox.Text == "")
            {
                errorProvider1.SetError(apellidosContactoTextBox, "Debe ingresar un apellido de contacto");
                apellidosContactoTextBox.Focus();
                return false;
            }
            errorProvider1.SetError(apellidosContactoTextBox, "");

            if (nombreTextBox.Text == "")
            {
                errorProvider1.SetError(nombreTextBox, "Debe ingresar un nombre de proveedor");
                nombreTextBox.Focus();
                return false;
            }
            errorProvider1.SetError(nombreTextBox, "");

            if (correoTextBox.Text != "")
            {
                RegexUtilities regexUtilities = new RegexUtilities();
                if(!regexUtilities.IsValidEmail(correoTextBox.Text))
                {
                    errorProvider1.SetError(correoTextBox, "Ingrese un correo valido");
                    correoTextBox.Focus();
                    return false;
                }
                errorProvider1.SetError(correoTextBox, "");
            }
            return true;
        }
Beispiel #3
0
 private void txtAdminEmail_LostFocus(object sender, EventArgs e)
 {
     RegexUtilities test = new RegexUtilities();
     if(test.IsValidEmail(txtAdminEmail.Text))
     {
         lblEmailVerify.ForeColor = System.Drawing.Color.Green;
         lblEmailVerify.Text = "Email accepted.";
         Email_Validated = true;
     }
     else
     {
         lblEmailVerify.ForeColor = System.Drawing.Color.Red;
         lblEmailVerify.Text = "A valid email is required";
         Email_Validated = false;
     }
 }
Beispiel #4
0
    protected void signUp_Click(object sender, EventArgs e)
    {
        if ((newPass.Text.Length != 0) && (newId.Text.Length != 0))
        {

           
            string sql2 = string.Format("SELECT Username FROM users WHERE Username = '******'", newId.Text);
            var con = new DBCon();
            var reader = con.Execute(sql2);
            RegexUtilities util = new RegexUtilities();
            bool check= util.IsValidEmail(newEmailid.Text);
            if (!reader.HasRows && check)
            {
                con.Close();
                
                string sql = string.Format("INSERT INTO users ([Username], [Password], [email]) VALUES ('{0}', '{1}', '{2}')", newId.Text, newPass.Text,newEmailid.Text);
                con.Execute(sql);
                checking.Text = "Account Created Successfully!";
                con.Close();
            }
            else if(reader.HasRows)
            {
                checking.Text = "Username Already Exists!";
                con.Close();
            }
            else if (!check)
            {
                checking.Text = "Invalid Email ID!";
                con.Close();
            }
            con.Close();

        }
        else
        {
            checking.Text = "Invalid Username or Password!";
            
        }
       
    }
Beispiel #5
0
        private bool validar()
        {
            if (tbx_nombres.TextLength == 0)
            {
                MessageBox.Show("Llene el campo Nombres.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            else if (!RegexUtilities.IsOnlyAlphas(tbx_nombres.Text))
            {
                MessageBox.Show("El nombre no debe contener caracteres numéricos.", "Información inválida.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_apellidos.TextLength == 0)
            {
                MessageBox.Show("Llene el campo Apellidos.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            else if (!RegexUtilities.IsOnlyAlphas(tbx_apellidos.Text))
            {
                MessageBox.Show("El apellido no debe contener caracteres numéricos.", "Información inválida.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (cbx_mesnac.SelectedIndex == -1)
            {
                MessageBox.Show("Seleccione su mes de nacimiento.", "Información incompleta.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (cbx_dianac.SelectedIndex == -1)
            {
                MessageBox.Show("Seleccione su día de nacimiento.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_añonac.TextLength == 0)
            {
                MessageBox.Show("Escriba su año de nacimiento.", "Información incompleta.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            else if (!RegexUtilities.IsOnlyNumerics(tbx_añonac.Text))
            {
                MessageBox.Show("El año no debe contener letras.", "Información inválida", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_calle.TextLength == 0)
            {
            }
            if (tbx_numext.TextLength == 0)
            {
                MessageBox.Show("Llene el número externo.", "Información inválida", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            else if (!RegexUtilities.IsOnlyNumerics(tbx_numext.Text))
            {
                MessageBox.Show("El número externo contiene letras.", "Información inválida", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_col.TextLength == 0)
            {
                MessageBox.Show("Llene la colonia de su domicilio.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_estado.TextLength == 0)
            {
                MessageBox.Show("Llene el estado de su domicilio.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_munic.TextLength == 0)
            {
                MessageBox.Show("Llene el municipio de su domicilio.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_cp.TextLength == 0)
            {
                MessageBox.Show("Llene el código postal de su domicilio.", "Información incompleta", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            else if (!RegexUtilities.IsOnlyNumerics(tbx_cp.Text))
            {
                MessageBox.Show("El código postal no debe contener letras.", "Información inválida", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_curp.TextLength != 18)
            {
                MessageBox.Show("El CURP debe contener 18 caracteres.", "Información incompleta.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (!RegexUtilities.IsValidEmail(tbx_email.Text))
            {
                MessageBox.Show("El correo electrónico no es válido.", "Información inválida.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }
            if (tbx_password.TextLength != 8)
            {
                MessageBox.Show("La contraseña debe contener 8 caracteres.", "Información incompleta.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return(false);
            }

            client = new ClienteClass(
                id_emp,
                tbx_nombres.Text,
                tbx_apellidos.Text,
                new DateTime(Convert.ToInt32(tbx_añonac.Text), Convert.ToInt32(cbx_mesnac.Text), Convert.ToInt32(cbx_dianac.Text)),
                new Domicilio(tbx_calle.Text, tbx_numext.Text, tbx_numint.Text, tbx_col.Text, tbx_munic.Text, tbx_estado.Text, tbx_cp.Text),
                tbx_curp.Text,
                tbx_email.Text,
                tbx_password.Text
                );

            return(true);
        }
Beispiel #6
0
 public void RegexUtilities_ValidateEmailForOnlyDot()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail(".com"));
 }
 public async Task<int> AddUser(string userEmail)
 {
     try
     {
         RegexUtilities util = new RegexUtilities();
         if (util.IsValidEmail(userEmail))
         {
             var user = userRepository.Find(u => u.UserName == userEmail);
             if (user != null)
             {
                 return 3;
             }
             else
             {
                 await SendMailHelper.SendInviteFromAdmin(userEmail);
                 return 2;
             }
         }
         else
         {
             return 0;
         }
     }
     catch
     {
         return 0;
     }
 }
Beispiel #8
0
        private async void Register()
        {
            if (string.IsNullOrEmpty(this.FirstName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.FirstNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.LastName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LastNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation,
                    Languages.Accept);

                return;
            }

            if (!RegexUtilities.IsValidEmail(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation2,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.Telephone))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PhoneValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.Password))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PasswordValidation,
                    Languages.Accept);

                return;
            }

            if (this.Password.Length < 6)
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PasswordValidation2,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.Confirm))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.ConfirmValidation,
                    Languages.Accept);

                return;
            }

            if (this.Password != this.Confirm)
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.ConfirmValidation2,
                    Languages.Accept);

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var checkConnetion = await this.apiService.CheckConnection();

            if (!checkConnetion.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    checkConnetion.Message,
                    Languages.Accept);

                return;
            }

            byte[] imageArray = null;
            if (this.file != null)
            {
                imageArray = FilesHelper.ReadFully(this.file.GetStream());
            }

            var user = new User
            {
                Email      = this.Email,
                FirstName  = this.FirstName,
                LastName   = this.LastName,
                Telephone  = this.Telephone,
                ImageArray = imageArray,
                UserTypeId = 1,
                Password   = this.Password,
            };

            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            var response    = await this.apiService.Post(
                apiSecurity,
                "/api",
                "/Users",
                user);

            if (!response.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    response.Message,
                    Languages.Accept);

                return;
            }

            this.IsRunning = false;
            this.IsEnabled = true;

            await Application.Current.MainPage.DisplayAlert(
                Languages.ConfirmLabel,
                Languages.UserRegisteredMessage,
                Languages.Accept);

            await Application.Current.MainPage.Navigation.PopAsync();
        }
Beispiel #9
0
 public void RegexUtilities_ValidateEmailForOnlyText()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail("abc"));
 }
        public void AddMedia()
        {
            List <string> opts = new List <string>()
            {
                "Song", "Video", "Back"
            };
            string sel = null;

            while (true)
            {
                Console.Clear();
                sel = RegexUtilities.GetMenu(opts);
                if (sel == opts[2])
                {
                    return;
                }

                else if (sel == opts[0])
                {
                    Console.Clear();
                    string fName = RegexUtilities.WriteData("File Name(with extension):  ");
                    Console.Clear();

                    try
                    {
                        Song song = new Song(fName);


                        Spotflix.SaveMedia(song);
                        Console.WriteLine("Win");
                        Thread.Sleep(2000);
                        return;
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Fail");
                        Thread.Sleep(2000);
                    }
                }

                else if (sel == opts[1])
                {
                    Console.Clear();
                    string fName = RegexUtilities.WriteData("File Name(with extension):  ");
                    Console.Clear();


                    try
                    {
                        Video video = new Video(fName);
                        Spotflix.SaveMedia(video);
                        return;
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Fail");
                        Thread.Sleep(2000);
                    }
                }
            }
        }
        private async void Save()
        {
            if (string.IsNullOrEmpty(this.User.FirstName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.FirstNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.User.LastName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LastNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.User.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation,
                    Languages.Accept);

                return;
            }

            if (!RegexUtilities.IsValidEmail(this.User.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation2,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.User.Telephone))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PhoneValidation,
                    Languages.Accept);

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var checkConnetion = await this.apiService.CheckConnection();

            if (!checkConnetion.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    checkConnetion.Message,
                    Languages.Accept);

                return;
            }



            var userDomain  = Converter.ToUserDomain(this.User);
            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            var response    = await this.apiService.Post(
                apiSecurity,
                "/api/account",
                "/customer",
                userDomain);

            if (!response.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    response.Message,
                    Languages.Accept);

                return;
            }

            var userApi = await this.apiService.GetUserByEmail(
                apiSecurity,
                "/api/account",
                "/customer/getcustomer",
                MainViewModel.GetInstance().Token.TokenType,
                MainViewModel.GetInstance().Token.AccessToken,
                MainViewModel.GetInstance().Token.UserName);

            userApi.ImageArray = User.ImageArray;
            var userLocal = Converter.ToUserLocal(userApi, Convert.ToInt32(MainViewModel.GetInstance().Token.UserName));

            MainViewModel.GetInstance().User = userLocal;
            MainViewModel.GetInstance().Login.registerDataService(userApi, MainViewModel.GetInstance().Token);
            MainViewModel.GetInstance().ImageSource = ImageSource.FromStream(() => new MemoryStream(User.ImageArray));
            this.dataService.Update(userLocal);

            this.IsRunning = false;
            this.IsEnabled = true;
            await Application.Current.MainPage.DisplayAlert(
                Languages.ConfirmLabel,
                "Profile Updated Succefully",
                Languages.Accept);

            //  await App.Navigator.PopAsync();
        }
Beispiel #12
0
 public void RegexUtilities_ValidateNullEmail()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail(null));
 }
        public static void Main(string[] args)
        {
            Console.CursorVisible = false;
            RegexUtilities.LoadingScreen();
            Thread.Sleep(3000);
            List <string> start = new List <string>()
            {
                "Hello, and welcome to Spotflix!", "Log In", "Register", "Admin Log In", "Exit"
            };
            List <string> mainMenu = new List <string>()
            {
                "Menu", "Search", "Profile", "play", "Log out"
            };
            List <string> searchMenu = new List <string>()
            {
                "Search: ", "Filters", "Go!", "Back"
            };

            Console.Clear();
            while (true)
            {
                RegexUtilities.LoadingScreen();
                string selectedMenuItem = RegexUtilities.GetMenu(start);
                if (selectedMenuItem == "Log In")
                {
                    Console.Clear();
                    RegexUtilities.LoadingScreen();
                    string username = Spotflix.LogIn();

                    if (username != "")
                    {
                        User activeUser = Spotflix.GetUserDB[username];
                        while (true)
                        {
                            Console.Clear();
                            RegexUtilities.LoadingScreen();
                            selectedMenuItem = RegexUtilities.GetMenu(mainMenu);
                            if (selectedMenuItem == "Log out")
                            {
                                username = ""; break;
                            }

                            else if (selectedMenuItem == "Search")
                            {
                                while (true)
                                {
                                    Console.Clear();
                                    RegexUtilities.LoadingScreen();
                                    selectedMenuItem = RegexUtilities.GetMenu(searchMenu);
                                    string searchKey = "";
                                    if (selectedMenuItem == searchMenu[0])
                                    {
                                        Console.Clear();
                                        RegexUtilities.LoadingScreen();
                                        searchMenu[0]  = searchMenu[0].Substring(0, 8);
                                        searchKey      = RegexUtilities.WriteData(searchMenu[0]);
                                        searchMenu[0] += searchKey;
                                        Console.Clear();
                                    }

                                    else if (selectedMenuItem == searchMenu[2])
                                    {
                                        Filter       fil     = new Filter();
                                        List <Media> results = fil.Search(searchKey);
                                        if (results.Count > 0)
                                        {
                                            List <string> lsSe = new List <string>();
                                            foreach (Media media in results)
                                            {
                                                lsSe.Add(media.GetMetadata().GetName());
                                            }
                                            lsSe.Add("Back");
                                            while (true)
                                            {
                                                string selectMedia = RegexUtilities.GetMenu(lsSe);
                                                if (selectMedia != "" && selectMedia != "Back")
                                                {
                                                    int   ind   = lsSe.IndexOf(selectMedia);
                                                    Media media = results[ind];
                                                    if (media.GetType() == typeof(Song))
                                                    {
                                                        //display info
                                                        media.Play();
                                                    }
                                                }
                                                else if (selectMedia == "Back")
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    else if (selectedMenuItem == searchMenu[3])
                                    {
                                        Console.Clear();
                                        break;
                                    }
                                }
                            }

                            else if (selectedMenuItem == "play")
                            {
                                //SoundPlayer player = new SoundPlayer();
                                //player.SoundLocation = "CSI.wav";
                                //player.Play();
                                //Player player = new Player();
                                //player.Open("CSI.wav");
                                //Thread.Sleep(30000);
                                //player.End();
                            }
                        }
                    }
                }

                else if (selectedMenuItem == "Register")
                {
                    Console.Clear();
                    RegexUtilities.LoadingScreen();
                    Spotflix.Register();
                    Save(Spotflix.GetUserDB, Spotflix.GetMediaDB, Spotflix.GetPeopleDB, fileName);
                }

                else if (selectedMenuItem == "Admin Log In")
                {
                    Console.Clear();
                    RegexUtilities.LoadingScreen();
                    string adm = Spotflix.AdminLogIn();
                    if (adm != "")
                    {
                        User administrator = Spotflix.GetUserDB[adm];



                        List <string> admMenu = new List <string>()
                        {
                            "Add Media", "a", "b", "c", "Log out"
                        };
                        while (true)
                        {
                            Console.Clear();
                            selectedMenuItem = RegexUtilities.GetMenu(admMenu);

                            if (selectedMenuItem == "Add Media")
                            {
                                Console.Clear();
                                RegexUtilities.LoadingScreen();
                                administrator.AddMedia();
                                Save(Spotflix.GetUserDB, Spotflix.GetMediaDB, Spotflix.GetPeopleDB, fileName);
                                Console.WriteLine("Ready");
                                Thread.Sleep(1000);
                                Console.Clear();
                            }

                            else if (selectedMenuItem == "Log out")
                            {
                                adm = "";
                                break;
                            }

                            else if (selectedMenuItem == "a")
                            {
                            }

                            Save(Spotflix.GetUserDB, Spotflix.GetMediaDB, Spotflix.GetPeopleDB, fileName);
                        }
                    }

                    else
                    {
                        Console.Clear();
                        RegexUtilities.LoadingScreen();
                        Console.WriteLine("You are not an administrator.");
                        break;
                    }


                    Save(Spotflix.GetUserDB, Spotflix.GetMediaDB, Spotflix.GetPeopleDB, fileName);
                }



                else if (selectedMenuItem == "Exit")
                {
                    Save(Spotflix.GetUserDB, Spotflix.GetMediaDB, Spotflix.GetPeopleDB, fileName);
                    Environment.Exit(0);
                }



                Console.Clear();
            }


            /*
             *
             * string ans = Console.ReadLine();
             *
             * if (ans == "new")
             * {
             *  Spotflix.Register();
             * }
             *
             * else if (ans == "returning")
             * {
             *  Console.WriteLine("Please write your username and password");
             *  Console.WriteLine("Username: "******"Password: "******"What do you want to do?");
             *          Console.WriteLine("a) Search for music or videos");
             *          Console.WriteLine("b) Go to playlists");
             *          Console.WriteLine("c) Look for other profiles");
             *          Console.WriteLine("");
             *          Console.WriteLine("d) Exit");
             *
             *          string Ans = Console.ReadLine();
             *
             *          if (Ans == "a")
             *          {
             *              Console.WriteLine("Please write the name of the song or video that you are looking for");
             *              string search = Console.ReadLine();
             *
             *              Console.WriteLine("Do you wish to apply any filters? y/n");
             *              string a = Console.ReadLine();
             *
             *              if (a == "y")
             *              {
             *                  Console.WriteLine("Please choose one or more of the following filters:");
             *                  Console.WriteLine("For songs:");
             *                  Console.WriteLine("1) Name");
             *                  Console.WriteLine("2) Artist");
             *                  Console.WriteLine("3) Album");
             *                  Console.WriteLine("4) Genre");
             *                  Console.WriteLine("");
             *                  Console.WriteLine("For videos:");
             *                  Console.WriteLine("5) Name");
             *                  Console.WriteLine("6) Creator");
             *                  Console.WriteLine("7) Genre");
             *                  Console.WriteLine("8) Category");
             *                  Console.WriteLine("9) Director");
             *                  Console.WriteLine("10) Studio");
             *
             *                  Console.WriteLine("Please type the numbers next to the desired filters");
             *                  List<int> FilterList = new List<int>();
             *
             *                  string b1 = "y";
             *
             *                  while (b1 == "y")
             *                  {
             *                      Console.WriteLine("Filter:");
             *
             *                      int f1 = Convert.ToInt32(Console.ReadLine());
             *                      FilterList.Add(f1);
             *
             *                      Console.WriteLine("Do you wish to add another filter? y/n");
             *                      b1 = Console.ReadLine();
             *
             *                      if (FilterList.Count >= 9) //Security measure, so that nobody can write filters forever.
             *                      {
             *                          b1 = "n";
             *                      }
             *                  }
             *
             *                  Filter f2 = new Filter();
             *
             *                  foreach(object o in f2.FilteredSearch(FilterList, a))
             *                  {
             *                      Console.WriteLine(o);
             *                  }
             *              }
             *
             *
             *              else if (a == "n")
             *              {
             *                  Filter f2 = new Filter();
             *
             *                  foreach(object o in f2.Search(a))
             *                  {
             *                      Console.WriteLine(o);
             *                  }
             *              }
             *
             *
             *              Console.WriteLine("What do you want to search for?");
             *              string a1 = Console.ReadLine();
             *
             *              Filter f = new Filter();
             *              List<object> filtered = f.Search(a1);
             *
             *              foreach (object o in filtered)
             *              {
             *                  Console.WriteLine(o);
             *              }
             *          }
             *
             *
             *          else if (Ans == "B" || Ans == "b")
             *          {
             *              User u = Spotflix.GetUserDB[userN];
             *              Console.WriteLine("Do you wish to:");
             *              Console.WriteLine("A) Access your existing playlists?");
             *              Console.WriteLine("B) Create a new one?");
             *              string a1 = Console.ReadLine();
             *
             *              if (a1 == "A" || a1 == "a")
             *              {
             *                  foreach(Playlist p in u.GetPlaylist())
             *                  {
             *                      Console.WriteLine(p);
             *                  }
             *
             *              }
             *
             *              else if(a1 == "B" || a1 == "b")
             *              {
             *                  u.NewPlaylist();
             *              }
             *
             *              else
             *              {
             *                  Console.WriteLine("Invalid answer");
             *              }
             *
             *          }
             *
             *          else if (Ans == "C" || Ans == "c")
             *          {
             *              Console.WriteLine("Please state the name of the user you are looking for");
             *              string userSearch = Console.ReadLine();
             *              User u2 = Spotflix.GetUserDB[userSearch];
             *
             *              try
             *              {
             *                  u2 = Spotflix.GetUserDB[userSearch];
             *
             *              }
             *
             *              catch(Exception e)
             *              {
             *                  Console.WriteLine("User not found");
             *                  Console.WriteLine(e.Message);
             *              }
             *
             *              Console.WriteLine("Here's the public info in the account");
             *              Console.WriteLine(" ");
             *
             *              Console.WriteLine("Account name: ");
             *              Console.Write(u2.GetUsername());
             *              Console.WriteLine(" ");
             *
             *              Console.WriteLine("List of playlists: ");
             *              Console.Write(u2.GetPlaylist());
             *              Console.WriteLine(" ");
             *
             *              Console.WriteLine("List of people who follow this account: ");
             *              Console.Write(u2.GetFollowers());
             *              Console.WriteLine(" ");
             *
             *              Console.WriteLine("List of people that this account follows: ");
             *              Console.WriteLine(u2.GetFollowing());
             *              Console.WriteLine(" ");
             *          }
             *
             *          else
             *          {
             *              Console.WriteLine("Invalid Answer");
             *          }
             *
             *      }
             *
             *
             *      else
             *      {
             *          Console.WriteLine("Wrong password");
             *      }
             *  }
             *
             *
             *  else
             *  {
             *      Console.WriteLine("User not found");
             *  }
             *
             * }
             *
             */
        }
Beispiel #14
0
 public void RegexUtilities_ValidateEmailForTextContainingSpace()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail("abc [email protected]"));
 }
Beispiel #15
0
 public void RegexUtilities_IsValidEmail()
 {
     Assert.IsTrue(RegexUtilities.IsValidEmail("*****@*****.**"));
 }
Beispiel #16
0
 public void RegexUtilities_ValidateEmailForMultipleDots()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail(".abcgmail.com@"));
 }
Beispiel #17
0
 //[ValidateAntiForgeryToken]
 public async Task<ActionResult> Register(RegisterViewModel model)
 {
     if (ModelState.IsValid)
     {
         RegexUtilities emailcheck = new RegexUtilities();
         string email = model.Email;
         var user = new ApplicationUser();
         if (emailcheck.IsValidEmail(email)) // Checks whether email is valid in order to fix an error we had
         {
             user = new ApplicationUser()
             {
                 UserName = model.Email,
                 Email = model.Email,
                 FirstName = model.FirstName,
                 LastName = model.LastName,
                 Institution = model.Institution,
                 Type = ApplicationUser.AccountType.Free,
                 Status = ApplicationUser.AccountStatus.Active
             };
         }
         else
         {
             user = new ApplicationUser()
             {
                 UserName = "******",//sets up a dummy model so it doesn't crash before showing validation message and error to user
                 Email = model.Email,
                 FirstName = model.FirstName,
                 LastName = model.LastName,
                 Institution = model.Institution,
                 Type = ApplicationUser.AccountType.Free,
                 Status = ApplicationUser.AccountStatus.Active
             };
         }
         IdentityResult result = await UserManager.CreateAsync(user, model.Password);
         if (result.Succeeded)
         {
             UserManager.AddToRole(user.Id, "Learner");
             ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                 + "before you can log in.";
             return RedirectToAction("Index", "Home");
         }
         else
         {
             AddErrors(result);
             RedirectToAction("Index", "Profile");
         }
     }
     // If we got this far, something failed, redisplay form
     return View(model);
 }
        private async void Save()
        {
            if (string.IsNullOrEmpty(this.profileEmail.Name))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LastNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.profileEmail.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation,
                    Languages.Accept);

                return;
            }

            if (!RegexUtilities.IsValidEmail(this.profileEmail.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation2,
                    Languages.Accept);

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var checkConnetion = await this.apiService.CheckConnection();

            if (!checkConnetion.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    checkConnetion.Message,
                    Languages.Accept);

                return;
            }

            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            var profile     = await this.apiService.PutProfile(
                apiSecurity,
                "/api",
                "/ProfileEmails/PutProfileEmail",
                profileEmail);

            this.IsRunning = false;
            this.IsEnabled = true;

            //Agregar a la lista
            MainViewModel.GetInstance().ProfilesByEmail.updateProfile(profile);
            await App.Navigator.PopAsync();
        }
        private bool CheckExcelSheet(string FileName, DataTable dt)
        {
            bool isValidExcelSheet = true;
            try
            {
                #region local variables for processing

                string StudentName = "";
                string LastName = "";
                string FatherName = "";
                string MotherName = "";
                DateTime DateOfBirth;
                int Semester;
                string Branch = "";
                string Section = "";
                string RollNo = "";
                string ParentsMobileNo = "";
                string StudentAddress = "";
                string Gender = "";
                string ParentsEmail = "";

                #endregion

                string path = string.Concat(Server.MapPath("~/Documents/" + FileName));

                FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);
                IExcelDataReader excelReader;

                switch (Path.GetExtension(path).ToLower())
                {
                    case ".xls":
                        //1. Reading from a binary Excel file ('97-2003 format; *.xls)
                        excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
                        break;
                    //...
                    case ".xlsx":
                        //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
                        excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                        break;
                    //...
                    default:
                        return false;
                }
                //3. DataSet - Create column names from first row
                excelReader.IsFirstRowAsColumnNames = true;
                DataSet result = excelReader.AsDataSet();

                //5. Data Reader methods

                for (int i = 0; i < result.Tables[0].Rows.Count; i++)
                {
                    //excelReader.GetInt32(0);
                    try
                    {
                        StudentName = valid(result.Tables[0].Rows[i], 0);
                        LastName = valid(result.Tables[0].Rows[i], 1);
                        FatherName = valid(result.Tables[0].Rows[i], 2);
                        MotherName = valid(result.Tables[0].Rows[i], 3);
                        DateOfBirth = DateTime.Parse(valid(result.Tables[0].Rows[i], 4));

                        if (Session["InstituteType"].ToString() == "S")
                        {
                            Semester = 0;
                        }
                        else
                        {
                            Semester = int.Parse(valid(result.Tables[0].Rows[i], 5));
                        }

                        Branch = valid(result.Tables[0].Rows[i], 6);
                        Section = valid(result.Tables[0].Rows[i], 7);
                        RollNo = valid(result.Tables[0].Rows[i], 8);
                        ParentsMobileNo = valid(result.Tables[0].Rows[i], 9);
                        StudentAddress = valid(result.Tables[0].Rows[i], 10);
                        Gender = valid(result.Tables[0].Rows[i], 11);
                        ParentsEmail = valid(result.Tables[0].Rows[i], 12);

                        if (excelReader[0] == DBNull.Value)
                            break;
                        string BranchId = new BOStudentRegistration().GetBranchId(valid(result.Tables[0].Rows[i], 6));
                        if (BranchId == string.Empty)
                        {
                            //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='Invalid Branch Name found in Branch column!!; it should be number!!';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true);
                            string alertScript = "jAlert('Invalid Branch Name found in Branch column', 'Campus2Caretaker');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                            return false;
                        }

                        int intvalue;
                        if (!int.TryParse(Semester.ToString(), out intvalue))
                        {
                            //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='Invalid Semester Id found in Semester column!!; it should be numeric!!';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true); isValidExcelSheet = false;
                            string alertScript = "jAlert('Invalid Semester Id found in Semester column', 'Campus2Caretaker');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                            isValidExcelSheet = false;
                            break;
                        }

                        DateTime dateTimeValue;
                        if (!DateTime.TryParse(DateOfBirth.ToString(), out dateTimeValue))
                        {
                            //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='Invalid DOB found in DOB column!!; it should be numeric!!';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true);
                            string alertScript = "jAlert('Invalid DOB found in DOB column', 'Campus2Caretaker');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                            isValidExcelSheet = false;
                            break;
                        }

                        string genderValue = valid(result.Tables[0].Rows[i], 11);
                        if (genderValue == string.Empty || (genderValue != "Male" && genderValue != "Female"))
                        {
                            //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='Invalid Gender found in Gender column!!; it should be Male or Female!!';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true);
                            string alertScript = "jAlert('Invalid Gender found in Gender column', 'Campus2Caretaker');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                            return false;
                        }

                        string parentsEmailValue = valid(result.Tables[0].Rows[i], 12);
                        RegexUtilities util = new RegexUtilities();
                        if (parentsEmailValue != string.Empty)
                        {
                            if (!util.IsValidEmail(parentsEmailValue))
                            {
                                //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='Invalid email found in parents email column!!';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                                //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true);
                                string alertScript = "jAlert('Invalid email found in parents email column', 'Campus2Caretaker');";
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                                return false;
                            }
                        }
                        //Here using this method we are inserting the data into a temporary DataTable
                        dt.Rows.Add(StudentName, LastName, FatherName, MotherName, DateOfBirth, Semester, BranchId, Section, RollNo, ParentsMobileNo, StudentAddress, Gender, ParentsEmail);
                    }

                    catch (Exception err)
                    {
                        //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='Invalid data found in uploaded excel!!';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                        //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true); isValidExcelSheet = false;
                        string alertScript = "jAlert('Invalid data found in uploaded excel', 'Campus2Caretaker');";
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                        isValidExcelSheet = false;
                        break;
                    }
                }
                //6. Free resources (IExcelDataReader is IDisposable)
                excelReader.Close();

            }
            catch (DataException ee)
            {
                //string script = @"document.getElementById('" + dvUploadStatus.ClientID + "').innerHTML='" + ee.Message + "';var elem = document.createElement('img');elem.setAttribute('src', 'cross.jpg');document.getElementById('" + dvUploadStatus.ClientID + "').appendChild(elem);document.getElementById('" + dvUploadStatus.ClientID + "').style.color = 'Red';document.getElementById('" + dvUploadStatus.ClientID + "').style.fontSize = '1em' ;document.getElementById('" + dvUploadStatus.ClientID + "').style.fontWeight = 'bold' ;setTimeout(function(){document.getElementById('" + dvUploadStatus.ClientID + "').style.display='none';},4500);";
                //ScriptManager.RegisterStartupScript(this, this.GetType(), "script", script, true);
                string alertScript = "jAlert('"+ ee.Message +"', 'Campus2Caretaker');";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertScript", alertScript, true);
                isValidExcelSheet = false;
            }
            finally
            {

            }

            return isValidExcelSheet;
        }
        private async void SaveProfileSpotify()
        {
            if (string.IsNullOrEmpty(this.Name))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.NameValidation,
                    Languages.Accept);

                return;
            }
            if (string.IsNullOrEmpty(this.Link))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LinkValidation,
                    Languages.Accept);

                return;
            }
            if (!RegexUtilities.IsValidURL(this.Link))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LinkValidation,
                    Languages.Accept);

                return;
            }
            this.IsRunning = true;
            this.IsEnabled = false;

            var checkConnetion = await this.apiService.CheckConnection();

            if (!checkConnetion.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    checkConnetion.Message,
                    Languages.Accept);

                return;
            }

            var mainViewModel = MainViewModel.GetInstance();

            var profileSpotify = new ProfileSM
            {
                ProfileName = this.Name,
                link        = this.Link,
                UserId      = mainViewModel.User.UserId,
                Exist       = false,
                RedSocialId = 8
            };

            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            var profileSM   = await this.apiService.Post(
                apiSecurity,
                "/api",
                "/ProfileSMs",
                profileSpotify);

            if (profileSM == default)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.ErrorAddProfile,
                    Languages.Accept);

                return;
            }
            var ProfileLocal = new Profile
            {
                UserId      = mainViewModel.User.UserId,
                ProfileName = profileSM.ProfileName,
                value       = profileSM.link,
                ProfileType = "Spotify",
                Logo        = "spotify2",
                ProfileId   = profileSM.ProfileMSId,
            };

            using (var conn = new SQLite.SQLiteConnection(App.root_db))
            {
                conn.CreateTable <Profile>();
                conn.Insert(ProfileLocal);
            }
            this.IsRunning = false;
            this.IsEnabled = true;

            //Agregar a la lista
            if (mainViewModel.ProfilesBYPESM != null)
            {
                mainViewModel.ProfilesBYPESM.addProfileSM(profileSM);
                mainViewModel.ListOfNetworks.addProfileSM(profileSM);
            }
            else
            {
                mainViewModel.ProfilesBySpotify.addProfile(profileSM);
            }


            this.Name = string.Empty;
            this.Link = string.Empty;

            if (mainViewModel.ProfilesBYPESM != null)
            {
                await PopupNavigation.Instance.PopAsync();
            }
            else
            {
                await App.Navigator.PopAsync();
            }
        }
Beispiel #21
0
        async void Save()
        {
            if (string.IsNullOrEmpty(FirstName))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter a first name.");

                return;
            }

            if (string.IsNullOrEmpty(LastName))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter a last name.");

                return;
            }

            if (string.IsNullOrEmpty(Email))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter a email.");

                return;
            }

            if (!RegexUtilities.IsValidEmail(Email))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter a valid email.");

                return;
            }

            if (string.IsNullOrEmpty(Password))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter a password.");

                return;
            }

            if (Password.Length < 6)
            {
                await dialogService.ShowMessage(
                    "Error",
                    "The password must have at least 6 characters length.");

                return;
            }

            if (string.IsNullOrEmpty(Confirm))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "You must enter a password confirm.");

                return;
            }

            if (!Password.Equals(Confirm))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "The password and confirm, does not match.");

                return;
            }

            IsRunning = true;
            IsEnabled = false;

            var connection = await apiService.CheckConnection();

            if (!connection.IsSuccess)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage("Error", connection.Message);

                return;
            }

            var urlAPI   = Application.Current.Resources["URLAPI"].ToString();
            var customer = new Customer
            {
                Address      = Address,
                CustomerType = 1,
                Email        = Email,
                FirstName    = FirstName,
                LastName     = LastName,
                Password     = Password,
                Phone        = Phone,
            };

            var response = await apiService.Post(
                urlAPI,
                "/api",
                "/Customers",
                customer);

            if (!response.IsSuccess)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage(
                    "Error",
                    response.Message);

                return;
            }

            var response2 = await apiService.GetToken(
                urlAPI,
                Email,
                Password);

            if (response2 == null)
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage(
                    "Error",
                    "The service is not available, please try latter.");

                Password = null;
                return;
            }

            if (string.IsNullOrEmpty(response2.AccessToken))
            {
                IsRunning = false;
                IsEnabled = true;
                await dialogService.ShowMessage(
                    "Error",
                    response2.ErrorDescription);

                Password = null;
                return;
            }

            var mainViewModel = MainViewModel.GetInstance();

            mainViewModel.Token = response2;
            mainViewModel.RegisterDevice();
            mainViewModel.Categories = new CategoriesViewModel();
            await navigationService.BackOnLogin();

            navigationService.SetMainPage("MasterView");

            IsRunning = false;
            IsEnabled = true;
        }
        private async void CambiarPassword()
        {
            if (string.IsNullOrEmpty(this.ActualPassword))
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Introduzca su Contraseña.",
                    "Aceptar");

                return;
            }

            if (this.ActualPassword.Length < 8 ||
                this.ActualPassword.Length > 20)
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "La Contraseña debe tener entre 8 y 20 caracteres.",
                    "Aceptar");

                return;
            }

            if (!RegexUtilities.ValidarPassword(this.ActualPassword))
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Las contraseñas deben tener al menos un carácter que no sea una letra ni un dígito, " +
                    "al menos una letra en minúscula ('a'-'z') y al menos una letra en mayúscula ('A'-'Z').",
                    "Aceptar");

                return;
            }

            if (this.ActualPassword != MainViewModel.GetInstance().Componente.Password)
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "La contraseña actual es incorrecta.",
                    "Aceptar");

                return;
            }

            if (string.IsNullOrEmpty(this.NuevoPassword))
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Introduzca su nueva Contraseña.",
                    "Aceptar");

                return;
            }

            if (this.NuevoPassword.Length < 8 ||
                this.NuevoPassword.Length > 20)
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "La nueva Contraseña debe tener entre 8 y 20 caracteres.",
                    "Aceptar");

                return;
            }

            if (!RegexUtilities.ValidarPassword(this.NuevoPassword))
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Las contraseñas deben tener al menos un carácter que no sea una letra ni un dígito, " +
                    "al menos una letra en minúscula ('a'-'z') y al menos una letra en mayúscula ('A'-'Z').",
                    "Aceptar");

                return;
            }

            if (this.NuevoPassword != this.Confirmacion)
            {
                this.IsRunning = false;
                this.IsEnabled = true;

                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "La nueva Contraseña y la confirmación no coinciden.",
                    "Aceptar");

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var connection = await this.apiService.CheckConnection();

            if (!connection.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    connection.Message,
                    "Aceptar");

                return;
            }

            var request = new CambiarPasswordRequest
            {
                ActualPassword = this.ActualPassword,
                Email          = MainViewModel.GetInstance().Componente.Email,
                NuevoPassword  = this.NuevoPassword,
            };

            var apiBase  = Application.Current.Resources["APIBase"].ToString();
            var response = await this.apiService.CambiarPassword(
                apiBase,
                "/api",
                "/Componentes/CambiarPassword",
                MainViewModel.GetInstance().Token.TokenType,
                MainViewModel.GetInstance().Token.AccessToken,
                request);

            if (!response.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "No se pudo cambiar la contraseña. Intentalo más tarde.",
                    "Aceptar");

                return;
            }

            MainViewModel.GetInstance().Componente.Password = this.NuevoPassword;
            this.dataService.Update(MainViewModel.GetInstance().Componente);

            this.IsRunning = false;
            this.IsEnabled = true;

            await Application.Current.MainPage.DisplayAlert(
                "Confirmación",
                "Contraseña modificada correctamente.",
                "Aceptar");

            await App.Navigator.PopAsync();
        }
Beispiel #23
0
        public async void Editar()
        {
            //Variable para la validacion de campos numericos
            int num = 0;

            //Obtener las imagenes del XAML
            var imageFotoPerfil          = this.FotoSource as FileImageSource;
            var imageCredencialFrontal   = this.CredencialFrontalSource as FileImageSource;
            var imageCredencialPosterior = this.CredencialPosteriorSource as FileImageSource;

            //Obtencion de las rutas de las imagenes de XAML
            string fotoRuta        = string.Empty;
            string credencialFRuta = string.Empty;
            string credencialPRuta = string.Empty;

            //Verificaciones de las cadenas de ruta de imagenes de XAML
            if (imageFotoPerfil == null)
            {
                fotoRuta = "0";
            }
            else
            {
                fotoRuta = "no_image";
            }

            if (imageCredencialFrontal == null)
            {
                credencialFRuta = "0";
            }
            else
            {
                credencialFRuta = "no_image";
            }

            if (imageCredencialPosterior == null)
            {
                credencialPRuta = "0";
            }
            else
            {
                credencialPRuta = "no_image";
            }

            //Validaciones
            //Validacion de Imagen de foto de perfil
            if (fotoRuta.Equals("no_image"))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Se necesita una foto de perfil",
                    "Aceptar");
            }
            //Validaciones de campos vacios
            else if (this.Nombre.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Nombre Vacío",
                    "Aceptar");
            }
            else if (this.ApellidoPat.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Apellido Paterno Vacío",
                    "Aceptar");
            }
            else if (this.ApellidoMat.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Apellido Materno Vacío",
                    "Aceptar");
            }
            else if (this.SexoSelected.Equals(this.Sexos.ElementAt(0)))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Sexo Vacío",
                    "Aceptar");
            }
            else if (this.Edad.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Edad Vacío",
                    "Aceptar");
            }
            //Validacion de campo numerico
            else if (!Int32.TryParse(this.Edad, out num))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo edad no es númerico",
                    "Aceptar");
            }
            else if (this.EstadoCivilSelected.Equals(this.EstadosCiviles.ElementAt(0)))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Estado Civil Vacío",
                    "Aceptar");
            }
            else if (this.Municipio.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Municipio Vacío",
                    "Aceptar");
            }
            else if (this.Region.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Región Vacío",
                    "Aceptar");
            }
            else if (!Int32.TryParse(this.Region, out num))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo región no es númerico",
                    "Aceptar");
            }

            /*else if (this.Zona.Equals(string.Empty))
             * {
             *  await Application.Current.MainPage.DisplayAlert(
             *      "ERROR",
             *      "Campo Zona Vacío",
             *      "Aceptar");
             * }
             * else if (!Int32.TryParse(this.Zona, out num))
             * {
             *  await Application.Current.MainPage.DisplayAlert(
             *      "ERROR",
             *      "Campo zona no es númerico",
             *      "Aceptar");
             * }
             * else if (this.Seccion.Equals(string.Empty))
             * {
             *  await Application.Current.MainPage.DisplayAlert(
             *      "ERROR",
             *      "Campo Sección Vacío",
             *      "Aceptar");
             * }
             * else if (!Int32.TryParse(this.Seccion, out num))
             * {
             *  await Application.Current.MainPage.DisplayAlert(
             *      "ERROR",
             *      "Campo sección no es númerico",
             *      "Aceptar");
             * }*/
            else if (this.Casilla.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Casilla Vacío",
                    "Aceptar");
            }
            else if (this.Promotor.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Promotor Vacío",
                    "Aceptar");
            }
            else if (this.Comunidad.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Comunidad Vacío",
                    "Aceptar");
            }
            else if (this.Domicilio.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Domicilio Vacío",
                    "Aceptar");
            }
            else if (this.TelefonoCelular.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Teléfono Celular Vacío",
                    "Aceptar");
            }
            //Validacion de tamaño de la cadena
            else if (!this.TelefonoCelular.Length.Equals(14))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Teléfono Celular Vacío",
                    "Aceptar");
            }
            else if (this.Ocupacion.Equals(this.Ocupaciones.ElementAt(0)))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Ocupación Vacío",
                    "Aceptar");
            }
            else if (this.Escolaridad.Equals(this.Escolaridades.ElementAt(0)))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Escolaridad Vacío",
                    "Aceptar");
            }
            else if (this.Email.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Correo Electrónico Vacío",
                    "Aceptar");
            }
            else if (!RegexUtilities.ComprobarFormatoEmail(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Formato Correo Electrónico Incorrecto",
                    "Aceptar");
            }
            else if (this.NumIne.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Número INE Vacío",
                    "Aceptar");
            }
            else if (!this.NumIne.Length.Equals(13))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    string.Format("Campo Número INE Tiene {0} dígitos y deben ser 13 dígitos", this.NumIne.Length),
                    "Aceptar");
            }
            else if (this.ClaveIne.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo Clave de Elector Vacío",
                    "Aceptar");
            }
            else if (!this.ClaveIne.Length.Equals(18))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    string.Format("Campo Clave de Elector Tiene {0} caracteres y deben ser 18 caracteres", this.ClaveIne.Length),
                    "Aceptar");
            }
            else if (this.Curp.Equals(string.Empty))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Campo CURP Vacío",
                    "Aceptar");
            }
            else if (!this.Curp.Length.Equals(18))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    string.Format("Campo CURP Tiene {0} caracteres y deben ser 18 caracteres", this.Curp.Length),
                    "Aceptar");
            }
            else if (credencialFRuta.Equals("no_image"))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Foto frontal de la credencial es obligatoria",
                    "Aceptar");
            }
            else if (credencialPRuta.Equals("no_image"))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "ERROR",
                    "Foto posterior de la credencial es obligatoria",
                    "Aceptar");
            }
            else
            {
                //Creacion de variables por default
                string id               = Settings.Id;
                byte[] imageArray       = null;
                byte[] credencialFArray = null;
                byte[] credencialPArray = null;

                //Obtener las imagenes del promovido ya en base de datos
                using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
                {
                    var afiliado = conn.Table <Afiliado>().Where(a => a.Id.Equals(id)).FirstOrDefault();
                    imageArray       = afiliado.Foto;
                    credencialFArray = afiliado.CredencialFrontal;
                    credencialPArray = afiliado.CredencialPosterior;
                }

                //convertir las imagenes en tipo byte[]
                if (this.file != null)
                {
                    imageArray = FilesHelper.ReadFully(this.file.GetStream());
                    File.Delete("/storage/emulated/0/Android/data/com.companyname.encuestahorizonte/files/Pictures/fotoPerfilEdit.jpg");
                    if (this.perfilTomado > 1)
                    {
                        for (int i = 1; i < this.perfilTomado; i++)
                        {
                            File.Delete(string.Format("/storage/emulated/0/Android/data/com.companyname.encuestahorizonte/files/Pictures/fotoPerfilEdit_{0}.jpg", i));
                        }
                    }
                    this.file.Dispose();
                    this.file = null;
                }

                if (this.credencialFrontalfile != null)
                {
                    credencialFArray = FilesHelper.ReadFully(this.credencialFrontalfile.GetStream());
                    File.Delete("/storage/emulated/0/Android/data/com.companyname.encuestahorizonte/files/Pictures/testCredencialFEdit.jpg");
                    if (this.frontalTomado > 1)
                    {
                        for (int i = 1; i < this.frontalTomado; i++)
                        {
                            File.Delete(string.Format("/storage/emulated/0/Android/data/com.companyname.encuestahorizonte/files/Pictures/testCredencialFEdit_{0}.jpg", i));
                        }
                    }
                    this.credencialFrontalfile.Dispose();
                    this.credencialFrontalfile = null;
                }

                if (this.credencialPosteriorfile != null)
                {
                    credencialPArray = FilesHelper.ReadFully(this.credencialPosteriorfile.GetStream());
                    File.Delete("/storage/emulated/0/Android/data/com.companyname.encuestahorizonte/files/Pictures/testCredencialPEdit.jpg");
                    if (this.posteriorTomado > 1)
                    {
                        for (int i = 1; i < this.posteriorTomado; i++)
                        {
                            File.Delete(string.Format("/storage/emulated/0/Android/data/com.companyname.encuestahorizonte/files/Pictures/testCredencialPEdit_{0}.jpg", i));
                        }
                    }
                    this.credencialPosteriorfile.Dispose();
                    this.credencialPosteriorfile = null;
                }

                this.perfilTomado    = 0;
                this.frontalTomado   = 0;
                this.posteriorTomado = 0;

                int rows = 0;
                try
                {
                    //Actualizar el afiliado
                    using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
                    {
                        conn.CreateTable <Afiliado>();
                        this.Afiliado = new Afiliado();
                        this.Afiliado = this.helperAfiliado.Llenado(id, this.Municipio, this.Region, this.Zona, this.Seccion, this.Casilla, this.Promotor, this.Comunidad,
                                                                    this.Nombre, this.NombreSegundo, this.ApellidoPat, this.ApellidoMat, this.SexoSelected, this.Edad, this.EstadoCivilSelected, this.Domicilio,
                                                                    this.TelefonoFijo, this.TelefonoCelular, this.TelefonoAlter, this.Ocupacion, this.Escolaridad, this.Email, this.NumIne, this.ClaveIne, this.Curp,
                                                                    this.Facebook, this.Observacion, Settings.IdUsuario, imageArray, credencialFArray, credencialPArray);
                        rows += conn.Update(this.Afiliado);
                    }
                }
                catch (Exception e)
                {
                    //Mensaje de error con la base de datos
                    await Application.Current.MainPage.DisplayAlert(
                        "ERROR",
                        e.Message + "\n\nVolver a intentar",
                        "Aceptar");
                }

                if (rows > 0)
                {
                    await Application.Current.MainPage.DisplayAlert(
                        "EXITO",
                        "Actualización Exitosa",
                        "Aceptar");
                }
                else
                {
                    await Application.Current.MainPage.DisplayAlert(
                        "ERROR",
                        "La Actualización Falló",
                        "Aceptar");
                }
            }
        }
        private void ejecutar()
        {
            RegexUtilities util = new RegexUtilities();

            if (ValidarCamposVacios())
            {
                MessageBox.Show("Debe completar todos los campos");
            }
            else if (ValidarTipoCabinaVacio())
            {
            }
            else if (ValidaPisoNumeroTipo())
            {
                MessageBox.Show("Piso, numero y tipo de cabina repetido");
            }
            else
            {
                if (String.IsNullOrEmpty(this.IDCrucero))
                {
                    //Validar ID
                    if (!CruceroFunc.EsValidoIdCrucero(this.txt_id.Text.Trim()))
                    {
                        MessageBox.Show("La identificación ya existe");
                    }
                    else
                    {
                        //Crear crucero
                        Crucero       crucero = new Crucero();
                        Tipo_Servicio tser    = new Tipo_Servicio();
                        Fabricante    fab     = new Fabricante();
                        ComboboxItem  item    = new ComboboxItem();
                        item            = (ComboboxItem)cmb_fabricante.SelectedItem;
                        fab             = (Fabricante)item.Value;
                        crucero.fab_id  = fab.id;
                        item            = (ComboboxItem)cmb_servicio.SelectedItem;
                        tser            = (Tipo_Servicio)item.Value;
                        crucero.tser_id = tser.id;
                        crucero.mod     = txt_modelo.Text.Trim();
                        crucero.id      = txt_id.Text.Trim();
                        CruceroFunc.CrearCrucero(crucero);

                        for (int l = 0; l < this.dgv_cabinas.Rows.Count - 1; l++)
                        {
                            Cabinas_Crucero cabinaCrucero = new Cabinas_Crucero();
                            cabinaCrucero.cru_id  = txt_id.Text.Trim();
                            cabinaCrucero.piso    = Convert.ToInt32(dgv_cabinas.Rows[l].Cells["colPiso"].Value);
                            cabinaCrucero.numero  = Convert.ToInt32(dgv_cabinas.Rows[l].Cells["colNumero"].Value);
                            cabinaCrucero.tcab_id = Cabina_crucerofunc.ObtenerIDTipo(Convert.ToString(dgv_cabinas.Rows[l].Cells["colTipoCabina"].Value));
                            Cabina_crucerofunc.CrearCabinaCrucero(cabinaCrucero);
                        }

                        MessageBox.Show("Crucero creado");
                        this.Close();
                    }
                }
                else
                {
                    //Modificar crucero
                    Crucero       crucero = new Crucero();
                    Tipo_Servicio tser    = new Tipo_Servicio();
                    Fabricante    fab     = new Fabricante();
                    ComboboxItem  item    = new ComboboxItem();
                    item            = (ComboboxItem)cmb_fabricante.SelectedItem;
                    fab             = (Fabricante)item.Value;
                    crucero.fab_id  = fab.id;
                    item            = (ComboboxItem)cmb_servicio.SelectedItem;
                    tser            = (Tipo_Servicio)item.Value;
                    crucero.tser_id = tser.id;
                    crucero.mod     = txt_modelo.Text.Trim();
                    crucero.id      = txt_id.Text.Trim();

                    CruceroFunc.ModificarCrucero(crucero);

                    //Cabinas del crucero
                    for (int l = 0; l < this.cantCabinas; l++)
                    {
                        Cabinas_Crucero cabinaCrucero = new Cabinas_Crucero();
                        cabinaCrucero.cru_id  = txt_id.Text.Trim();
                        cabinaCrucero.piso    = Convert.ToInt32(dgv_cabinas.Rows[l].Cells["colPiso"].Value);
                        cabinaCrucero.numero  = Convert.ToInt32(dgv_cabinas.Rows[l].Cells["colNumero"].Value);
                        cabinaCrucero.tcab_id = Cabina_crucerofunc.ObtenerIDTipo(Convert.ToString(dgv_cabinas.Rows[l].Cells["colTipoCabina"].Value));
                        cabinaCrucero.id      = Convert.ToInt32(dgv_cabinas.Rows[l].Cells["ColId"].Value);
                        Cabina_crucerofunc.ModificarCabinaCrucero(cabinaCrucero);
                    }
                    for (int l2 = this.cantCabinas; l2 < this.dgv_cabinas.Rows.Count - 1; l2++)
                    {
                        Cabinas_Crucero cabinaCrucero = new Cabinas_Crucero();
                        cabinaCrucero.cru_id  = txt_id.Text.Trim();
                        cabinaCrucero.piso    = Convert.ToInt32(dgv_cabinas.Rows[l2].Cells["colPiso"].Value);
                        cabinaCrucero.numero  = Convert.ToInt32(dgv_cabinas.Rows[l2].Cells["colNumero"].Value);
                        cabinaCrucero.tcab_id = Cabina_crucerofunc.ObtenerIDTipo(Convert.ToString(dgv_cabinas.Rows[l2].Cells["colTipoCabina"].Value));
                        Cabina_crucerofunc.ModificarCabinaCrucero(cabinaCrucero);
                    }

                    MessageBox.Show("Crucero modificado");
                    this.Close();
                }
            }
        }
Beispiel #25
0
        public async Task <IActionResult> ImportProjectsFromExcel(ImportProjectsFromExcelViewModel viewModel)
        {
            #region Validate ViewModel
            ViewBag.SemesterId = new SelectList(await _context.Semesters.OrderByDescending(s => s.StartedDate).ToListAsync(), "Id", "Name", viewModel.SemesterId);
            if (!ModelState.IsValid)
            {
                return(View(viewModel));
            }

            if (!FormFileValidation.IsValidFileSizeLimit(viewModel.File, 268435456)) // 256 MiB
            {
                ModelState.AddModelError("File", _localizer["File size not greater than or equals 256 MiB."]);
                return(View(viewModel));
            }

            var fileExtension = FormFileValidation.GetFileExtension(viewModel.File.FileName).ToLower();
            if (!FormFileValidation.IsValidExcelFileExtension(fileExtension))
            {
                ModelState.AddModelError("File", _localizer["Invalid file extension(.xls, .xlsx)."]);
                return(View(viewModel));
            }
            #endregion

            //set sheet
            ISheet sheet;
            using (var stream = new MemoryStream())
            {
                viewModel.File.CopyTo(stream);
                stream.Position = 0;
                if (fileExtension == ".xls")
                {
                    HSSFWorkbook workbook = new HSSFWorkbook(stream);
                    sheet = workbook.GetSheetAt(0);
                }
                else
                {
                    XSSFWorkbook workbook = new XSSFWorkbook(stream);
                    sheet = workbook.GetSheetAt(0);
                }
            }

            #region Read Sheet
            var projects         = new List <Project>();
            var newStudents      = new List <ApplicationUser>();
            var newLecturers     = new List <ApplicationUser>();
            var regexStudentCode = new Regex(@"^\d{10}$");

            var rowIndex = sheet.FirstRowNum + 1;
            while (rowIndex <= sheet.LastRowNum)
            {
                IRow row = sheet.GetRow(rowIndex);


                rowIndex = getMegreRowLastRowIndex(sheet, rowIndex) + 1;
                if (row == null || row.Cells.All(d => d.CellType == CellType.Blank))
                {
                    continue;
                }

                //check unique project
                var uniqueId = row.GetCell(0).ToString();
                if (_context.Projects.Any(p => p.UniqueId == uniqueId))
                {
                    continue;
                }

                //Init project
                var project = new Project
                {
                    UniqueId      = uniqueId,
                    ProjectTypeId = short.Parse(row.GetCell(1).ToString()),
                    Title         = row.GetCell(2)?.ToString(),
                    Description   = row.GetCell(3)?.ToString(),
                    FacultyId     = short.Parse(row.GetCell(4).ToString()),
                    SemesterId    = viewModel.SemesterId
                };

                //Add members to project
                project.ProjectMembers = new List <ProjectMember>();
                for (int localRowIndex = row.RowNum; localRowIndex < rowIndex; localRowIndex++)
                {
                    IRow localRow = sheet.GetRow(localRowIndex);

                    var studentCode = localRow.GetCell(5)?.ToString();
                    if (!string.IsNullOrWhiteSpace(studentCode) && regexStudentCode.IsMatch(studentCode))
                    {
                        var user = newStudents.FirstOrDefault(u => u.UserName == studentCode) ?? await _userManager.FindByNameAsync(studentCode);

                        if (user == null)
                        {
                            user = new ApplicationUser
                            {
                                UserName = studentCode,
                                Student  = new Student
                                {
                                    ClassName   = localRow.GetCell(6)?.ToString(),
                                    StudentCode = studentCode,
                                },
                                LastName    = localRow.GetCell(7)?.ToString(),
                                FirstName   = localRow.GetCell(8)?.ToString(),
                                Email       = localRow.GetCell(9)?.ToString(),
                                PhoneNumber = localRow.GetCell(10)?.ToString(),
                            };
                            if (RegexUtilities.IsValidEmail(user.Email))
                            {
                                user.EmailConfirmed = true;
                            }
                            else
                            {
                                user.Email = $"student{user.UserName}@myweb.com";
                            }
                            newStudents.Add(user);
                        }
                        project.ProjectMembers.Add(new ProjectMember
                        {
                            StudentId = user.Id,
                            Type      = (ProjectMemberType)byte.Parse(localRow.GetCell(11)?.ToString() ?? "0")
                        });
                    }
                }

                //Add lecturers to project
                project.ProjectLecturers = new List <ProjectLecturer>();
                for (int localRowIndex = row.RowNum; localRowIndex < rowIndex; localRowIndex++)
                {
                    IRow localRow = sheet.GetRow(localRowIndex);

                    var lecturerCode = localRow.GetCell(12)?.ToString();
                    if (!string.IsNullOrWhiteSpace(lecturerCode))
                    {
                        var user = newLecturers.FirstOrDefault(u => u.UserName == lecturerCode) ?? await _userManager.FindByNameAsync(lecturerCode);

                        if (user == null)
                        {
                            user = new ApplicationUser
                            {
                                UserName = lecturerCode,
                                Lecturer = new Lecturer
                                {
                                    LecturerCode = lecturerCode,
                                },
                                LastName    = localRow.GetCell(13)?.ToString(),
                                FirstName   = localRow.GetCell(14)?.ToString(),
                                Email       = localRow.GetCell(15)?.ToString(),
                                PhoneNumber = localRow.GetCell(16)?.ToString(),
                            };
                            if (RegexUtilities.IsValidEmail(user.Email))
                            {
                                user.EmailConfirmed = true;
                            }
                            else
                            {
                                user.Email = $"lecturer{user.UserName}@myweb.com";
                            }
                            newLecturers.Add(user);
                        }
                        project.ProjectLecturers.Add(new ProjectLecturer
                        {
                            LecturerId = user.Id,
                            Type       = (ProjectLecturerType)byte.Parse(localRow.GetCell(17)?.ToString() ?? "0")
                        });
                    }
                }

                //Add weeks schedule
                var schedules   = new List <ProjectSchedule>();
                var startedDate = new DateTime(viewModel.StartedDate.Value.Year, viewModel.StartedDate.Value.Month, viewModel.StartedDate.Value.Day);
                if (!int.TryParse(row.GetCell(18)?.ToString(), out int weeks))
                {
                    weeks = 10;
                }
                for (int i = 1; i <= weeks; i++)
                {
                    var expiredDate = startedDate.AddDays(7);
                    schedules.Add(new ProjectSchedule
                    {
                        Name        = $"Tuần {i}",
                        StartedDate = startedDate,
                        ExpiredDate = expiredDate
                    });
                    startedDate = expiredDate;
                }
                schedules.Reverse();
                project.ProjectSchedules = schedules;
                projects.Add(project);
            }
            #endregion

            #region Insert To Database
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var user in newStudents)
                    {
                        var result = await _userManager.CreateAsync(user, user.UserName);

                        if (result.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "Student");
                        }
                    }

                    foreach (var user in newLecturers)
                    {
                        var result = await _userManager.CreateAsync(user, user.UserName);

                        if (result.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "Lecturer");
                        }
                    }

                    await _context.Projects.AddRangeAsync(projects);

                    await _context.SaveChangesAsync();

                    await transaction.CommitAsync();
                }
                catch (TransactionException ex)
                {
                    _logger.LogError(ex.Message);
                    await transaction.RollbackAsync();

                    ModelState.AddModelError(string.Empty, _localizer["Someone import file as same time with you. Try it later."]);
                    return(View());
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    await transaction.RollbackAsync();

                    ModelState.AddModelError(string.Empty, _localizer["Error {0}.", ex.Message]);
                    return(View());
                }
            }
            #endregion
            return(RedirectToAction(nameof(Index)));
        }
Beispiel #26
0
        public async Task <IActionResult> Update(string field, string value)
        {
            Console.WriteLine(field);
            Console.WriteLine(value);
            var username = User?.Identity.Name;
            var user     = await UserMgr.FindByNameAsync(username);

            if (field == "firstName")
            {
                user.FirstName = value;
            }
            else if (field == "lastName")
            {
                user.LastName = value;
            }
            else if (field == "newPassword")
            {
                await UserMgr.RemovePasswordAsync(user);

                await UserMgr.AddPasswordAsync(user, value);
            }
            else if (field == "newEmail")
            {
                Console.WriteLine(RegexUtilities.IsValidEmail(value));
                if (RegexUtilities.IsValidEmail(value))
                {
                    var checkEmail = await UserMgr.FindByEmailAsync(value);

                    if (checkEmail == null)
                    {
                        await UserMgr.SetEmailAsync(user, value);

                        var newUser = await UserMgr.FindByEmailAsync(value);

                        await SignInMgr.SignOutAsync();

                        await SignInMgr.SignInAsync(newUser, true);

                        user = newUser;
                    }
                    else
                    {
                        return(Ok("Email exists"));
                    }
                }
                else
                {
                    return(Ok("Email invalid"));
                }
            }

            IdentityResult result = await UserMgr.UpdateAsync(user);

            Console.WriteLine(result.Succeeded + "<----");
            if (result.Succeeded)
            {
                var userToSend = new UserModel();
                userToSend.FirstName = user.FirstName;
                userToSend.LastName  = user.LastName;
                userToSend.UserName  = user.NormalizedEmail;
                return(Ok(userToSend));
            }
            return(Ok("Accout update failed"));
        }
Beispiel #27
0
        async void Login()
        {
            if (string.IsNullOrEmpty(Email))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe ingresar un correo electrónico");

                return;
            }

            if (!RegexUtilities.IsValidEmail(Email))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debe ingresar un Correo válido.");

                return;
            }

            if (string.IsNullOrEmpty(Password))
            {
                await dialogService.ShowMessage(
                    "Error",
                    "Debes ingresar una contraseña");

                return;
            }

            IsRunning         = true;
            IsEnabled         = false;
            IsEnabledRegister = false;

            var connection = await apiService.CheckConnection();

            if (!connection.IsSuccess)
            {
                IsRunning         = false;
                IsEnabled         = true;
                IsEnabledRegister = true;
                await dialogService.ShowMessage("Error", connection.Message);

                return;
            }

            var urlAPI = Application.Current.Resources["URLAPI"].ToString();

            var response = await apiService.GetBy <Usuario>(
                urlAPI,
                "/api",
                "/Usuarios",
                Email);

            if (!response.IsSuccess)
            {
                IsRunning         = false;
                IsEnabled         = true;
                IsEnabledRegister = true;
                await dialogService.ShowMessage(
                    "Error",
                    "Usuario o contraseña incorrecta");

                Password = null;
                return;
            }

            var usuario = (Usuario)response.Result;

            if (Password != usuario.Password)
            {
                IsRunning         = false;
                IsEnabled         = true;
                IsEnabledRegister = true;
                await dialogService.ShowMessage(
                    "Error",
                    "Usuario o contraseña incorrecta");

                Password = null;
                return;
            }

            Email    = null;
            Password = null;

            IsRunning         = false;
            IsEnabled         = true;
            IsEnabledRegister = true;

            var mainViewModel = MainViewModel.GetInstance();

            mainViewModel.Usuario     = usuario;
            mainViewModel.Vehiculos   = mainViewModel.Usuario.Vehiculos;
            mainViewModel.MisReservas = mainViewModel.Usuario.Reservas;
            //mainViewModel.Permisos =  (List<Permiso>) otherResponse.Result;
            mainViewModel.LoadMenu(usuario.Permisos);

            mainViewModel.Perfil = new PerfilViewModel(mainViewModel.Usuario);
            //mainViewModel.Carros = new VehiculoViewModel(mainViewModel.Vehiculos);
            //mainViewModel.Reservas = new ReservaViewModel(mainViewModel.MisReservas);
            navigationService.SetMainPage("MasterView");
        }
        private bool ValidateAll()
        {
            if (string.IsNullOrEmpty(NewEmployee.FirstName) || NewEmployee.FirstName.Length < 2 || NewEmployee.FirstName.Length > 25)
            {
                MessageBox.Show("Voornaam moet 2 tot 25 tekens bevatten");
                return(false);
            }
            if (NewEmployee.NameAddition != null && NewEmployee.NameAddition.Length > 10)
            {
                MessageBox.Show("tussenvoegsel mag maximum 10 tekens bevatten");
                return(false);
            }

            if (string.IsNullOrEmpty(NewEmployee.LastName) || NewEmployee.LastName.Length < 2 || NewEmployee.LastName.Length > 25)
            {
                MessageBox.Show("Achternaam moet 2 tot 25 tekens bevatten");
                return(false);
            }

            if (!RegexUtilities.IsValidEmail(NewEmployee.Email))
            {
                MessageBox.Show("Email is geen geldig email");
                return(false);
            }

            if (NewEmployee.MobileNumber != null && NewEmployee.MobileNumber.Length > 20)
            {
                MessageBox.Show("Gsm mag maximum 20 tekens bevatten");
                return(false);
            }
            if (NewEmployee.PhoneNumber != null && NewEmployee.PhoneNumber.Length > 15)
            {
                MessageBox.Show("Telefoon mag maximum 15 tekens bevatten");
                return(false);
            }
            if (string.IsNullOrEmpty(NewEmployee.EmpAddress.Street) || NewEmployee.EmpAddress.Street.Length < 2 || NewEmployee.EmpAddress.Street.Length > 30)
            {
                MessageBox.Show("Straat moet 2 tot 30 tekens bevatten");
                return(false);
            }
            if (NewEmployee.EmpAddress.HouseNumber < 1 || NewEmployee.EmpAddress.HouseNumber > 3000)
            {
                MessageBox.Show("geen geldig huisnummer");
                return(false);
            }
            if (NewEmployee.EmpAddress.HouseNumberAddition != null && NewEmployee.EmpAddress.HouseNumberAddition.Length > 8)
            {
                MessageBox.Show("Bus kan maximum 8 tekens bevatten");
                return(false);
            }
            if (string.IsNullOrEmpty(NewEmployee.EmpAddress.Zipcode) || NewEmployee.EmpAddress.Zipcode.Length < 4 || NewEmployee.EmpAddress.Zipcode.Length > 12)
            {
                MessageBox.Show("postcode moet 4 tot maximum 12 tekens bevatten");
                return(false);
            }
            if (string.IsNullOrEmpty(NewEmployee.EmpAddress.City) || NewEmployee.EmpAddress.City.Length < 4 || NewEmployee.EmpAddress.City.Length > 20)
            {
                MessageBox.Show("Gemeente moet 4 tot maximum 20 tekens bevatten");
                return(false);
            }
            if (string.IsNullOrEmpty(NewEmployee.EmpAddress.Country) || NewEmployee.EmpAddress.Country.Length < 4 || NewEmployee.EmpAddress.Country.Length > 20)
            {
                MessageBox.Show("Land moet 4 tot maximum 20 tekens bevatten");
                return(false);
            }
            if (string.IsNullOrEmpty(NewEmployee.PassPortID) || NewEmployee.PassPortID.Length < 4 || NewEmployee.PassPortID.Length > 15)
            {
                MessageBox.Show("rijksregisternummer moet 5 tot maximum 15 tekens bevatten");
                return(false);
            }
            if (string.IsNullOrEmpty(NewEmployee.IBAN) || NewEmployee.IBAN.Length < 4 || NewEmployee.IBAN.Length > 15)
            {
                MessageBox.Show("IBAN moet 5 tot maximum 15 tekens bevatten");
                return(false);
            }
            if (NewEmployee.Id_EmpDepartment < 1)
            {
                MessageBox.Show("Afdeling is niet ingevuld");
                return(false);
            }
            if (NewEmployee.EmpContract.Id_EmpContractType < 1)
            {
                MessageBox.Show("contracttype is niet ingevuld");
                return(false);
            }
            if (NewEmployee.EmpContract.Id_EmpContractStatuutType < 1)
            {
                MessageBox.Show("Statuut is niet ingevuld");
                return(false);
            }
            if (NewEmployee.EmpContract.MonthSalary < 1)
            {
                MessageBox.Show("Ongeldig maandsalaris");
                return(false);
            }
            if (NewEmployee.EmpContract.DateOfStart == null)
            {
                MessageBox.Show("Startdatum moet ingevuld zijn");
                return(false);
            }


            if (IsNewMode)
            {
                //cijfers, grote en kleine letters, underscores en range
                if (string.IsNullOrEmpty(NewEmployee.EmpAppAccount.UserName) ||
                    !new Regex("^[0-9A-Za-z_]{5,20}$").IsMatch(NewEmployee.EmpAppAccount.UserName))
                {
                    MessageBox.Show("Geen geldig gebruikersnaam");
                    return(false);
                }

                if (string.IsNullOrEmpty(NewEmployee.EmpAppAccount.Password) ||
                    !new Regex(
                        "^"
                        +
                        "(?=.*[A-Z]+)"          // [A-Z] betekend een hoofdletter, het plusje betekend '1 of meer'
                        +
                        "(?=.*[a-z]+)"          // [a-z] betekend een kleine letter, het plusje betekend '1 of meer'
                        +
                        "(?=.*[0-9]+)"          // [0-9] betekend een digital, het plusje betekend '1 of meer'
                        +
                        $"(?=.*[_]+)"           //tekens tss aanhalingstekenz, het plusje betekend '1 of meer'
                        +
                        ".{8,20}$"              //kijken of het geheel 8tot 20 lang is,
                        ).IsMatch(NewEmployee.EmpAppAccount.Password))
                {
                    MessageBox.Show("Geen geldig Passwoord");
                    return(false);
                }
            }

            return(true);
        }
Beispiel #29
0
 public void RegexUtilities_ValidateBlankEmail()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail("   "));
 }
Beispiel #30
0
        public async static void OpenClientEditDialog(Client client)
        {
            ClientEdit dialog = new ClientEdit(client);
            var        result = await dialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                string firstName = dialog.FirstName.Text;
                string lastName  = dialog.LastName.Text;
                string email     = dialog.Email.Text;
                string phone     = dialog.Phone.Text;
                string street    = dialog.Street.Text;
                string number    = dialog.HouseNumber.Text;
                string box       = dialog.Box.Text;
                string city      = dialog.City.Text;
                string zip       = dialog.Zip.Text;
                string country   = "";
                string company   = dialog.Company.Text;
                string vat       = dialog.VAT.Text;

                if (dialog.Country.SelectedIndex >= 0)
                {
                    country = dialog.Country.SelectedItem.ToString().Split(new string[] { ": " }, StringSplitOptions.None).Last();
                }
                if (string.IsNullOrWhiteSpace(firstName) || string.IsNullOrWhiteSpace(lastName))
                {
                    MainWindow.DisplayThrowbackDialog("Client Edit Error", "You must fill in a first and list name"); return;
                }
                if (!RegexUtilities.IsValidEmail(email, false))
                {
                    MainWindow.DisplayThrowbackDialog("Client Edit Error", "The given email address is not valid"); return;
                }
                if (!RegexUtilities.IsValidPhoneNumber(phone, false))
                {
                    MainWindow.DisplayThrowbackDialog("Client Edit Error", "The given phone number is not valid"); return;
                }
                if (dialog.Type.SelectedIndex < 0)
                {
                    MainWindow.DisplayThrowbackDialog("Client Edit Error", "You must select an account type"); return;
                }
                if (!Enum.TryParse(typeof(ClientType), dialog.Type.SelectedItem.ToString().ToUpper().Split(new string[] { ": " }, StringSplitOptions.None).Last(), out object objType))
                {
                    MainWindow.DisplayThrowbackDialog("Client Edit Error", "Something went wrong with the client type, try agian"); return;
                }
                ClientType type = (ClientType)objType;
                if (type == ClientType.PRIVATE || type == ClientType.VIP)
                {
                    company = ""; vat = "";
                }

                client.Type          = type;
                client.FirstName     = firstName;
                client.LastName      = lastName;
                client.Email         = email;
                client.Phone         = phone;
                client.AddressStreet = street;
                client.AddressNumber = number;
                client.AddressBus    = box;
                client.AddressCity   = city;
                client.AddressZip    = zip;
                client.AddressCounty = country;
                client.CompanyName   = company;
                client.VATNumber     = vat;

                RentalManager manager = new RentalManager(new UnitOfWork(new RentalContext()));
                manager.UpdateClient(client);

                MainWindow.DisplayThrowbackDialog("Client Saved", "All changes have been saved"); return;
            }
        }
Beispiel #31
0
 public void RegexUtilities_ValidateEmailForTextAndSymbol()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail("abc@"));
 }
Beispiel #32
0
        private async void Save()
        {
            if (string.IsNullOrEmpty(this.User.FirstName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Não pode dejar o Nome vazio",
                    "Aceitar");

                return;
            }

            if (string.IsNullOrEmpty(this.User.LastName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Não pode dejar o Sobrenome vazio",
                    "Aceitar");

                return;
            }

            if (string.IsNullOrEmpty(this.User.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Não pode dejar o Email vazio",
                    "Aceitar");

                return;
            }

            if (!RegexUtilities.IsValidEmail(this.User.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Não é o Email valido",
                    "Aceitar");

                return;
            }

            if (string.IsNullOrEmpty(this.User.Telephone))
            {
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Não pode dejar o Telephone vazio",
                    "Aceitar");

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var checkConnetion = await this.apiService.CheckConnection();

            if (!checkConnetion.IsSucces)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "Problemas de coneçao",
                    "Aceitar");

                return;
            }

            byte[] imageArray = null;
            if (this.file != null)
            {
                imageArray = FilesHelper.ReadFully(this.file.GetStream());
            }

            var userDomain = Converter.ToUserDomain(this.User, imageArray);


            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            var response    = await this.apiService.Put(
                apiSecurity,
                "/api",
                "/Users",
                MainViewModel.GetInstance().TokenType,
                MainViewModel.GetInstance().Token,
                userDomain);

            if (!response.IsSucces)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    response.Message,
                    "Aceitar");

                return;
            }

            this.IsRunning = false;
            this.IsEnabled = true;


            await App.Navigator.PopAsync();
        }
Beispiel #33
0
 public void RegexUtilities_ValidateEmailForMultipleSymbols()
 {
     Assert.IsFalse(RegexUtilities.IsValidEmail("[email protected]@"));
 }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string eventName = String.Format("{0}", Request.Form["EventName"]);
        string eventCategory = String.Format("{0}", Request.Form["EventCategory"]);
        string description = String.Format("{0}", Request.Form["description"]);
        string address = String.Format("{0}", Request.Form["address"]);
        string date = String.Format("{0}", Request.Form["date"]);
        string time = String.Format("{0}", Request.Form["time"]);
        string phone = String.Format("{0}", Request.Form["PhoneNumber"]);
        string email = String.Format("{0}", Request.Form["email"]);

        RegexUtilities util = new RegexUtilities();

        //TODO connect to database and create the event
        if(eventName.CompareTo("") == 0 || eventCategory.CompareTo("") == 0 ||
           description.CompareTo("") == 0 || date.CompareTo("") == 0 ||
           time.CompareTo("") == 0 || phone.CompareTo("") == 0 || email.CompareTo("") == 0)
        {
            Response.Write("Complete all fields");
            return;
        }
        else if(!util.IsValidEmail(email))
        {
            Response.Write("That is not a valid email.");
            return;
        }

        //opens the object connection
        SqlConnection objConnection = new SqlConnection("Data Source=184.168.194.68;Initial Catalog=EventsDB;Integrated Security=False;User ID=kevin95duarte;password=sqlpassword1;Connect Timeout=60;Encrypt=False;Packet Size=4096;MultipleActiveResultSets=True");

        try
        {
            objConnection.Open();
            /*
                pubprirso values:

                0 public university event
                1 private university event
                2 RSO event
            */
            int pubprirso = 0;

            //Finds out if the user is a student, admin, or superadmin (denoted by pubprirso)
            String strSQL = String.Format("select * from director D where D.directorID={0}", Session["studentID"]);
            SqlCommand isDirector = new SqlCommand(strSQL, objConnection);
            SqlDataReader isDirectorReader = isDirector.ExecuteReader();

            if(isDirectorReader.Read())
            {
                pubprirso = 1;
            }

            strSQL = String.Format("select * from admin A where A.adminID={0}", Session["studentID"]);
            SqlCommand isAdmin = new SqlCommand(strSQL, objConnection);
            SqlDataReader isAdminReader = isAdmin.ExecuteReader();

            if (isAdminReader.Read())
            {
                pubprirso = 2;
            }

            //checks if there is an event with the same name
            strSQL = String.Format("select * from event E where E.name='{0}'", eventName);
            SqlCommand eventExists = new SqlCommand(strSQL, objConnection);
            SqlDataReader eventExistsReader = eventExists.ExecuteReader();

            if(eventExistsReader.Read())
            {
                Response.Write("An event of that name already exists");
                return;
            }

            //Create the event
            strSQL = String.Format("INSERT INTO event(type, name, description, contact_phone, contact_email, date, time, pubprirso) VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', {7})",
                                    eventCategory, eventName, description, phone, email, date, time, pubprirso);
            SqlCommand insertEvent = new SqlCommand(strSQL, objConnection);
            insertEvent.ExecuteNonQuery();

            //gets the eventID
            strSQL = String.Format("SELECT * FROM event E WHERE E.name='{0}'", eventName);
            SqlCommand getEventID = new SqlCommand(strSQL, objConnection);
            SqlDataReader eventReader = getEventID.ExecuteReader();

            int eventID = -1;
            if (eventReader.Read())
            {
                eventID = Convert.ToInt32(eventReader["eventID"]);
            }

            //gets the universityID
            strSQL = String.Format("SELECT * FROM attends A WHERE A.studentID={0}", Session["studentID"]);
            SqlCommand getUniversityID = new SqlCommand(strSQL, objConnection);
            SqlDataReader universityReader = getUniversityID.ExecuteReader();

            int universityID = -1;
            if(universityReader.Read())
            {
                universityID = Convert.ToInt32(universityReader["universityID"]);
            }

            //creates the hostedBy relation between event and university
            strSQL = String.Format("INSERT INTO hostedBy(universityID, eventID) VALUES({0}, {1})", universityID, eventID);
            SqlCommand insertHosted = new SqlCommand(strSQL, objConnection);
            insertHosted.ExecuteNonQuery();

            //creates the organizedBy relation between rso and event
            if(pubprirso == 2)
            {
                //gets the rsoID
                strSQL = String.Format("SELECT * FROM manages M WHERE M.adminID={0}", Session["studentID"]);
                SqlCommand getRSOID = new SqlCommand(strSQL, objConnection);
                SqlDataReader rsoReader = getRSOID.ExecuteReader();

                int rsoID = -1;
                if (rsoReader.Read())
                {
                    rsoID = Convert.ToInt32(rsoReader["rsoID"]);
                }

                strSQL = String.Format("INSERT INTO organizedBy(rsoID, eventID) VALUES({0}, {1})", rsoID, eventID);
                SqlCommand insertOrganized = new SqlCommand(strSQL, objConnection);
                insertOrganized.ExecuteNonQuery();
            }

            //creates the heldAt relationship for the event
            strSQL = String.Format("INSERT INTO heldAt(eventID, address) VALUES({0},'{1}')", eventID, address);
            SqlCommand insertHeldAt = new SqlCommand(strSQL, objConnection);
            insertHeldAt.ExecuteNonQuery();

            Response.Redirect("Events.aspx");

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
        finally
        {
            if (objConnection.State == ConnectionState.Open)
            {
                objConnection.Close();
            }
        }
    }
Beispiel #35
0
        private async void Save()
        {
            if (string.IsNullOrEmpty(this.User.FirstName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.FirstNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.User.LastName))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.LastNameValidation,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.User.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation,
                    Languages.Accept);

                return;
            }

            if (!RegexUtilities.IsValidEmail(this.User.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation2,
                    Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(this.User.Telephone))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.PhoneValidation,
                    Languages.Accept);

                return;
            }

            this.IsRunning = true;
            this.IsEnabled = false;

            var checkConnetion = await this.apiService.CheckConnection();

            if (!checkConnetion.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    checkConnetion.Message,
                    Languages.Accept);

                return;
            }

            byte[] imageArray = null;
            if (this.file != null)
            {
                imageArray = FilesHelper.ReadFully(this.file.GetStream());
            }

            var userDomain  = Converter.ToUserDomain(this.User, imageArray);
            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            var response    = await this.apiService.Put(
                apiSecurity,
                "/api",
                "/Users",
                MainViewModel.GetInstance().Token.TokenType,
                MainViewModel.GetInstance().Token.AccessToken,
                userDomain);

            if (!response.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    response.Message,
                    Languages.Accept);

                return;
            }

            var userApi = await this.apiService.GetUserByEmail(
                apiSecurity,
                "/api",
                "/Users/GetUserByEmail",
                MainViewModel.GetInstance().Token.TokenType,
                MainViewModel.GetInstance().Token.AccessToken,
                this.User.Email);

            var userLocal = Converter.ToUserLocal(userApi);

            MainViewModel.GetInstance().User = userLocal;
            this.dataService.Update(userLocal);

            this.IsRunning = false;
            this.IsEnabled = true;

            await App.Navigator.PopAsync();
        }
        async void Recovery()
        {
            if (string.IsNullOrEmpty(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation,
                    Languages.Accept);

                return;
            }

            if (!RegexUtilities.IsValidEmail(this.Email))
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    Languages.EmailValidation2,
                    Languages.Accept);

                return;
            }

            IsRunning = true;
            IsEnabled = false;

            var checkConnetion = await apiService.CheckConnection();

            if (!checkConnetion.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.Error,
                    checkConnetion.Message,
                    Languages.Accept);

                return;
            }

            var apiSecurity = Application.Current.Resources["APISecurity"].ToString();

            var response = await apiService.PasswordRecovery(
                apiSecurity,
                "/api",
                "/Users/PasswordRecovery",
                Email);

            if (!response.IsSuccess)
            {
                IsRunning = false;
                IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    "Error",
                    "We can't send the new password to this email.",
                    "OK");

                return;
            }

            IsRunning = false;
            IsEnabled = true;

            await Application.Current.MainPage.DisplayAlert(
                Languages.ConfirmLabel,
                "Your new password has been sent to your email!",
                Languages.Accept);

            await Application.Current.MainPage.Navigation.PopAsync();
        }
Beispiel #37
0
 public async Task<int> AddRedactor(string redactorEmail)
 {
     try
     {
         RegexUtilities util = new RegexUtilities();
         if (util.IsValidEmail(redactorEmail))
         {
             var user = User.Identity.Name;
             var redactor = userRepository.Find(u => u.UserName == redactorEmail);
             if (redactor != null)
             {
                 var tRedactor = redactorsRepository.Find(r => r.UserId_Id == redactor.Id && r.Administrator_Id == User.Identity.GetUserId());
                 if (tRedactor != null)
                 {
                     return 3;
                 }
                 else
                 {
                     redactorsRepository.Add(new Model.TableRedactorModels { Administrator_Id = User.Identity.GetUserId(), IsLocked = false, IsReadOnly = false, TableId = -1, UserId_Id = redactor.Id });
                     await SendMailHelper.SendNoticeAboutAccess(redactorEmail, user);
                     return 1;
                 }
             }
             else
             {
                 await SendMailHelper.SendInvite(redactorEmail, user);                           
                 return 2;
             }
         }
         else
         {
             return 0;
         }
     }
     catch
     {
     return 0;
     }
 }
Beispiel #38
0
    protected override void OnMenuGUI()
    {
        Screen.lockCursor = false;
        Screen.showCursor = true;

        GUIStyle centeredStyle = new GUIStyle(GUI.skin.label);

        centeredStyle.alignment        = TextAnchor.MiddleCenter;
        centeredStyle.normal.textColor = Color.red;

        if (loginFailed && Time.time - lastLoginFailed < 5f)
        {
            GUILayout.Label(failedMessage, centeredStyle, GUILayout.Width(490));
        }
        else if (Time.time - lastLoginFailed >= 5f)
        {
            loginFailed = false;
        }

        if (!internetConnection)
        {
            failedMessage = "No internet connection";
            loginFailed   = true;

            if (GUILayout.Button("Play offline", GUILayout.Width(490)))
            {
                SwitchTo <MainMenu>();
            }
        }
        else
        {
            if (disconnected)
            {
                disconnected = false;
                OnDisconnected();
            }
            else if (GameStateManager.loggedIn)
            {
                SwitchTo <MainMenu>();
            }

            GUILayout.BeginHorizontal(GUILayout.Width(490));
            GUILayout.Label("Login: "******"Password: "******"Signup", GUILayout.ExpandWidth(true)))
            {
                SwitchTo <Signup>();
            }


            if (GameStateManager.Password != "" && GameStateManager.Login != "")
            {
                if (GUILayout.Button("Login", GUILayout.Width(245)))
                {
                    confirm = true;
                }

                if (confirm)
                {
                    RegexUtilities rg = new RegexUtilities();
                    confirm = false;

                    using (WebClient wb = new WebClient())
                    {
                        string hashString = GameStateManager.Password;
                        if (hashString != startPassword)
                        {
                            isHashNeeded = true;
                        }
                        NameValueCollection data = new NameValueCollection();
                        if (isHashNeeded)
                        {
                            hashString = Signup.HashString(GameStateManager.Password);
                        }

                        data["id"]   = GameStateManager.Login;
                        data["psw"]  = hashString;
                        data["mode"] = "in";

                        byte[] response = wb.UploadValues(MainMenu.url, "POST", data);
                        using (MD5 md5Hash = MD5.Create())
                        {
                            if (!Signup.VerifyMd5Hash(md5Hash, "no", System.Text.Encoding.UTF8.GetString(response)))
                            {
                                GameStateManager.connectionID = System.Text.Encoding.UTF8.GetString(response);
                                GameStateManager.loggedIn     = true;
                                GameStateManager.Password     = hashString;
                                GameStateManager.startProcess = true;
                                GameStateManager.version      = checkVersion();
                                PlayerLogs pl = new PlayerLogs();
                                pl.Login    = GameStateManager.Login;
                                pl.Password = GameStateManager.Password;
                                pl.SerializeLogs();
                                SwitchTo <MainMenu>();
                            }
                            else
                            {
                                loginFailed     = true;
                                failedMessage   = "Login failed";
                                lastLoginFailed = Time.time;
                            }
                        }
                    }
                }
            }
            GUILayout.EndHorizontal();
        }
    }
 private void txtEmailAdd_Leave(object sender, EventArgs e)
 {
     RegexUtilities util = new RegexUtilities();
     if (txtEmailAdd.Text != string.Empty)
     {
         if (!util.IsValidEmail(txtEmailAdd.Text))
         {
             MessageBox.Show("Invalid E-mail Address");
             txtEmailAdd.Focus();
             return;
         }
     }
 }
        async void Save()
        {
            try
            {
                if (conexion.AbrirConexion() == true)
                {
                    /*aca validamos que si hallan ingresado*/
                    if (string.IsNullOrEmpty(FirstName))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "Debes ingresar un nombre.");

                        return;
                    }

                    if (string.IsNullOrEmpty(LastName))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "Debes ingresar un apellido");

                        return;
                    }

                    if (string.IsNullOrEmpty(Email))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "Debes ingresar un correo electrónico.");

                        return;
                    }

                    if (!RegexUtilities.IsValidEmail(Email))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "Debes ingresar un Email válido.");

                        return;
                    }

                    if (string.IsNullOrEmpty(Password))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "Debes ingresar una contraseña");

                        return;
                    }

                    if (Password.Length < 6)
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "La contraseña debe tener al menos 6 caracteres.");

                        return;
                    }

                    if (string.IsNullOrEmpty(Confirm))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "Debe ingresar una contraseña de confirmación");

                        return;
                    }

                    if (!Password.Equals(Confirm))
                    {
                        await dialogService.ShowMessage(
                            "Error",
                            "La contraseña y confirmacion, no coincide.");

                        return;
                    }

                    Usuario pUsuario = new Usuario();

                    pUsuario.FirstName = FirstName;
                    pUsuario.LastName  = LastName;
                    pUsuario.Email     = Email;
                    pUsuario.Phone     = Phone;
                    pUsuario.Password  = Password;
                    pUsuario.Confirm   = Confirm;

                    int resultado;

                    resultado = Usuario.AgregarUsuario(conexion.conexion, pUsuario);

                    if (resultado > 0)
                    {
                        FirstName = "";
                        LastName  = "";
                        Email     = "";
                        Phone     = "";
                        Password  = "";
                        Confirm   = "";
                    }

                    IsRunning = true;
                    IsEnabled = false;

                    conexion.CerrarConexion();
                }
            } catch (MySql.Data.MySqlClient.MySqlException ex) {
                await dialogService.ShowMessage(ex.Message);
            }



            /* var customer = new Customer
             * {
             *   Email = Email,
             *   FirstName = FirstName,
             *   LastName = LastName,
             *   Password = Password,
             *   Phone = Phone,
             * };*/
            #region Comentado

            /*var connection = await apiService.CheckConnection();
             * if (!connection.IsSuccess)
             * {
             * IsRunning = false;
             * IsEnabled = true;
             * await dialogService.ShowMessage("Error", connection.Message);
             * return;
             * }
             * // aca mandamos todos los datos que el usuario halla digitado
             * var customer = new Customer
             * {
             * Address = Address,
             * CustomerType = 1,
             * Email = Email,
             * FirstName = FirstName,
             * LastName = LastName,
             * Password = Password,
             * Phone = Phone,
             * };
             *
             * var response = await apiService.Post(
             * "http://productszuluapi.azurewebsites.net",
             * "/api",
             * "/Customers",
             * customer);
             *
             * if (!response.IsSuccess)
             * {
             * IsRunning = false;
             * IsEnabled = true;
             * await dialogService.ShowMessage(
             *     "Error",
             *     response.Message);
             * return;
             * }
             *
             * var response2 = await apiService.GetToken(
             * "http://productszuluapi.azurewebsites.net",
             * Email,
             * Password);
             *
             * if (response2 == null)
             * {
             * IsRunning = false;
             * IsEnabled = true;
             * await dialogService.ShowMessage(
             *     "Error",
             *     "The service is not available, please try latter.");
             * Password = null;
             * return;
             * }
             *
             * if (string.IsNullOrEmpty(response2.AccessToken))
             * {
             * IsRunning = false;
             * IsEnabled = true;
             * await dialogService.ShowMessage(
             *     "Error",
             *     response2.ErrorDescription);
             * Password = null;
             * return;
             * }
             */

            #endregion

            var mainViewModel = MainViewModel.GetInstance();
            mainViewModel.Plans = new PlansViewModel();
            /**/ await Application.Current.MainPage.Navigation.PushAsync(new PlansPage());

            IsRunning = false;
            IsEnabled = true;
        }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //receive the inputed information
        string firstName = String.Format("{0}", Request.Form["firstName"]);
        string lastName = String.Format("{0}", Request.Form["lastName"]);
        string email = String.Format("{0}", Request.Form["email"]);
        string password = String.Format("{0}", Request.Form["password"]);
        string university = String.Format("{0}", Request.Form["universityInfo"]);
        RegexUtilities util = new RegexUtilities();

        //TODO connect to database and add the information
        if (firstName.CompareTo("") == 0 || lastName.CompareTo("") == 0 ||
            email.CompareTo("") == 0 || password.CompareTo("") == 0 ||
            university.CompareTo("") == 0)
        {
            //all fields are not completed
            Response.Write("Complete all fields");
        }
        else if(!util.IsValidEmail(email))
        {
            //email is not valid
            Response.Write("Not a valid email");
        }
        else
        {
            SqlConnection objConnection = new SqlConnection("Data Source=184.168.194.68;Initial Catalog=EventsDB;Integrated Security=False;User ID=kevin95duarte;password=sqlpassword1;Connect Timeout=15;Encrypt=False;Packet Size=4096;MultipleActiveResultSets=True");

            try
            {
                objConnection.Open();

                //checks if the email is in the DB
                string strSQL = String.Format("select * from student where email='{0}'", email);
                SqlCommand objCommand = new SqlCommand(strSQL, objConnection);
                SqlDataReader objReader = objCommand.ExecuteReader();

                //the email is in the DB
                if (objReader.Read())
                {
                    //Email already has an account
                    Response.Write("this email already has an account.");
                }
                //email is not in the DB, create the account
                else
                {
                    //inserts the student in the DB
                    strSQL = String.Format("INSERT INTO student (first_name, last_name, password, email) VALUES ('{0}','{1}','{2}','{3}');",
                        firstName, lastName, password, email);
                    SqlCommand objCommand2 = new SqlCommand(strSQL, objConnection);
                    objCommand2.ExecuteNonQuery();

                    //gets the universityID
                    strSQL = String.Format("SELECT * FROM university U WHERE U.initials='{0}'", university);
                    SqlCommand getUniversityID = new SqlCommand(strSQL, objConnection);
                    SqlDataReader universityReader = getUniversityID.ExecuteReader();
                    int universityID = -1;

                    if(universityReader.Read())
                    {
                        universityID = Convert.ToInt32(universityReader["universityID"]);
                    }
                    else
                    {
                        //getting the uniID failed, I dont know how such a thing happened
                        Response.Write("UniversityID failed");
                    }
                    universityReader.Close();

                    //gets the row of the recently created student account
                    strSQL = String.Format("select * from student where email='{0}'", email);
                    SqlCommand objCommand3 = new SqlCommand(strSQL, objConnection);
                    SqlDataReader objReader2 = objCommand3.ExecuteReader();

                    if (objReader2.Read())
                    {
                        //adds the student to the attends table
                        int studentID = Convert.ToInt32(objReader2["studentID"]);
                        strSQL = String.Format("INSERT INTO attends(studentID, universityID) VALUES('{0}', '{1}')", studentID, universityID);
                        SqlCommand insertAttends = new SqlCommand(strSQL, objConnection);
                        insertAttends.ExecuteNonQuery();

                        //saves the student id to the session
                        Session["studentID"] = studentID;
                        //redirects to the View Events page
                        Response.Redirect("Events.aspx");
                    }
                    else
                    {
                        //login failed, I dont know how such a thing happened
                        Response.Write("Creation failed");
                    }
                    objReader2.Close();
                }
                objReader.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
            finally
            {
                if (objConnection.State == ConnectionState.Open)
                {
                    objConnection.Close();
                }
            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string rsoName = String.Format("{0}", Request.Form["RSOName"]);
        String[] emails = new String[6];
        emails[0] = String.Format("{0}", Request.Form["email"]);
        emails[1] = String.Format("{0}", Request.Form["email1"]);
        emails[2] = String.Format("{0}", Request.Form["email2"]);
        emails[3] = String.Format("{0}", Request.Form["email3"]);
        emails[4] = String.Format("{0}", Request.Form["email4"]);
        emails[5] = String.Format("{0}", Request.Form["email5"]);
        RegexUtilities util = new RegexUtilities();

        //ensures all emails are not null, and are emails
        if (rsoName.CompareTo("") == 0 || emails[0].CompareTo("") == 0 ||
            emails[1].CompareTo("") == 0 || emails[2].CompareTo("") == 0 ||
            emails[3].CompareTo("") == 0 || emails[4].CompareTo("") == 0 ||
            emails[5].CompareTo("") == 0)
        {
            Response.Write("Fill in all fields");
            return;
        }
        else if (!(util.IsValidEmail(emails[0]) && util.IsValidEmail(emails[1]) &&
                    util.IsValidEmail(emails[2]) && util.IsValidEmail(emails[3]) &&
                    util.IsValidEmail(emails[4]) && util.IsValidEmail(emails[5])))
        {
            Response.Write("Not valid emails");
            return;
        }

        //opens the object connection
        SqlConnection objConnection = new SqlConnection("Data Source=184.168.194.68;Initial Catalog=EventsDB;Integrated Security=False;User ID=kevin95duarte;password=sqlpassword1;Connect Timeout=60;Encrypt=False;Packet Size=4096;MultipleActiveResultSets=True");

        try
        {
            objConnection.Open();

            //checks if RSO name exists
            String strSQL = String.Format("select * from rso R where name='{0}'", rsoName);
            SqlCommand objCommand = new SqlCommand(strSQL, objConnection);
            SqlDataReader objReader = objCommand.ExecuteReader();

            //the rso name is in the DB
            if (objReader.Read())
            {
                //Email already has an account
                Response.Write("This rso name is taken.");
                return;
            }
            objReader.Close();

            //check if all emails are in DB
            int[] ids = new int[6];
            for(int i = 0; i < 6; i++)
            {

                strSQL = String.Format("SELECT * FROM student S WHERE UPPER(S.email)=UPPER('{0}')", emails[i]);
                SqlCommand objCommand2 = new SqlCommand(strSQL, objConnection);
                SqlDataReader objReader2 = objCommand2.ExecuteReader();

                //the email is in the DB, save the id
                if(objReader2.Read())
                {
                    ids[i] = Convert.ToInt32(objReader2["studentID"]);
                }
                else
                {
                    //email is not in the DB
                    Response.Write(String.Format("{0} does not have an account", emails[i]));
                    return;
                }
                objReader2.Close();
            }

            //checks if all students attend the same university
            int[] universityIDs = new int[6];
            for (int i = 0; i < 6; i++)
            {
                strSQL = String.Format("select * from attends A where A.studentID='{0}'", ids[i]);
                SqlCommand objCommand2 = new SqlCommand(strSQL, objConnection);
                SqlDataReader objReader2 = objCommand2.ExecuteReader();

                if (objReader2.Read())
                {
                    universityIDs[i] = Convert.ToInt32(objReader2["universityID"]);
                }
                objReader2.Close();
            }
            for(int i = 1; i < 6; i++)
            {
                //all the universities are not the same
                if(universityIDs[0] != universityIDs[i])
                {
                    Response.Write("All students do not attend the same university");
                    return;
                }
            }

            String emailEnd = emails[0].Substring(emails[0].IndexOf('@'));
            for(int i = 1; i < 6; i++)
            {
                //all emails do not end the same
                if(emailEnd.CompareTo(emails[i].Substring(emails[i].IndexOf('@'))) != 0)
                {
                    Response.Write("All students do not have the same university email");
                    return;
                }
            }

            //Creates a new rso INSERTS it into the Database

            strSQL = String.Format("INSERT INTO rso(name) VALUES('{0}')", rsoName);
            SqlCommand insertRSO = new SqlCommand(strSQL, objConnection);
            insertRSO.ExecuteNonQuery();

            //gets the rsoID
            strSQL = String.Format("SELECT * FROM rso WHERE name='{0}'", rsoName);
            SqlCommand getRSOID = new SqlCommand(strSQL, objConnection);
            SqlDataReader rsoReader = getRSOID.ExecuteReader();

            int rsoID = -1;
            if(rsoReader.Read())
            {
                rsoID = Convert.ToInt32(rsoReader["rsoID"]);
            }

            //creates a new partOf relationship
            strSQL = String.Format("INSERT INTO partOf(universityID, rsoID) VALUES({0}, {1})", universityIDs[0], rsoID);
            SqlCommand insertPartOf = new SqlCommand(strSQL, objConnection);
            insertPartOf.ExecuteNonQuery();

            //adds all the students into the rso
            for(int i = 0; i < 6; i++)
            {
                strSQL = String.Format("INSERT INTO memberOf(studentID, rsoID) VALUES({0}, {1})", ids[i], rsoID);
                SqlCommand insertMemberOf = new SqlCommand(strSQL, objConnection);
                insertMemberOf.ExecuteNonQuery();
            }

            //makes the admin, an admin
            strSQL = String.Format("INSERT INTO admin(adminID) VALUES({0})", ids[0]);
            SqlCommand insertAdmin = new SqlCommand(strSQL, objConnection);
            insertAdmin.ExecuteNonQuery();

            //makes admin manage the rso
            strSQL = String.Format("INSERT INTO manages(adminID, rsoID) VALUES({0}, {1})", ids[0], rsoID);
            SqlCommand insertManages = new SqlCommand(strSQL, objConnection);
            insertManages.ExecuteNonQuery();

            Response.Write("The RSO has been successfully created");

        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
        finally
        {
            if (objConnection.State == ConnectionState.Open)
            {
                objConnection.Close();
            }
        }
    }