protected void Button1_Click(object sender, EventArgs e) //注册用户登录 { Boolean is_enter = false; if ( userOrStaff.Text.Equals("员工") ) { t_login = new LaborialStaff(); t_login.Initialize( user_name.Text,pass_word.Text ); is_enter = t_login.IsLegal(); Session["UserType"] = "员工"; } if( userOrStaff.Text.Equals ("用户") ) { t_login = new User(); t_login.Initialize( user_name.Text,pass_word.Text ); is_enter = t_login.IsLegal(); Session["UserType"] = "用户"; } if (userOrStaff.Text.Equals("信息管理员")) { t_login = new InfoManager(); t_login.Initialize(user_name.Text, pass_word.Text); is_enter = t_login.IsLegal(); Session["UserType"] = "信息管理员"; } if ( is_enter ) { Server.Transfer("RegisteredUser.aspx",true);//跳转问题:1.系统管理员 2.信息管理员 3.普通注册用户 //判断角色跳转到相应的页面 } }
protected void Button3_Click(object sender, EventArgs e) //系统管理员登录 { Boolean is_enter = false; t_login = new LogBackstage(); t_login.Initialize( user_name.Text,pass_word.Text ); is_enter = t_login.IsLegal(); if ( is_enter ) { Server.Transfer("ManageUserInfo.aspx", true); } }
protected void Button2_Click(object sender, EventArgs e) //游客通道 { Boolean is_record; t_login = new Visitor(); t_login.Initialize("ip","time");//此处要求时间和IP地址 is_record = t_login.IsLegal(); if ( is_record ) { t_login.Record(); Server.Transfer("Visitor.aspx", true); }//此处要判断IP地址是否合法,目前还没做 }
public static void Main(string[] args) { Mutex mutex = new System.Threading.Mutex(false, "OwnCloudCalendarConnerctor"); try { if (mutex.WaitOne(0, false)) { string logConfigFile = AppDomain.CurrentDomain.BaseDirectory + @"config.log4net"; log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(logConfigFile)); Application.Initialize(ToolkitType.Gtk); Xwt.Drawing.Image iconImage = Xwt.Drawing.Image.FromFile(@"D:\Vladimir Varagic\Privatno\Diplomski rad\svnVersion\ownCloudCalendar\trunk\ownCloudCalendarProject\ownCloudCalendar\ownCloudCalendarXWT\Images\20141129064955676_easyicon_net_32.ico"); var mainWindow = new Window() { Title = "ownCloud Calendar Client", Width = 500, Height = 250, Icon = iconImage }; mainWindow.Resizable = false; LogIn logIn = new LogIn(); mainWindow.Content = logIn; mainWindow.Show(); Application.Run(); mainWindow.Dispose(); } else { Application.Initialize(ToolkitType.Gtk); MessageDialog.ShowMessage("An instance of the application is already running."); } } finally { if (mutex != null) { mutex.Close(); mutex = null; } } }
public void GoTo(LoginScreen loginScreen) { LogIn.Click(loginScreen.WaitForAppear); }
public void Init() { userList = new List <User>(); login = new LogIn(); }
private void LogInButton_Click(object sender, EventArgs e) { // LogInPresenter lp = new LogInPresenter(this); LogIn?.Invoke(); }
public void GivenIHaveEnteredMyUsernameAndPassword() { LogIn.UserNamePassWord(); }
public void FillLogInFormHardCode(LogIn user) { Type(this.EmailAdress, user.EmailAddress); Type(this.Password, user.Password); this.LogInButton.Click(); }
internal Tuple<bool, TimeSpan> LogIn(LogIn.Model.User userAtComputer, ServiceReference1.Credentials knownUser, LogIn.ServiceReference1.Booking booking) { TimeSpan time = new TimeSpan(0, 0, 0); if (knownUser != null) { if (isSameUser(userAtComputer, knownUser)) { return Tuple.Create<bool, TimeSpan>(true, getTimeForLogIn(booking)); } } return Tuple.Create<bool, TimeSpan>(false, time); }
public ActionResult Login(LogIn login) { var user = database.Customer.Where(e => e.Email == login.Username && e.PassCode == login.Password).FirstOrDefault(); return RedirectToAction("UserProfile", new { id = user.Id }); }
public static Account DrawLogin() { Console.CursorVisible = false; ConsoleKeyInfo btn; var cur = 0; bool chosen = true; while (chosen) { Console.Clear(); if (cur == 0) { Console.ForegroundColor = ConsoleColor.Blue; System.Console.WriteLine("registration"); Console.ForegroundColor = ConsoleColor.White; System.Console.WriteLine("sinin"); } else { Console.ForegroundColor = ConsoleColor.White; System.Console.WriteLine("registration"); Console.ForegroundColor = ConsoleColor.Blue; System.Console.WriteLine("sinin"); } btn = Console.ReadKey(); switch (btn.Key) { case ConsoleKey.UpArrow: if (cur == 0) { cur = 1; } else { cur = 0; } break; case ConsoleKey.DownArrow: if (cur == 0) { cur = 1; } else { cur = 0; } break; case ConsoleKey.Enter: if (cur == 1) { chosen = false; return(LogIn.LogOn()); } else { SignUp.CreateAccount(); } break; } } return(null); }
protected override void OnStartup(StartupEventArgs e) { LogIn window = new LogIn(); window.Show(); }
async private void LogInToApp_Click(object sender, EventArgs e) { var logIn = LogInInput.Text; var password = PasswordInput.Text; await LogIn?.Invoke(logIn, password); }
public BtnLogIn(LogIn logIn) { this.logIn = logIn; }
internal ServiceReference1.Credentials getUserFBooking(LogIn.ServiceReference1.Booking booking, long libId) { if (booking != null) { if (!booking.ClientPass.Equals(string.Empty)) { LogIn.ServiceReference1.PrinchService1SoapClient soap = new LogIn.ServiceReference1.PrinchService1SoapClient(binding, endpointAddress); return soap.getUserForBooking(booking.BookingID, libId); } } return null; }
protected override void SpeechRecognitionEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { base.SpeechRecognitionEngine_SpeechRecognized(sender, e); RecognitionResult result = e.Result; if (result.Confidence < 0.6) { SpeakRepeat(); } else { string[] command = result.Semantics.Value.ToString().ToLower().Split('.'); DispatchAsync(() => { switch (command.First()) { case "login": if (PopupLogin.IsOpen == false) { Speak("Podaj numer telefonu!"); LogIn.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); } else { if (NumberTextBox.Text.Length == NumberTextBox.MaxLength) { LogowaniePopup.Focus(); LogowaniePopup.Command?.Execute(null); LogowaniePopup.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); } else { Speak("Wpisz poprawny numer telefonu"); } } break; case "register": if (PopupRegister.IsOpen == false) { Speak("Podaj numer telefonu!"); Register.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); } else { if (NumberTextBoxReg.Text.Length == NumberTextBoxReg.MaxLength) { RegisterPopup.Focus(); RegisterPopup.Command?.Execute(null); RegisterPopup.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); } else { Speak("Wpisz poprawny numer telefonu"); } } break; case "help": SpeakHelp(); break; case "quit": ZamknijPopup.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent)); break; } }); } }
public void logInMethod() { LogIn logInObject = new LogIn(); _token = logInObject.logUserIn("user", "password"); }
public void CircularAssignTest() { LogIn.Login("nati", "123456", UserId_Nati); Assert.AreEqual(AssignStoreManager.AsssignManager(UserId_Orel, "Victory", "nati", privileges), true); Assert.Throws <ErrorMessageException>(() => AssignStoreManager.AsssignManager(UserId_Nati, "Victory", "orel", privileges)); }
public void ReadFromStateFile(string Path) { string line; string FunctionName; try { int userId = CreateAndGetUser.CreateUser(); StreamReader sr = new StreamReader(Path + ".txt"); line = sr.ReadLine(); while (line != null) { string[] funcAndParam = line.Split(':'); FunctionName = funcAndParam[0].Trim(); string[] param = funcAndParam[1].Split(','); switch (FunctionName) { case "Login": { LogIn.Login(param[0], param[1], userId); break; } case "Register": { Register.Registration(param[0], param[1], userId); break; } case "SaveProductToCart": { SaveProductToCart.SaveProduct(int.Parse(param[0]), userId, int.Parse(param[1])); break; } case "Edit": { WatchAndEdit.Edit(param[0], int.Parse(param[1]), userId); break; } case "Logout": { LogOut.Logout(userId); break; } case "OpenStore": { OpenStore.openStore(param[0], userId); break; } case "AssignStoreOwner": { AssignStoreOwner.assignStoreOwner(userId, param[1], param[2]); break; } case "AssignStoreManager": { string[] boolArray = param[3].Split(';'); bool[] privileges = new bool[7]; int index = 0; foreach (string X in boolArray) { if (X.Equals("T")) { privileges[index] = true; } else { privileges[index] = false; } index++; } AssignStoreManager.AsssignManager(userId, param[1], param[2], privileges); break; } case "RemoveStoreManager": { RemoveStoreManager.removeStoreManager(userId, param[1], param[2]); break; } case "AcceptAppointment": { HandlerRequestAppointment.AcceptAppointment(param[0], userId, param[2]); break; } case "DeclineAppointment": { HandlerRequestAppointment.DeclineAppointment(param[0], userId, param[2]); break; } case "RemoveUserFromSystem": { RemoveUserFromSystem.RemoveUser(userId, param[1]); break; } } line = sr.ReadLine(); } sr.Close(); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); } }
public ActionResult LogIn() { LogIn login = new LogIn(); return(View("~/Views/Login.cshtml", login)); }
public void GivenIHaveNavigatedToFacebook_Com() { CommonFeatures.Initialize(); LogIn.Navigation(); }
public App() { InitializeComponent(); MainPage = new LogIn(); }
public void WhenIClickOnLogin() { LogIn.ClickLogin(); }
private void Form1_Load(object sender, EventArgs e) { start = new LogIn { Dock = DockStyle.Fill }; topScores = new HighScores { Dock = DockStyle.Fill }; ca = new ControlArkanoid { Dock = DockStyle.Fill }; ca.Width = Width; ca.Height = Height; player = new Player(); gO = new GameOverUser { Dock = DockStyle.Fill }; gO.backToMenu = () => { Controls.Remove(gO); tableLayoutPanel1.Show(); }; w = new Winner { Dock = DockStyle.Fill }; w.backToMenuW = () => { Controls.Remove(w); tableLayoutPanel1.Show(); }; start.startGame = () => { start.Dispose(); Controls.Remove(start); Controls.Add(ca); bttnStartGame.Focus(); ca.GamePage = (wo) => { gP = wo; }; ca.TerminarJuego = () => { player.Score = DatosJuego.puntaje; PlayerDAO.CreateNew(player); DatosJuego.vidas = 3; DatosJuego.ticksRealizados = 0; DatosJuego.puntaje = 0; Controls.Remove(ca); ca = null; ca = new ControlArkanoid { Dock = DockStyle.Fill, }; ca.Width = Width; ca.Height = Height; if (gP) { Controls.Add(w); } else { Controls.Add(gO); } }; bttnStartGame.Focus(); }; topScores.backMenu = () => { Controls.Remove(topScores); tableLayoutPanel1.Show(); }; ca.GamePage = (wo) => { gP = wo; }; ca.TerminarJuego = () => { player.Score = DatosJuego.puntaje; PlayerDAO.CreateNew(player); Controls.Remove(ca); DatosJuego.vidas = 3; DatosJuego.puntaje = 0; DatosJuego.ticksRealizados = 0; ca = null; ca = new ControlArkanoid { Dock = DockStyle.Fill, }; ca.Width = Width; ca.Height = Height; if (gP) { Controls.Add(w); } else { Controls.Add(gO); } }; bttnStartGame.Focus(); }
private bool LogIn(LoginRegisterData data) { LogIn login = new LogIn(data.UserName); return(login.ValidatePassword(data.Password)); }
private void logInToolStripMenuItem_Click(object sender, EventArgs e) { if (trafficMonitor.User.Name == "") { var login = new LogIn(); login.Show(); } else { MessageBox.Show(trafficMonitor.User.Name + " you are already logged in!"); } }
static void Main(string[] args) { User temporaryUser = new User(); bool isActive = true; string key; do { Console.Clear(); Console.WriteLine("1. Зарегистрировать пользователя \n2. Войти в личный кабинет \n3. Поиск \n4. Просмотреть весь каталог товаров \n5. Выход"); key = Console.ReadLine(); switch (key) { case "1": { Console.Clear(); User user = new User(); AccountRegistration registration = new AccountRegistration(); registration.Registration(user); } break; case "2": { Console.Clear(); LogIn login = new LogIn(); login.LogInChecker(temporaryUser); if (temporaryUser.IsLogged == true) { Console.Clear(); Console.WriteLine("1. Корзина \n2. История покупок \n3. Выйти из аккаунта \n4. Назад в главное меню"); string action; bool basketIsExit = false; action = Console.ReadLine(); switch (action) { case "1": { Console.WriteLine("Реализовано только в подкюченном режиме"); } break; case "2": { Console.WriteLine("Реализовано только в подкюченном режиме"); } break; case "3": { login.LogOut(temporaryUser); } break; case "4": { break; } break; } Console.ReadKey(); } else { Console.WriteLine("Для доступа в личный кабинет нужно авторизоваться в системе"); Console.ReadKey(); } } break; case "3": { int pageSize = 3; int pageNumber = 0; bool exit = false; FindItem find = new FindItem(); Console.WriteLine("Введите название товара"); string itemName = Console.ReadLine(); while (!exit) { Console.Clear(); try { var result = find.FindItems(itemName, pageSize, pageNumber); foreach (var item in result) { Console.WriteLine(item.Name); Console.WriteLine(item.Price); Console.WriteLine(item.Description); Console.WriteLine("--------------------------------------------------"); } } catch (ArgumentOutOfRangeException exception) { Console.WriteLine("Ошибка! Чтобы продолжить просмотр листайте вперед"); } Console.WriteLine("1. Следующая страница \n2. Предыдущая страница \n3. Выход"); string action = Console.ReadLine(); if (action == "1") { pageNumber++; } else if (action == "2") { pageNumber--; } else if (action == "3") { exit = true; } } } break; case "4": { int pageSize = 3; int pageNumber = 0; bool exit = false; int i = 1; ShowItem show = new ShowItem(); while (!exit) { Console.Clear(); try { var result = show.ShowItems(pageSize, pageNumber); foreach (var item in result) { Console.WriteLine("Наименование товара: " + item.Name); Console.WriteLine("Цена: " + item.Price); Console.WriteLine("Описание товара: " + item.Description); Console.WriteLine("--------------------------------------------------"); i++; } } catch (ArgumentOutOfRangeException exception) { Console.WriteLine("Ошибка! Чтобы продолжить просмотр листайте вперед"); } Console.WriteLine("1. Следующая страница \n2. Предыдущая страница \n3. Выход"); string action = Console.ReadLine(); if (action == "1") { pageNumber++; } else if (action == "2") { pageNumber--; } else if (action == "3") { exit = true; } } } break; case "5": { isActive = false; } break; } } while (isActive != false); }
private void LoginButton_Click(object sender, EventArgs e) { AutomaticFormPosition.SaveFormStatus(this); LogIn?.Invoke(this, e); Hide(); }
public async Task <int> SaveItemAsync() { //Getting the current timestamp... //long currentTimeStamp = ConvertToTimestamp(DateTime.Now); Application.Current.Properties.Clear(); await LogIn.checkLocationAsync(); int count = await database.Table <Weather>().CountAsync(); if (!Application.Current.Properties.ContainsKey("Location_ERR") && Application.Current.Properties.ContainsKey("latitude") && Application.Current.Properties.ContainsKey("longitude")) { double latitude = (double)Application.Current.Properties["latitude"]; double longitude = (double)Application.Current.Properties["longitude"]; //Building the queryString string queryString = "https://api.darksky.net/forecast/7066a9da455e545aff23508adb3c59f8/" + latitude + "," + longitude; //Get the data of the week.. if (LogIn.checkConnectivity()) { var results = await DataCore.getDataFromService(queryString).ConfigureAwait(false); Debug.WriteLine("Got data"); await DeleteItemAsync(); // Code for addition... Application.Current.Properties["Summary"] = ((string)results["daily"]["summary"]).Split(',')[0]; if (results["daily"] != null) { var dailyData = results["daily"]["data"]; Debug.WriteLine(dailyData.Count() + " <- Count"); for (int i = 0; i < dailyData.Count() - 1; i++) { Weather weather = new Weather(); weather.Icon = (string)dailyData[i]["icon"]; if (weather.Icon.Equals("partly-cloudy")) { weather.Icon = "partly_cloudy"; } else if (weather.Icon.Equals("clear-day")) { weather.Icon = "clear_day"; } else if (weather.Icon.Equals("clear-night")) { weather.Icon = "clear_night"; } else if (weather.Icon.Equals("cloudy-night")) { weather.Icon = "cloudy_night"; } else if (weather.Icon.Equals("partly-cloudy-day")) { weather.Icon = "partly_cloudy"; } else if (weather.Icon.Equals("partly-cloudy-night")) { weather.Icon = "cloudy_night"; } weather.Icon += ".png"; weather.SummaryOfWeek = ((string)results["daily"]["summary"]).Split(',')[0]; Debug.WriteLine(weather.Icon); weather.Summary = (string)dailyData[i]["summary"]; weather.Time = (long)dailyData[i]["time"]; DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(weather.Time).ToLocalTime(); if (i > 0) { weather.dateToDisplay = dt.Date.DayOfWeek.ToString(); } else if (i == 0) { weather.dateToDisplay = "Today"; } weather.TemperatureLow = (int)(((float)dailyData[i]["temperatureMin"] - 32) * 5 / 9); weather.TemperatureMax = (int)(((float)dailyData[i]["temperatureMax"] - 32) * 5 / 9); await database.InsertAsync(weather); Debug.WriteLine("Inserted!!"); Present.IsPresent = true; } } return(1); } else { DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(ConvertToTimestamp(DateTime.Now)).ToLocalTime(); string currentWeekDay = dt.Date.DayOfWeek.ToString(); Weather weather = await database.Table <Weather>().Where(i => i.dateToDisplay == currentWeekDay).FirstAsync(); if (weather != null) { Debug.WriteLine("Weather ID -> " + weather.ID); await DeleteItemAsync(weather.ID); } else { if (count == 0) { return(-1); } Weather weather1 = await database.Table <Weather>().FirstAsync(); Application.Current.Properties["Summary"] = weather1.SummaryOfWeek; } } return(0); } else { DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(ConvertToTimestamp(DateTime.Now)).ToLocalTime(); string currentWeekDay = dt.Date.DayOfWeek.ToString(); Weather weather = await database.Table <Weather>().Where(i => i.dateToDisplay == currentWeekDay).FirstOrDefaultAsync(); if (weather != null) { Debug.WriteLine("Weather ID -> " + weather.ID); await DeleteItemAsync(weather.ID); } if (count == 0) { return(-1); } Weather weather1 = await database.Table <Weather>().FirstAsync(); Application.Current.Properties["Summary"] = weather1.SummaryOfWeek; return(0); } }
private async Task Member(IDialogContext context, IAwaitable <string> result) { try { Contrasena = await result; if (OpcionLoginSignUp == "Iniciar Sesión") { JavaScriptSerializer js = new JavaScriptSerializer(); string tramaJson = ""; LogIn logIn = new LogIn { access_token = "LmTXw9oHsVZhhjgllFQphiZfXXJJGVwF" }; string postdata = js.Serialize(logIn); byte[] dataBytes = Encoding.UTF8.GetBytes(postdata); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://loginrestapi.herokuapp.com/auth"); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.ContentLength = dataBytes.Length; request.ContentType = "application/json"; request.Method = "POST"; string authInfo = Correo + ":" + Contrasena; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers.Add("Authorization", "Basic " + authInfo); using (Stream requestBody = request.GetRequestStream()) { requestBody.Write(dataBytes, 0, dataBytes.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { tramaJson = reader.ReadToEnd(); } UsuarioObtenido usuarioObtenido = js.Deserialize <UsuarioObtenido>(tramaJson); token = usuarioObtenido.token; string[] opciones = { "Consultar Pregunta", "Crear Pregunta" }; var options = opciones; var descriptions = opciones; PromptDialog.Choice <string>(context, ConsultaCreaPregunta, options, $"Hola {usuarioObtenido.user.name}, ahora escoge entre consultar o crear pregunta:", descriptions: descriptions); } else if (OpcionLoginSignUp == "Registrarse") { JavaScriptSerializer js = new JavaScriptSerializer(); string tramaJson = ""; SignUp signUp = new SignUp { access_token = "LmTXw9oHsVZhhjgllFQphiZfXXJJGVwF", email = Correo, password = Contrasena, name = Nombres, picture = "", role = "" }; string postdata = js.Serialize(signUp); byte[] dataBytes = Encoding.UTF8.GetBytes(postdata); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://loginrestapi.herokuapp.com/users"); request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.ContentLength = dataBytes.Length; request.ContentType = "application/json"; request.Method = "POST"; using (Stream requestBody = request.GetRequestStream()) { requestBody.Write(dataBytes, 0, dataBytes.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { tramaJson = reader.ReadToEnd(); } UsuarioObtenido usuarioObtenido = js.Deserialize <UsuarioObtenido>(tramaJson); token = usuarioObtenido.token; string[] opciones = { "Consultar Pregunta", "Crear Pregunta" }; var options = opciones; var descriptions = opciones; PromptDialog.Choice <string>(context, ConsultaCreaPregunta, options, $"Hola {usuarioObtenido.user.name}, ahora escoge entre consultar o crear pregunta:", descriptions: descriptions); } } catch (WebException wex) { if (wex.Response != null) { if (((HttpWebResponse)wex.Response).StatusCode.ToString() == "Unauthorized") { await context.PostAsync($"El usuario o contraseña ingresada no es correcta."); context.Wait(MessageReceived); } else { using (var errorResponse = (HttpWebResponse)wex.Response) { using (var reader = new StreamReader(errorResponse.GetResponseStream())) { string error = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); UsuarioError usuarioError = js.Deserialize <UsuarioError>(error); await context.PostAsync($"Error en: {usuarioError.message}"); context.Wait(MessageReceived); } } } } } catch (Exception ex) { await context.PostAsync($"{ex.Message.ToString()}"); context.Wait(MessageReceived); } }
internal TimeSpan getTimeForLogIn(LogIn.ServiceReference1.Booking booking) { DateTime now = DateTime.Now; TimeSpan t = now.Subtract(booking.BookingEnd); return t; }
private void btLogIn_Click(object sender, EventArgs e) { LogIn?.Invoke(this, EventArgs.Empty); }
internal bool isSameUser(LogIn.Model.User userAtPC, ServiceReference1.Credentials theUser) { byte[] hashSalt = Convert.FromBase64String(theUser.ClientPass); return validate(userAtPC.UserName, hashSalt, theUser.ClientID); }
public async Task <IActionResult> Index(string nuts, string list, string money, string pills, string ticket, string action, string graf, string balls, string birz, string value) { //получаем БД var users = from m in _context.LogIn orderby m.Id select m; //Проверяем тест int answer = 0; if (nuts == "1") { answer += 1; } if (list == "3") { answer += 1; } if (money == "3") { answer += 1; } if (pills == "2") { answer += 1; } if (ticket == "4") { answer += 1; } if (action == "1") { answer += 1; } if (graf == "3") { answer += 1; } if (balls == "2") { answer += 1; } if (birz == "4") { answer += 1; } if (value == "1") { answer += 1; } //Берём последнюю запись, т.е. нынешнего пользователя LogIn user = users.Last(); //Т.к. пользователь впервый раз проходит тест, то его поля верных и неверных ответов пока равны 0, после его ответа они изменят значение, но если он вернётся и попытается //исправить свои ответы, ему это не удастся, т.к. эти поля уже будут заполнены ответами и он просто вернётся на страницу регистрации if (user.False == 0 && user.True == 0) { //вычисляем поля верных и неверных ответов и обновляем БД user.True = answer; user.False = 10 - answer; _context.Update(user); //сохраняем изменения await _context.SaveChangesAsync(); //отправляем письмо var emailMessage = new MimeMessage(); emailMessage.From.Add(new MailboxAddress("Администрация", "*****@*****.**")); emailMessage.To.Add(new MailboxAddress(user.Name, user.Email)); emailMessage.Subject = "Тестирование"; emailMessage.Body = new TextPart(MimeKit.Text.TextFormat.Plain) { Text = $"{user.Name} {user.FirstName}, Вы набрали {user.True} из 10 баллов." }; using (var client = new SmtpClient()) { await client.ConnectAsync("smtp.gmail.com", 465, true); await client.AuthenticateAsync("*****@*****.**", "1q2w3E4R$"); await client.SendAsync(emailMessage); await client.DisconnectAsync(true); } } return(RedirectToAction(nameof(Create))); }
public void UserLoggings(int UserID) { String sDate = DateTime.Now.ToString(); DateTime dValue = (Convert.ToDateTime(sDate.ToString())); String strDay = dValue.Day.ToString(); String strMonth = dValue.Month.ToString(); String strYear = dValue.Year.ToString(); String strDayID = strDay + "-" + strMonth + "-" + strYear; dynamic UL = (from u in db.UserLogins where u.UserIDs.Equals(UserID) && u.Date.Equals(strDayID) select u).FirstOrDefault(); //Checking if the User has lo if (UL != null) //If user already exist increase the number of times he has logged in today. /** * This is to check if there is a new user loggining in. If The user is not new it will just increment the number of * times the user has logged in. * This code is meant excute if it already exists in the database */ { UL.NumberOfLogins++; try { db.SubmitChanges(); } catch (Exception e) { e.GetBaseException(); } } else { UserLogin U = new UserLogin() { Date = strDayID, UserIDs = UserID, NumberOfLogins = 1, }; db.UserLogins.InsertOnSubmit(U); try { db.SubmitChanges(); } catch (Exception e) { e.GetBaseException(); } //The abouve code keeps tracks of how many times a specific user logins /** * Now we going to use the dateId to check if an instance of the date already exists. If it does exist than * We will make the number of log ins equal to 1. We will just increment it. */ dynamic Day = (from d in db.LogIns where d.Date.Equals(strDayID) select d).FirstOrDefault(); if (Day != null) { Day.NumberOfLogins++; try { db.SubmitChanges(); } catch (Exception e) { e.GetBaseException(); } } else { LogIn LG = new LogIn() { Date = strDayID, NumberOfLogins = 1, }; db.LogIns.InsertOnSubmit(LG); try { db.SubmitChanges(); } catch (Exception e) { e.GetBaseException(); } } } }
async Task LoginAfterResolveUserDetailAction(NiconicoContext context) { Context = context; Mntone.Nico2.Users.Info.InfoResponse userInfo = null; try { await Task.Delay(50); userInfo = await Context.User.GetInfoAsync(); if (userInfo == null) { IsLoggedIn = false; throw new Exception("ログインに失敗"); } } catch (Exception e) { IsLoggedIn = false; HandleLoginError(e); return; } IsLoggedIn = true; UserId = userInfo.Id; IsPremiumAccount = userInfo.IsPremium; try { var user = await Context.User.GetUserDetail(_UserId.ToString()); UserName = user?.Nickname ?? _UserId.ToString(); UserIconUrl = user?.ThumbnailUri; } catch (Exception ex) { IsLoggedIn = false; Debug.WriteLine("ユーザー名取得処理に失敗 + " + _UserId); Debug.WriteLine(ex.ToString()); #if DEBUG if (Debugger.IsAttached) { Debugger.Break(); } #endif return; } LogIn?.Invoke(this, new NiconicoSessionLoginEventArgs() { UserId = UserId, IsPremium = userInfo.IsPremium, UserName = UserName, UserIconUrl = UserIconUrl, }); Debug.WriteLine("Login Done! " + ServiceStatus); }
private void btnLogOut_Click() { try { this.ParentWindow.Hide(); var mainWindow = new Window() { Title = "ownCloud Calendar Client", Width = 500, Height = 250, Icon = iconImage }; mainWindow.Resizable = false; LogIn logIn = new LogIn(); mainWindow.Content = logIn; mainWindow.Show(); } catch (Exception ex) { HandleException(ex); } }
public ActionResult LogIn() { var myLogin = new LogIn(); return(View("~/Views/LogIn.cshtml", myLogin)); }
private void LogOut() { var currentWindow = Application.Current.MainWindow; var logIn = new LogIn(); logIn.Show(); currentWindow.Close(); Application.Current.MainWindow = logIn; }
public BtnRegistration(LogIn logIn) { this.logIn = logIn; }