Esempio n. 1
0
 public ListProfile(XmlElement element)
     : base(element)
 {
     Users = new UserList();
     foreach (XmlElement child in element.GetElementsByTagName("user"))
     {
         Users.Add(new User(child));
     }
 }
Esempio n. 2
0
 public void SortTest()
 {
     UserList target = new UserList();
     target.Add(new User { Nick = "Ortzinator"});
     target.Add(new User { Nick = "P90" });
     target.Add(new User { Nick = "gparent" });
     target.Add(new User { Nick = "DEADBEEF" });
     target.Add(new User { Nick = "@ChanServ" });
     target.Add(new User { Nick = "+SteveUK" });
     target.Add(new User { Nick = "@SpamServ" });
     target.Add(new User { Nick = "+HTF" });
     target.Add(new User { Nick = "+ninjers" });
     Comparison<User> comparison = (user1, user2) => user1.CompareTo(user2);
     target.Sort(comparison);
     foreach (User user in target)
     {
         Debug.WriteLine(user.Nick);
     }
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
 internal static UserList getUserList(HttpResponseMessage response)
 {
     var userList = new UserList();
     JObject jobject = JObject.Parse(response.Content.ReadAsStringAsync().Result);
     if(jobject["users"]!=null)
     {
         foreach(var userObj in jobject["users"])
         {
             var user = getUserProperties(userObj.ToString());
             userList.Add(user);
         }
     }
     if (jobject["page_context"]!=null)
     {
         var pageContext = new PageContext();
         pageContext = JsonConvert.DeserializeObject<PageContext>(jobject["page_context"].ToString());
         userList.page_context = pageContext;
     }
     return userList;
 }
Esempio n. 4
0
        public void adding()
        {
            bool lo = true;

            do
            {
                Console.WriteLine("Wprowadź login:"******"Nadaj uprawnienia \n1 - admin \n2 - lekarz");
                int.TryParse(Console.ReadLine(), out i);
                if (i >= 1 && i <= 2)
                {
                    newPermission = i;
                    k             = false;
                }

                if (i > 2)
                {
                    Console.WriteLine("Uprawnienia: \n1- admin \n2-lekarz ");
                }
            } while (k);


            bool pa = true;

            do
            {
                Console.WriteLine("Wprowadź hasło:");
                Console.WriteLine();
                newPassword = Console.ReadLine().ToLower();

                if (newPassword.Length > 2)
                {
                    pa = false;
                }
            }while (pa);


            Console.Clear();

            UserList _oLista = new UserList();

            if (File.Exists(@"baza_uzytkownikow.xml"))
            {
                _oLista.LoadFromXml(@"baza_uzytkownikow.xml");

                _oLista.Add(new User {
                    Login = newLogin, Password = newPassword, Permission = newPermission
                });


                _oLista.SaveAsXml(@"baza_uzytkownikow.xml");
            }
            else
            {
                Console.WriteLine("Błąd wczytywania bazy danych przy próbie dodania użytkownika");
            }
        }
 public void AddUser(User user)
 {
     UserList.Add(user);
     UserPersistency.SaveUsers(user);
 }
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         ObjectList.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 GXDLMSObject obj = GetObject(settings, item);
                 //Unknown objects are not shown.
                 if (obj is IGXDLMSBase)
                 {
                     ObjectList.Add(obj);
                 }
             }
         }
     }
     else if (e.Index == 3)
     {
         if (e.Value != null)
         {
             ClientSAP = Convert.ToByte(((Object[])e.Value)[0]);
             ServerSAP = Convert.ToUInt16(((Object[])e.Value)[1]);
         }
     }
     else if (e.Index == 4)
     {
         //Value of the object identifier encoded in BER
         if (e.Value is byte[])
         {
             GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]);
             if (arr.GetUInt8(0) == 0x60)
             {
                 ApplicationContextName.JointIsoCtt            = arr.GetUInt8();
                 ApplicationContextName.Country                = arr.GetUInt8();
                 ApplicationContextName.CountryName            = arr.GetUInt8();
                 ApplicationContextName.IdentifiedOrganization = arr.GetUInt8();
                 ApplicationContextName.DlmsUA             = arr.GetUInt8();
                 ApplicationContextName.ApplicationContext = arr.GetUInt8();
                 ApplicationContextName.ContextId          = (ApplicationContextName)arr.GetUInt8();
             }
             else
             {
                 //Get Tag and Len.
                 if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.JointIsoCtt = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.Country = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x12)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.CountryName = arr.GetUInt16();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.IdentifiedOrganization = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.DlmsUA = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.ApplicationContext = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 ApplicationContextName.ContextId = (ApplicationContextName)arr.GetUInt8();
             }
         }
         else if (e.Value != null)
         {
             Object[] arr = (Object[])e.Value;
             ApplicationContextName.JointIsoCtt            = Convert.ToByte(arr[0]);
             ApplicationContextName.Country                = Convert.ToByte(arr[1]);
             ApplicationContextName.CountryName            = Convert.ToUInt16(arr[2]);
             ApplicationContextName.IdentifiedOrganization = Convert.ToByte(arr[3]);
             ApplicationContextName.DlmsUA             = Convert.ToByte(arr[4]);
             ApplicationContextName.ApplicationContext = Convert.ToByte(arr[5]);
             ApplicationContextName.ContextId          = (ApplicationContextName)Convert.ToByte(arr[6]);
         }
     }
     else if (e.Index == 5)
     {
         if (e.Value != null)
         {
             Object[]     arr = (Object[])e.Value;
             GXByteBuffer bb  = new GXByteBuffer();
             GXCommon.SetBitString(bb, arr[0]);
             bb.SetUInt8(0, 0);
             XDLMSContextInfo.Conformance       = (Conformance)bb.GetUInt32();
             XDLMSContextInfo.MaxReceivePduSize = Convert.ToUInt16(arr[1]);
             XDLMSContextInfo.MaxSendPduSize    = Convert.ToUInt16(arr[2]);
             XDLMSContextInfo.DlmsVersionNumber = Convert.ToByte(arr[3]);
             XDLMSContextInfo.QualityOfService  = Convert.ToSByte(arr[4]);
             XDLMSContextInfo.CypheringInfo     = (byte[])arr[5];
         }
     }
     else if (e.Index == 6)
     {
         //Value of the object identifier encoded in BER
         if (e.Value is byte[])
         {
             GXByteBuffer arr = new GXByteBuffer(e.Value as byte[]);
             if (arr.GetUInt8(0) == 0x60)
             {
                 AuthenticationMechanismName.JointIsoCtt            = arr.GetUInt8();
                 AuthenticationMechanismName.Country                = arr.GetUInt8();
                 AuthenticationMechanismName.CountryName            = arr.GetUInt8();
                 AuthenticationMechanismName.IdentifiedOrganization = arr.GetUInt8();
                 AuthenticationMechanismName.DlmsUA = arr.GetUInt8();
                 AuthenticationMechanismName.AuthenticationMechanismName = arr.GetUInt8();
                 AuthenticationMechanismName.MechanismId = (Authentication)arr.GetUInt8();
             }
             else
             {
                 //Get Tag and Len.
                 if (arr.GetUInt8() != (int)BerType.Integer && arr.GetUInt8() != 7)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.JointIsoCtt = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.Country = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x12)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.CountryName = arr.GetUInt16();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.IdentifiedOrganization = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.DlmsUA = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.AuthenticationMechanismName = arr.GetUInt8();
                 //Get tag
                 if (arr.GetUInt8() != 0x11)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 AuthenticationMechanismName.MechanismId = (Authentication)arr.GetUInt8();
             }
         }
         else if (e.Value != null)
         {
             Object[] arr = (Object[])e.Value;
             AuthenticationMechanismName.JointIsoCtt            = Convert.ToByte(arr[0]);
             AuthenticationMechanismName.Country                = Convert.ToByte(arr[1]);
             AuthenticationMechanismName.CountryName            = Convert.ToUInt16(arr[2]);
             AuthenticationMechanismName.IdentifiedOrganization = Convert.ToByte(arr[3]);
             AuthenticationMechanismName.DlmsUA = Convert.ToByte(arr[4]);
             AuthenticationMechanismName.AuthenticationMechanismName = Convert.ToByte(arr[5]);
             AuthenticationMechanismName.MechanismId = (Authentication)Convert.ToByte(arr[6]);
         }
     }
     else if (e.Index == 7)
     {
         Secret = (byte[])e.Value;
     }
     else if (e.Index == 8)
     {
         if (e.Value == null)
         {
             AssociationStatus = AssociationStatus.NonAssociated;
         }
         else
         {
             AssociationStatus = (AssociationStatus)Convert.ToInt32(e.Value);
         }
     }
     else if (e.Index == 9)
     {
         SecuritySetupReference = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 10)
     {
         UserList.Clear();
         if (e.Value != null)
         {
             foreach (Object[] item in (Object[])e.Value)
             {
                 UserList.Add(new KeyValuePair <byte, string>(Convert.ToByte(item[0]), Convert.ToString(item[1])));
             }
         }
     }
     else if (e.Index == 11)
     {
         if (e.Value != null)
         {
             Object[] tmp = (Object[])e.Value;
             CurrentUser = new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1]));
         }
         else
         {
             CurrentUser = new KeyValuePair <byte, string>(0, null);
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Esempio n. 7
0
        void client_ClientDataIn(string key, ConClient client, byte[] data)
        {
            try
            {
                UserInfo user = client.UserToken as UserInfo;

                if (user == null && client.IsProxy)
                {
                    if (UserList == null)
                    {
                        UserList = new List <UserInfo>();
                    }

                    user             = new UserInfo();
                    user.Client      = client;
                    user.MainClient  = MClient;
                    user.Stream      = new ZYSocket.share.ZYNetRingBufferPoolV2(1073741824);
                    client.UserToken = user;

                    UserList.Add(user);
                    UpdateUserListView();

                    this.BeginInvoke(new EventHandler((a, b) =>
                    {
                        this.richTextBox1.AppendText(client.Host + ":" + client.Port + "-" + client.Key + " 连接");
                    }));
                }



                if (user != null)
                {
                    user.Stream.Write(data);

                    byte[] datax;
                    while (user.Stream.Read(out datax))
                    {
                        if (user.IsSuccess)
                        {
                            DataOn(user, datax);
                        }
                        else
                        {
                            SuccessData(user, datax);
                        }
                    }
                }
                else
                {
                    if (!client.IsProxy)
                    {
                        client.Sock.Close();
                    }
                }
            }
            catch (Exception er)
            {
                this.BeginInvoke(new EventHandler((a, b) =>
                {
                    this.richTextBox1.AppendText(er.ToString() + "\r\n");
                }));
            }
        }
 internal static UserList getUserList(HttpResponseMessage responce)
 {
     var userList = new UserList();
     var jsonObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(responce.Content.ReadAsStringAsync().Result);
     if (jsonObj.ContainsKey("users"))
     {
         var usersArray = JsonConvert.DeserializeObject<List<object>>(jsonObj["users"].ToString());
         foreach(var userObj in usersArray)
         {
             var user = new User();
             user = JsonConvert.DeserializeObject<User>(userObj.ToString());
             userList.Add(user);
         }
     }
     if (jsonObj.ContainsKey("page_context"))
     {
         var pageContext = new PageContext();
         pageContext = JsonConvert.DeserializeObject<PageContext>(jsonObj["page_context"].ToString());
         userList.page_context = pageContext;
     }
     return userList;
 }
        /// <summary>
        /// Checks if its possible to login depending on the given username and password and saves the logged in user to a list
        /// </summary>
        /// <param name="obj"></param>
        private void LoginExecute(object obj)
        {
            bool   found         = false;
            bool   foundUsername = false;
            string password      = (obj as PasswordBox).Password;

            for (int i = 0; i < UserList.Count; i++)
            {
                if (User.Username == UserList[i].Username && password == UserList[i].UserPassword)
                {
                    LoggedUser.CurrentUser = new tblUser
                    {
                        UserID       = UserList[i].UserID,
                        Username     = UserList[i].Username,
                        UserPassword = UserList[i].UserPassword
                    };

                    InfoLabel = "Logged in";
                    found     = true;
                    Songs song = new Songs();
                    view.Close();
                    song.Show();
                    break;
                }
            }

            if (found == false)
            {
                for (int i = 0; i < UserList.Count; i++)
                {
                    if (User.Username == UserList[i].Username)
                    {
                        InfoLabel     = "Username already exists";
                        foundUsername = true;
                        break;
                    }
                }

                if (foundUsername == false)
                {
                    if (password == validation.PasswordChecker(password))
                    {
                        InfoLabel         = "Logged in";
                        User.UserPassword = password;
                        service.AddUser(User);
                        UserList.Add(User);

                        LoggedUser.CurrentUser = new tblUser
                        {
                            UserID       = User.UserID,
                            Username     = User.Username,
                            UserPassword = User.UserPassword
                        };

                        Songs song = new Songs();
                        view.Close();
                        song.Show();
                    }
                    else
                    {
                        InfoLabel = "Wrong Username or Password";
                    }
                }
            }
        }
Esempio n. 10
0
        public Boolean addNewUser(int userID, string username, string password, string userType, bool online)
        {
            //// some validation on userName, we won't allow duplicate usernames. Business rule
            //IUser duplicateUser = this.UserList.FirstOrDefault(user => user.Username == name.Trim());
            ///* provides a shortcut to accessing the element that occurs first in the collection or query,
            //while protecting against invalid accesses if there are no elements.It'sa linq query. FirstOrDefault is a generic method which means it accepts a type parameter that indicates what types it acts upon.
            //The => is a lambda operator. Anything before the => are the input parameters, and anything after is the expression. You can have multiple input parameters.
            //Think of a lambda expression as"given x, do something with x" * */
            //if (duplicateUser != null)
            //    return false;
            //else
            //{
            //    try
            //    {
            //        if (name.Length < 5) // Won't allow usernames with less than 5 characters. Business Rule
            //            return false; // Maybe other rules on Usernames such as some Uppercase etc
            //        if (password.Length < 5)// Won't allow passwords with less than 5 characters. Business Rule
            //            return false; // Maybe password policy such as at least one Upper case, one number etc see
            //                          // see Regex - regular expressions

            //        int maxId = 0;

            //        // maybe add some logic (busiess rules) about password policy
            //        // IUser user = new User(name, password, userType); // Construct a User Object
            //        foreach (User user in UserList)
            //        {
            //            if (user.UserID > maxId)
            //                maxId = user.UserID;
            //        }
            //        IUser theUser = UserFactory.GetUser(name, password, userType, maxId + 1); // Using a Factory to create the user entity object. ie seperating object creation from business logic
            //        UserList.Add(theUser); // Add a reference to the newly created object to the Models UserList
            //        DataLayer.addNewUserToDB(theUser); //Gets the DataLayer to add the new user to the DB.
            //        return true;
            //    }
            //    catch (System.Exception excep)
            //    {
            //        return false;
            //    }
            //}

            try
            {
                //int maxId = 0;
                //// need some code to avoid dulicate usernames
                //// maybe add some logic (busiess rules) about password policy
                ////      IUser user = new User(name, password, userType); // Construct a User Object
                //foreach (User user in UserList)
                //{
                //    if (user.UserID > maxId)
                //        maxId = user.UserID;
                //}
                IUser theUser = UserFactory.GetUser(userID, username, password, userType, online); // Using a Factory to create the user entity object. ie seperating object creation from business logic
                UserList.Add(theUser);                                                             // Add a reference to the newly created object to the Models UserList
                DataLayer.addNewUserToDB(theUser);                                                 //Gets the DataLayer to add the new user to the DB.
                return(true);
            }
            catch (System.Exception excep)
            {
                return(false);
            }
        }
Esempio n. 11
0
 public void UserIn(User newUser)
 {
     // Code for adding user to chat room
     MyUserList.Add(newUser);
 }
Esempio n. 12
0
        static async void BotOnMessageReceived(object sender, MessageEventArgs MessageEventArgs)
        {
            Telegram.Bot.Types.Message msg = MessageEventArgs.Message;
            if (msg == null || msg.Type != MessageType.Text)
            {
                return;
            }

            string Answer = "Server Error";

            if (DateTime.UtcNow.Subtract(msg.Date).TotalMinutes > 3)
            {
                await BOT.SendTextMessageAsync(msg.Chat.Id, Answer);

                return;
            }

            if (UserList.ContainsKey(msg.Chat.Id))
            {
                UserList[msg.Chat.Id].LastAccess = DateTime.Now;
            }
            if (!IsRegistered(msg.Chat.Id))
            {
                UserList.Add(msg.Chat.Id, new User()
                {
                    ident = 3
                });
                Json_Data.WriteData();   //регистрация в базе
            }
            if (UserList[msg.Chat.Id].ident == 5)
            {
                bool onOrOff = msg.Text.ToLower() == "включить";
                UserList[msg.Chat.Id].eveningNotify = onOrOff;
                UserList[msg.Chat.Id].ident         = 3;
                Json_Data.WriteData();
                string onOrOffMsg = onOrOff ? "включено" : "выключено";
                Answer = $"Вечернее уведомление *{onOrOffMsg}*.";
            }
            else if (UserList[msg.Chat.Id].ident == 6)
            {
                bool onOrOff = msg.Text.ToLower() == "включить";
                UserList[msg.Chat.Id].morningNotify = onOrOff;
                UserList[msg.Chat.Id].ident         = 3;
                Json_Data.WriteData();
                string onOrOffMsg = onOrOff ? "включено" : "выключено";
                Answer = $"Уведомление за 15 минут до первой пары *{onOrOffMsg}*.";
            }
            else
            {
                try
                {
                    switch (msg.Text.ToLower())             // Обработка команд боту
                    {
                    case "/start":
                        Answer = "Добро пожаловать!\n" + _help;
                        break;

                    case "/joke":
                    case "анекдот":
                        do
                        {
                            Answer = Markov.MakeText(1, random).Replace(" . ", ". ");
                        } while (Answer.Length > 4096);     //Search for new joke if it exceeds Telegram text msg limit
                        break;

                    case "/knowme":
                    case "знаешь меня?":
                        Answer = $"Вы {msg.Chat.FirstName.Replace("`", "").Replace("_", "").Replace("*", "")}.";
                        break;

                    case "/eveningnotify":
                        Answer = $"Сейчас вечернее уведомление *{(UserList[msg.Chat.Id].eveningNotify ? "включено" : "выключено")}*. \nНастройте его.";
                        UserList[msg.Chat.Id].ident = 5;
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : notifierKeyboard);

                        return;

                    case "/morningnotify":
                        Answer = $"Сейчас утреннее уведомление *{(UserList[msg.Chat.Id].morningNotify ? "включено" : "выключено")}*. \nНастройте его.";
                        UserList[msg.Chat.Id].ident = 6;
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : notifierKeyboard);

                        return;


                    case "/stop":
                    case "стоп":
                        UserList.Remove(msg.Chat.Id);
                        Json_Data.WriteData();
                        Answer = "Я вас забыл! Для повторной регистрации пиши /start";
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, replyMarkup : new ReplyKeyboardRemove());

                        return;

                    case "помощь":
                    case "/help":
                        Answer = _help;
                        break;

                    case "/info":
                    case "информация":
                        Answer = "Прекрасный бот для генерации прекрасного настроения!\n" +
                                 "Данный бот, реализованный на марковских цепях, используя базу данных из свыше, чем 100т. анекдотов, способен генерировать новые шедевры комедийного искусства.";
                        break;

                    case "/forceupdate":
                        logger.Info($"Запрошено принудительное обновление, ID: {msg.Chat.Id}, @{msg.Chat.Username}.");

                        logger.Info($"Завершено принудительное обновление, ID: {msg.Chat.Id}, @{msg.Chat.Username}.");
                        Answer = "Данные обновлены!";
                        break;

                    default:
                        Answer = "Введены неверные данные, повторите попытку.";
                        break;
                    }
                }
                catch (System.Net.WebException e)
                {
                    logger.Error(e, "Catched exeption:");
                    Answer = "Ошибка! Вероятно, что-то умерло. Пожалуйста, попробуйте повторить запрос позднее.";
                }
            }
            try
            {
                await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : defaultKeyboard);
            }
            catch (Exception ex) when(ex is System.Net.Http.HttpRequestException && ex.Message.Contains("429"))
            {
                logger.Warn(ex, $"Network error while answering @{msg.Chat.Username}");
            }
            catch (Exception ex) when(ex is Telegram.Bot.Exceptions.ApiRequestException)
            {
                logger.Warn(ex, $"Telegram API error while answering @{msg.Chat.Username}");
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Checks if its possible to login depending on the given username and password and saves the logged in user to a list
        /// </summary>
        /// <param name="obj"></param>
        private void LoginExecute(object obj)
        {
            bool   found         = false;
            bool   foundUsername = false;
            string password      = (obj as PasswordBox).Password;

            for (int i = 0; i < UserList.Count; i++)
            {
                if (User.Username == UserList[i].Username && password == UserList[i].UserPassword)
                {
                    LoggedUser.CurrentUser = new tblUser
                    {
                        UserID       = UserList[i].UserID,
                        Username     = UserList[i].Username,
                        UserPassword = UserList[i].UserPassword,
                        FirstName    = UserList[i].FirstName,
                        LastName     = UserList[i].LastName,
                        UserAddress  = UserList[i].UserAddress,
                        PhoneNumber  = UserList[i].PhoneNumber
                    };

                    InfoLabel = "Logged in";
                    found     = true;
                    UserWindow cake = new UserWindow();
                    view.Close();
                    cake.Show();
                    break;
                }
            }

            if (found == false)
            {
                for (int i = 0; i < UserList.Count; i++)
                {
                    if (User.Username == UserList[i].Username)
                    {
                        InfoLabel     = "Username already exists";
                        foundUsername = true;
                        break;
                    }
                }

                if (foundUsername == false)
                {
                    InfoLabel         = "Logged in";
                    User.UserPassword = password;
                    service.AddUser(User);
                    UserList.Add(User);

                    LoggedUser.CurrentUser = new tblUser
                    {
                        UserID       = User.UserID,
                        Username     = User.Username,
                        UserPassword = User.UserPassword
                    };

                    UserWindow cake = new UserWindow();
                    view.Close();
                    cake.Show();
                }
                else
                {
                    InfoLabel = "Wrong Username or Password";
                }
            }
        }
Esempio n. 14
0
 public void UserJoin(Client client)
 {
     UserList.Add(client);
 }
Esempio n. 15
0
        public Boolean addNewUser(string firstname, string lastname, string password, object userType)
        {
            string userID = "";

            if (!(userType.ToString().Equals("Student")))
            {
                userID = firstname + "." + lastname;
            }
            else // StudentID //
            {
                int[] code = new int[8] {
                    0, 0, 0, 0, 0, 0, 0, 0
                };

                foreach (IStudent s in this.StudentList)
                {
                    string[] token = s.UserID.Split(new[] { "CC" }, StringSplitOptions.None);
                    for (int i = 0; i < code.Length; i++)
                    {
                        code[i] = Int32.Parse(token[1][i].ToString());
                    }
                }

                int before = 0;
                for (int i = 7; i >= 0; i--)
                {
                    before = i;
                    if (code[i].Equals(9))
                    {
                        code[before] = 0;
                        continue;
                    }
                    code[i] += 1;
                    break;
                }
                userID = "CC";
                foreach (int i in code)
                {
                    userID += i;
                }
            }


            //IUser duplicateUser = this.UserList.FirstOrDefault(user => user.UserID == userID.Trim());

            //if (duplicateUser != null)
            //{
            //    return false;
            //}

            //else
            //{

            try
            {
                int    count = 0;
                string id    = userID;
                foreach (IUser user in UserList)
                {
                    if (user.FirstName.Equals(firstname) && user.LastName.Equals(lastname))
                    {
                        count++;
                    }
                }
                if (count == 0)
                {
                }
                else
                {
                    userID += count.ToString();
                }

                if (password.Length < 5)
                {
                    return(false);                                                                               // Maybe password policy such as at least one Upper case, one number etc see
                }
                IUser theUser = UserFactory.GetUser(userID, firstname, lastname, password, userType.ToString()); // Using a Factory to create the user entity object. ie seperating object creation from business logic
                UserList.Add(theUser);                                                                           // Add a reference to the newly created object to the Models UserList
                DataLayer.addNewUserToDB(theUser);                                                               //Gets the DataLayer to add the new user to the DB.
                return(true);
            }
            catch (System.Exception excep)
            {
                return(false);
            }
            //}
        }
Esempio n. 16
0
 public void AddNewUser(String userCode, String firstName, String lastName)
 {
     userList.Add(new User(userCode, firstName, lastName));
     userList.Save();
 }
Esempio n. 17
0
        public VMTest1()
        {
            var list = new CustomList <MAdmin>();

            list.Add(new MAdmin()
            {
                ADMIN_SEQ = 1, ADMIN_NAME = "관리자1"
            });
            list.Add(new MAdmin()
            {
                ADMIN_SEQ = 2, ADMIN_NAME = "관리자2"
            });
            list.Add(new MAdmin()
            {
                ADMIN_SEQ = 3, ADMIN_NAME = "관리자3"
            });
            list.Add(new MAdmin()
            {
                ADMIN_SEQ = 4, ADMIN_NAME = "관리자4"
            });

            AdminList = list;

            Button1Command.ExecuteTargets += Button1Command_ExecuteTargets;
            Button2Command.ExecuteTargets += Button2Command_ExecuteTargets;

            UserListAddCommand.ExecuteTargets += () => {
                //non ThreadSafe 로 오류 발생
                return(Task.Run(() => {
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                }));

                //UI 쓰레드를 통해 추가
                return(Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                    UserList.Add(new MUser()
                    {
                        isNew = true, isEdit = true
                    });
                }).Task);
            };

            UserListDeleteCommand.ExecuteTargets += (item) => {
                //원래대로라면 UI ThreadSafe 오류 발생함
                return(Task.Run(() =>
                {
                    if (item == null)
                    {
                        return;
                    }

                    if (item.isNew)
                    {
                        UserList.Remove(item);
                    }
                    else
                    {
                        item.isDelete = true;
                    }

                    //UserList.OnNotifyCollectionChanged();
                }));
            };

            /*
             * return Task.Run(async () =>
             * {
             *  if (item == null)
             *      return;
             *
             *  if (item.isNew)
             *  {
             *      await Application.Current.Dispatcher.InvokeAsync(() =>
             *      {
             *          UserList.Remove(item);
             *      });
             *  }
             *  else
             *      item.isDelete = true;
             * });
             * };
             */

            List1.Add(new KeyValuePair <string, string>("aaa", "111"));
            List1.Add(new KeyValuePair <string, string>("bbb", "222"));
            List1.Add(new KeyValuePair <string, string>("ccc", "333"));
            List1.Add(new KeyValuePair <string, string>("ddd", "444"));

            List1SelectedValue = "222";

            UserList.Add(new MUser()
            {
                USER_ID = "a1", UNIQUE_SEQ = 1, REG_DATE = DateTime.Now.AddDays(-1), ADMIN_SEQ = 1
            });
            UserList.Add(new MUser()
            {
                USER_ID = "b2", NAME = "고길동", UNIQUE_SEQ = 2, REG_DATE = DateTime.Now.AddDays(-2)
            });
            UserList.Add(new MUser()
            {
                USER_ID = "c3", NAME = "홍길홍", UNIQUE_SEQ = 3, REG_DATE = DateTime.Now.AddDays(-3)
            });
            UserList.Add(new MUser()
            {
                USER_ID = "d4", NAME = "길길동", UNIQUE_SEQ = 4, REG_DATE = DateTime.Now.AddDays(-4)
            });
            UserList.Add(new MUser()
            {
                USER_ID = "e5", NAME = "동길동", UNIQUE_SEQ = 5, REG_DATE = DateTime.Now.AddDays(-5)
            });

            foreach (var item in UserList)
            {
                item.Initialize();
            }
        }
        /// <summary>
        /// Main entry point for handling a user operation
        /// </summary>
        /// <param name="portal">DevicePortal reference for communicating with the device.</param>
        /// <param name="parameters">Parsed command line parameters.</param>
        public static void HandleOperation(DevicePortal portal, ParameterHelper parameters)
        {
            if (parameters.HasFlag(ParameterHelper.HelpFlag))
            {
                Console.WriteLine(XblUserUsageMessage);
                return;
            }

            string operationType = parameters.GetParameterValue("subop");

            if (string.IsNullOrWhiteSpace(operationType))
            {
                Console.WriteLine("Missing subop parameter");
                Console.WriteLine();
                Console.WriteLine(XblUserUsageMessage);
                return;
            }

            operationType = operationType.ToLowerInvariant();

            if (operationType.Equals("list"))
            {
                Task <UserList> getUsers = portal.GetXboxLiveUsers();

                getUsers.Wait();
                Console.WriteLine(getUsers.Result);
            }
            else if (operationType.Equals("addsponsored"))
            {
                UserInfo user = new UserInfo();

                user.SponsoredUser = true;
                user.SignedIn      = true;

                UserList userList = new UserList();
                userList.Add(user);

                UpdateXboxLiveUsers(portal, userList);
            }
            else if (operationType.Equals("signin") || operationType.Equals("signout") || operationType.Equals("delete") || operationType.Equals("autosignin"))
            {
                UserInfo user = new UserInfo();

                if (parameters.HasParameter("id"))
                {
                    uint userId = 0;
                    if (!uint.TryParse(parameters.GetParameterValue("id"), out userId))
                    {
                        Console.WriteLine(string.Format("Failed to parse id to an unsigned integer: {0}", parameters.GetParameterValue("id")));
                        return;
                    }

                    user.UserId = userId;
                }
                else
                {
                    user.EmailAddress = parameters.GetParameterValue("msa");

                    if (user.EmailAddress == null)
                    {
                        Console.WriteLine("Must provide either msa or id to this operation");
                        Console.WriteLine();
                        Console.WriteLine(XblUserUsageMessage);
                        return;
                    }
                }

                if (operationType.Equals("signin"))
                {
                    // Optional password (only used on first signin)
                    user.Password = parameters.GetParameterValue("msapwd");

                    user.SignedIn = true;
                }
                else if (operationType.Equals("signout"))
                {
                    user.SignedIn = false;
                }
                else if (operationType.Equals("delete"))
                {
                    user.Delete = true;
                }
                else if (operationType.Equals("autosignin"))
                {
                    if (parameters.HasFlag("on"))
                    {
                        user.AutoSignIn = true;
                    }
                    else if (parameters.HasFlag("off"))
                    {
                        user.AutoSignIn = false;
                    }
                    else
                    {
                        Console.WriteLine("autosignin operation requires the state (/on or /off).");
                        Console.WriteLine();
                        Console.WriteLine(XblUserUsageMessage);
                        return;
                    }
                }

                UserList userList = new UserList();
                userList.Add(user);

                UpdateXboxLiveUsers(portal, userList);
            }
            else
            {
                Console.WriteLine(string.Format("Unrecognized subop: {0}", operationType));
                Console.WriteLine();
                Console.WriteLine(XblUserUsageMessage);
                return;
            }
        }
        public ActionResult ProcessRequest(ApiTestRequest request)
        {
            // Base uri
            string baseUri = ConfigurationManager.AppSettings["LitmosAPIBaseUri"].ToString();

            RESTResponse rs = new RESTResponse();
            RESTClient client = new RESTClient(baseUri, request.ApiKey, request.Source);
            RequestFactory factory = new RequestFactory(baseUri, request.ApiKey, request.Source);

            switch (request.RequestType)
            {
                case "USERS": // Get a List of Users
                    // Get
                    var listUsers = factory.ListUsers(Request.Form["Filter"]);

                    // Format Response
                    request.ResponseBody = GetUserList(listUsers);
                    break;

                case "USER": // Get a User
                    // Get
                    var singleUser = factory.GetUser(Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = GetUser(singleUser);
                    break;

                case "CREATE_USER": // Create a User

                    UserProfile createUser = new UserProfile(Request.Form["UserName"], Request.Form["FirstName"], Request.Form["LastName"]);

                    // Create
                    var newUser = factory.CreateUser(createUser);

                    // Format Response
                    request.ResponseBody = GetUser(newUser);
                    break;

                case "UPDATE_USER": // Update a User

                    // Get User
                    var updateUser = factory.GetUser(Request.Form["UserId"]);

                    // Update User Properties
                    if (updateUser != null)
                    {
                        updateUser.Id = Request.Form["UserId"];
                        updateUser.FirstName = Request.Form["FirstName"];
                        updateUser.LastName = Request.Form["LastName"];

                        // Update 
                        updateUser = factory.UpdateUser(Request.Form["UserId"], updateUser);
                    }
                    break;

                case "TEAMS": // Get a List of Teams
                    request.ResponseBody = GetTeamList(factory.ListTeams(Request.Form["Filter"]));
                    break;

                case "SUBTEAMS": // Get a List of sub Teams
                    // Get
                    var subTeams = factory.ListTeams(Request.Form["TeamId"], Request.Form["Filter"]);

                    // Format Response
                    request.ResponseBody = GetTeamList(subTeams);
                    break;

                case "ADD_TEAMUSERS": // Get a List of Teams
                    
                    var users = new UserList();

                    users.Add(new UserProfilePartial(){
                        Id = Request.Form["UserId"]
                    });

                    var userTeamSuccess = factory.AddUsersToTeam(Request.Form["TeamId"], users);

                    // Format Response
                    request.ResponseBody = userTeamSuccess ? "Users added to team!" : "Users to team FAILED";
                    break;

                case "TEAMUSERS": // Get a List of Users
                    // Get
                    var listTeamUsers = factory.ListTeamUsers(Request.Form["TeamId"]);

                    // Format Response
                    request.ResponseBody = GetUserList(listTeamUsers);
                    break;

                case "PROMOTE_LEADER":
                    var promoteLeader = factory.PromoteTeamLeader(Request.Form["TeamId"], Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = promoteLeader ? "Users promoted to team leader!" : "Users to team FAILED";
                    break;

                case "DEMOTE_LEADER":
                    var demoteTeamLeader = factory.DemoteTeamLeader(Request.Form["TeamId"], Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = demoteTeamLeader ? "Users demoted from team leader!" : "Users to team FAILED";
                    break;

                case "COURSES": // Get a List of Courses
                    // Get
                    var listCourses = factory.ListCourses();

                    // Format Response
                    request.ResponseBody = GetCourseList(listCourses);
                    break;

                case "USER_COURSES": // Get a List of Courses
                    // Get
                    var listUserCourses = factory.ListUserCourses(Request.Form["UserId"]);

                    // Format Response
                    request.ResponseBody = GetUserCourseList(listUserCourses);
                    break;
            }


            if (rs != null)
            {
                request.ResponseStatusCode = rs.StatusCode;
                request.ResponseDescription = rs.StatusDescription;
            }

            return View("Index", request);
        }
        public UserList Login()
        {
            Console.Clear();
            UserList _oLista    = new UserList();
            UserList _oNewLista = new UserList();

            User _oUser = new User();
            Menu menu   = new Menu();



            if (File.Exists(@"baza_uzytkownikow.xml"))
            {
                _oLista.LoadFromXml(@"baza_uzytkownikow.xml");
            }
            else
            {
                Console.WriteLine("Błąd bazy danych");
            }
            do
            {
                Console.WriteLine("Zaloguj się jako:");
                Console.WriteLine("1 - Lekarz/Administrator.");
                Console.WriteLine("2 - Pacjent");
                int _odp;
                int.TryParse(Console.ReadLine(), out _odp);


                if (_odp == 1)
                {
                    do
                    {
                        Console.WriteLine("Podaj login:"******"Login nie może być pusty!");
                        }
                        else if (_oLista.Collection.Exists(x => x.Login == _oUser.Login))
                        {
                            do
                            {
                                Console.WriteLine("Podaj hasło:");

                                _oUser.Password = Console.ReadLine().ToLower();

                                if (string.IsNullOrEmpty(_oUser.Password))
                                {
                                    Console.WriteLine("Hasło nie może być puste!");
                                }
                                else if (_oLista.Collection.Exists(x => x.Password == _oUser.Password))
                                {
                                    if (_oLista.Collection.Exists(x => x.Login == _oUser.Login && x.Permission == 1))
                                    {
                                        _oNewLista.Add(new User()
                                        {
                                            Login = _oUser.Login, Permission = 1
                                        });

                                        return(_oNewLista);
                                    }
                                    if (_oLista.Collection.Exists(x => x.Login == _oUser.Login && x.Permission == 2))
                                    {
                                        _oNewLista.Add(new User {
                                            Login = _oUser.Login, Permission = 2
                                        });

                                        return(_oNewLista);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("Błędne hasło");
                                    Console.WriteLine("Czy chcesz sie cofnąć (T/N) ?");
                                    string odp = Console.ReadLine().ToUpper();
                                    if (odp == "T" || odp == "TAK" || odp == "Y" || odp == "YES")
                                    {
                                        break;
                                    }
                                }
                            } while (true);
                        }
                        else
                        {
                            Console.WriteLine("Błedny login");
                            Console.WriteLine("Czy chcesz wyjść z programu (T/N) ?");
                            string odp = Console.ReadLine().ToUpper();
                            if (odp == "T" || odp == "TAK" || odp == "Y" || odp == "YES")
                            {
                                break;
                            }
                        }
                    }while (true);
                }
                else if (_odp == 2)
                {
                    Console.WriteLine("Podaj login:"******"Login nie może być pusty!");
                    }
                    else if (!string.IsNullOrEmpty(_oUser.Login))
                    {
                        _oNewLista.Add(new User {
                            Login = _oUser.Login, Permission = 3
                        });

                        return(_oNewLista);
                    }
                }
                else
                {
                    Console.WriteLine("Błąd podaj cyfrę 1 lub 2");
                }
            } while (true);
        }
Esempio n. 21
0
 public void AddItemToList(Models.User item)
 {
     UserList.Add(item);
 }
Esempio n. 22
0
 public async Task AddItem(User item)
 {
     UserList.Add(item);
     await DataStore.AddUpdateUserAsync(item);
 }
Esempio n. 23
0
 public IActionResult RegistrationSummary(UserList)
 {
     UserList.Add("");
     return(View());
 }
        public async Task <IActionResult> OnPostFilterAsync()
        {
            try
            {
                CreateLists();

                var resultLog = await apiHttpClient.Get <List <LogItem> >("/api/Log/GetByFilter/" + FilterModel.FromDate.Ticks + "/" + FilterModel.ToDate.Ticks + "/" + FilterModel.Succeeded);

                var resultUser = await apiHttpClient.Get <List <UserItem> >("/api/User/GetAll");

                var resultCompany = await apiHttpClient.Get <List <CompanyItem> >("/api/Company/GetAll");

                if (resultLog.Succeeded && resultUser.Succeeded && resultCompany.Succeeded)
                {
                    LogList     = resultLog.Data;
                    UserList    = resultUser.Data;
                    CompanyList = resultCompany.Data;

                    UserList.Add(new UserItem
                    {
                        Id   = Guid.Empty,
                        Name = localizer["Not logged in"]
                    });

                    CompanyList.Add(new CompanyItem
                    {
                        Id   = Guid.Empty,
                        Name = ""
                    });

                    var unkonwnUser = new UserItem
                    {
                        Id   = Guid.NewGuid(),
                        Name = localizer["Unknown"]
                    };

                    var unkonwnCompany = new CompanyItem()
                    {
                        Id   = Guid.NewGuid(),
                        Name = localizer["Unknown"]
                    };

                    foreach (var logItem in LogList)
                    {
                        var user = UserList.SingleOrDefault(x => x.Id == logItem.UserId);

                        logItem.UserItem = user ?? unkonwnUser;

                        var company = CompanyList.SingleOrDefault(x => x.Id == logItem.CompanyId);

                        logItem.CompanyItem = company ?? unkonwnCompany;
                    }

                    return(Page());
                }

                return(await errorHandler.View(this, null, !resultLog.Succeeded?resultLog.Exception : !resultUser.Succeeded?resultUser.Exception : resultCompany.Exception));
            }
            catch (Exception exception)
            {
                return(await errorHandler.Log(this, null, exception));
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Add new item
        /// </summary>
        public override void Add()
        {
            User usr = ClientEnvironment.UserService.CreateEntity();

            using (FormUser frm = new FormUser())
            {
                frm.Entity = usr;
                if (frm.ShowDialog(this) == DialogResult.OK)
                {
                    if (usr.IsNew)
                    {
                        try
                        {
                            usr = ClientEnvironment.UserService.Save(usr);
                            UserList.Add(new UserInfo(usr));
                            for (int row = 0; row < UserList.Count; row++)
                            {
                                if (UserList[row].User.ID == usr.ID)
                                {
                                    focusedRow = row;
                                    break;
                                }
                            }
                            focusedUser   = new UserInfo(usr);
                            isRowNotFixed = true;
                            fixedTimes    = 3;
                            fixFocusedEntity();
                        }
                        catch (EntityException ex)
                        {
                            // 2think: what details should we show?
                            // 2think: how to localize?
                            using (FrmEntityExceptionDetails form = new FrmEntityExceptionDetails(ex))
                            {
                                form.Text = GetLocalized("CannotSaveUser");
                                form.ShowDialog(this);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            usr = ClientEnvironment.UserService.SaveOrUpdate(usr);
                            UserList.ResetItemById(usr.ID);
                        }
                        catch (EntityException ex)
                        {
                            // 2think: what details should we show?
                            // 2think: how to localize?
                            using (FrmEntityExceptionDetails form = new FrmEntityExceptionDetails(ex))
                            {
                                form.Text = GetLocalized("CannotSaveUser");
                                form.ShowDialog(this);
                            }
                        }
                    }
                }
            }
            //   RefreshData(); //******************!!!!!!!!!
        }
Esempio n. 26
0
        /// <summary>
        /// Retorba las lista de usuarios y roles desde la expresion de la regla
        /// </summary>
        /// <param name="wexpression"></param>
        /// <param name="assignedRoleList"></param>
        /// <param name="excludeUserList"></param>
        public static void BuildRolesAndUsers_FromRuleExpression(string wexpression, out RolList assignedRoleList, out UserList excludeUserList)
        {
            Rol wRol;
            User wUser;
            assignedRoleList = new RolList();
            excludeUserList = new UserList();

            StringBuilder exp = new StringBuilder(wexpression);

            exp.Replace("R:", string.Empty);
            exp.Replace("I:", string.Empty);
            exp.Replace("(", string.Empty);
            exp.Replace(")", string.Empty);
            exp.Replace("AND", string.Empty);
            String[] wArray = exp.ToString().Split(new string[] { "NOT" }, StringSplitOptions.RemoveEmptyEntries);

            if (wArray.Length > 0)
            {
                foreach (string str in wArray[0].Split(new string[] { "OR" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    wRol = new Rol(str.Trim());
                    assignedRoleList.Add(wRol);
                }
            }

            if (wArray.Length > 1)
            {
                foreach (string str in wArray[1].Split(new string[] { "OR" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    wUser = new User(str.Trim());
                    excludeUserList.Add(wUser);
                }
            }

        }
Esempio n. 27
0
 public override ExecutionResult Run(IStepExecutionContext context)
 {
     UserList.Add(User);
     Console.WriteLine($"user count: {UserList.Count}");
     return(ExecutionResult.Next());
 }
Esempio n. 28
0
        /// <summary>
        /// To Get All Users
        /// </summary>
        /// <param name="oUser"></param>
        /// <returns></returns>
        public UserList GetAllUsers(UserBO oUser)
        {
            proc = "USP_MST_GETALLUSER";
            cnn  = new OracleConnection(con);
            UserBO objUser = null;
            //Role objRole = null; //Need to used assgining the Role Name

            UserList Users   = new UserList();
            string   strUser = string.Empty;

            if (!string.IsNullOrEmpty(oUser.UserName))
            {
                strUser = "******" + oUser.UserName + "%";
            }

            cmd             = new OracleCommand(proc, cnn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("roleid_", oUser.RoleID);
            cmd.Parameters.Add("username_", strUser);
            cmd.Parameters.Add("Sp_recordset", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

            try
            {
                cmd.Connection.Open();
                OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

                while (dr.Read())
                {
                    objUser = new UserBO();
                    //objRole = new Role();
                    if (ColumnExists(dr, "UserID") && !dr.IsDBNull(dr.GetOrdinal("UserID")))
                    {
                        objUser.UserID = dr.GetInt32(dr.GetOrdinal("UserID"));
                    }
                    if (ColumnExists(dr, "UserName") && !dr.IsDBNull(dr.GetOrdinal("UserName")))
                    {
                        objUser.UserName = dr.GetString(dr.GetOrdinal("UserName"));
                    }
                    if (ColumnExists(dr, "EmailID") && !dr.IsDBNull(dr.GetOrdinal("EmailID")))
                    {
                        objUser.EmailID = dr.GetString(dr.GetOrdinal("EmailID"));
                    }
                    if (ColumnExists(dr, "RoleID") && !dr.IsDBNull(dr.GetOrdinal("RoleID")))
                    {
                        objUser.RoleID = dr.GetInt32(dr.GetOrdinal("RoleID"));
                    }
                    //Role Name need to be Assigned
                    if (ColumnExists(dr, "rolename") && !dr.IsDBNull(dr.GetOrdinal("rolename")))
                    {
                        objUser.RoleName = dr.GetString(dr.GetOrdinal("rolename"));
                    }

                    if (ColumnExists(dr, "CellNumber") && !dr.IsDBNull(dr.GetOrdinal("CellNumber")))
                    {
                        objUser.CellNumber = dr.GetString(dr.GetOrdinal("CellNumber"));
                    }
                    if (ColumnExists(dr, "DisplayName") && !dr.IsDBNull(dr.GetOrdinal("DisplayName")))
                    {
                        objUser.DisplayName = dr.GetString(dr.GetOrdinal("DisplayName"));
                    }

                    if (ColumnExists(dr, "IsDeleted") && !dr.IsDBNull(dr.GetOrdinal("IsDeleted")))
                    {
                        objUser.IsDeleted = dr.GetString(dr.GetOrdinal("IsDeleted"));
                    }
                    Users.Add(objUser);
                }

                dr.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(Users);
        }
Esempio n. 29
0
        static async void BotOnMessageReceived(object sender, MessageEventArgs MessageEventArgs)
        {
            Telegram.Bot.Types.Message msg = MessageEventArgs.Message;
            if (msg == null || msg.Type != MessageType.Text)
            {
                return;
            }

            string Answer = "Server Error";

            if (System.DateTime.UtcNow.Subtract(msg.Date).TotalMinutes > 3)
            {
                await BOT.SendTextMessageAsync(msg.Chat.Id, Answer);

                return;
            }

            if (UserList.ContainsKey(msg.Chat.Id))
            {
                UserList[msg.Chat.Id].LastAccess = DateTime.Now;
            }

            if (!IsRegistered(msg.Chat.Id))
            {
                if (!UserList.ContainsKey(msg.Chat.Id))
                {
                    UserList.Add(msg.Chat.Id, new User());
                }
                Answer = Registration(msg);      //регистрация студента
            }//prev command was /findteacher
            else if (UserList[msg.Chat.Id].ident == 4)
            {
                if (!NameMatches.ContainsKey(msg.Chat.Id))
                {
                    var lst = ReturnTeachersId(msg.Text);
                    if (lst.Length == 1)
                    {
                        Answer = LessonTechToStr(TeacherMethods.GetCurrentLesson(lst[0].id), true);
                        UserList[msg.Chat.Id].ident = 3;
                    }
                    else if (lst.Length > 1)
                    {
                        NameMatches.Add(msg.Chat.Id, lst);
                        var s = $"Найдено несколько совпадений:\n";
                        for (var i = 0; i < lst.Length; i++)
                        {
                            s = s + $"{i + 1}) {lst[i].name}\n";
                        }
                        s      = s + "Ввведи номер выбранного преподавателя.";
                        Answer = s;
                    }
                    else
                    {
                        Answer = "Ошибка, преподаватель не найден! Попробуй ещё раз.";
                    }
                }
                else
                {
                    if (int.TryParse(msg.Text, out int n) && n - 1 < NameMatches[msg.Chat.Id].Length && n - 1 >= 0)
                    {
                        var LCG = TeacherMethods.GetCurrentLesson(NameMatches[msg.Chat.Id][n - 1].id);
                        Answer = LessonTechToStr(LCG, true);
                        UserList[msg.Chat.Id].ident = 3;
                        NameMatches.Remove(msg.Chat.Id);
                    }
                    else
                    {
                        Answer = "Ошибка, введён некорректный номер.";
                    }
                }
            }
            else if (UserList[msg.Chat.Id].ident == 5)
            {
                bool onOrOff = msg.Text.ToLower() == "включить";
                UserList[msg.Chat.Id].eveningNotify = onOrOff;
                UserList[msg.Chat.Id].ident         = 3;
                Json_Data.WriteData();
                string onOrOffMsg = onOrOff ? "включено" : "выключено";
                Answer = $"Вечернее уведомление *{onOrOffMsg}*.";
            }
            else if (UserList[msg.Chat.Id].ident == 6)
            {
                bool onOrOff = msg.Text.ToLower() == "включить";
                UserList[msg.Chat.Id].preLessonNotify = onOrOff;
                UserList[msg.Chat.Id].ident           = 3;
                Json_Data.WriteData();
                string onOrOffMsg = onOrOff ? "включено" : "выключено";
                Answer = $"Уведомление за 15 минут до первой пары *{onOrOffMsg}*.";
            }
            else
            {
                try
                {
                    switch (msg.Text.ToLower())             // Обработка команд боту
                    {
                    case "/next":
                    case "ближайшая пара":
                        if (UserList[msg.Chat.Id].Info != User.UserInfo.teacher)
                        {
                            Answer = LessonToStr(StudentMethods.GetCurrentLesson(UserList[msg.Chat.Id].groupid), true);
                        }
                        else
                        {
                            Answer = LessonTechToStr(TeacherMethods.GetCurrentLesson(UserList[msg.Chat.Id].teacherId), true);
                        }
                        break;

                    case "/findteacher":
                    case "найти преподавателя":
                        Answer = "Введи фамилию преподавателя";
                        UserList[msg.Chat.Id].ident = 4;
                        break;

                    case "/week":
                    case "расписание на неделю":
                        if (UserList[msg.Chat.Id].Info != User.UserInfo.teacher)
                        {
                            Answer = WeekSchToStr(StudentMethods.GetWeekSchedule(UserList[msg.Chat.Id].groupid));
                        }
                        else
                        {
                            Answer = WeekSchTechToStr(TeacherMethods.GetWeekSchedule(UserList[msg.Chat.Id].teacherId));
                        }
                        break;

                    case "/today":
                    case "расписание на сегодня":
                        if (UserList[msg.Chat.Id].Info != User.UserInfo.teacher)
                        {
                            Answer = DaySchToStr(StudentMethods.GetTodaySchedule(UserList[msg.Chat.Id].groupid));
                        }
                        else
                        {
                            Answer = DaySchTechToStr(TeacherMethods.GetTodaySchedule(UserList[msg.Chat.Id].teacherId));
                        }
                        break;

                    case "/tomorrow":
                    case "расписание на завтра":
                        if (UserList[msg.Chat.Id].Info != User.UserInfo.teacher)
                        {
                            Answer = DaySchToStr(StudentMethods.GetTomorrowSchedule(UserList[msg.Chat.Id].groupid));
                        }
                        else
                        {
                            Answer = DaySchTechToStr(TeacherMethods.GetTomorrowSchedule(UserList[msg.Chat.Id].teacherId));
                        }
                        break;

                    case "/knowme":
                    case "знаешь меня?":
                        if (UserList[msg.Chat.Id].Info == User.UserInfo.teacher)
                        {
                            Answer = $"Вы {TeacherList[UserList[msg.Chat.Id].teacherId].name}";         //База старая, так что выводим только ФИО!!!
                        }
                        else
                        {
                            Answer = $"Вы {msg.Chat.FirstName.Replace("`","").Replace("_","").Replace("*","")} из группы {StudentMethods.groupIDToCourseGroup(UserList[msg.Chat.Id].groupid)}";
                        }
                        break;

                    case "/eveningnotify":
                        Answer = $"Сейчас вечернее уведомление о завтрашней первой паре *{(UserList[msg.Chat.Id].eveningNotify? "включено" : "выключено")}*. \nНастройте его.";
                        UserList[msg.Chat.Id].ident = 5;
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : notifierKeyboard);

                        return;

                    case "/prelessonnotify":
                        Answer = $"Сейчас уведомление за 15 минут до первой пары *{(UserList[msg.Chat.Id].preLessonNotify ? "включено" : "выключено")}*. \nНастройте его.";
                        UserList[msg.Chat.Id].ident = 6;
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : notifierKeyboard);

                        return;


                    case "/forget":
                    case "забудь меня":
                        UserList.Remove(msg.Chat.Id);
                        Json_Data.WriteData();
                        Answer = "Я вас забыл! Для повторной регистрации пиши /start";
                        await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, replyMarkup : new ReplyKeyboardRemove());

                        return;

                    case "помощь":
                    case "/help":
                        Answer = _help;
                        break;

                    case "/info":
                    case "информация":
                        Answer = "Меня создали Миша, Дима, Дима, Глеб, Никита, Ира, Максим в рамках проектной деятельности на ФИиИТ в 2018-2019 уч. году.\n" +
                                 "Я предоставляю доступ к интерактивному расписанию мехмата через платформу ботов Telegram.\n" +
                                 "Если обнаружили ошибку в расписании, проверьте, совпадает ли оно с указанным на schedule.sfedu.ru. " +
                                 "При сопададении, для исправления обратитесь в деканат, либо напишите на [email protected], в противном случае напишите [Михаилу](tg://user?id=61026374).";
                        break;

                    case "/optionalcourses":
                    case "факультативы":
                        Answer = electivesStr;
                        break;

                    case "/curweek":
                        Answer = $"Сейчас *{CurrentSubject.GetCurrentWeek().ToString()}* неделя.";
                        break;

                    case "/forceupdate":
                        logger.Info($"Запрошено принудительное обновление расписаний, ID: {msg.Chat.Id}, @{msg.Chat.Username}.");
                        TeachersInit(false);
                        GradeInit(false);
                        GroupShedListInit(false);
                        TeachersShedInit(false);
                        WeekInit(false);
                        logger.Info($"Завершено принудительное обновление расписаний, ID: {msg.Chat.Id}, @{msg.Chat.Username}.");
                        Answer = "Данные расписаний обновлены!";
                        break;

                    default:
                        Answer = "Введены неверные данные, повторите попытку.";
                        break;
                    }
                }
                catch (System.Net.WebException e)
                {
                    logger.Error(e, "Catched exeption:");
                    Answer = "Ошибка! Вероятно, сервер интерактивного расписания недоступен. Пожалуйста, попробуйте повторить запрос позднее.";
                }
            }
            try
            {
                if (IsRegistered(msg.Chat.Id))
                {
                    await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, ParseMode.Markdown, replyMarkup : UserList[msg.Chat.Id].Info == User.UserInfo.teacher?teacherKeyboard : studentKeyboard);
                }
                else if (UserList[msg.Chat.Id].ident == 1)
                {
                    await BOT.SendTextMessageAsync(msg.Chat.Id, Answer, replyMarkup : registrationKeyboard);
                }
                else
                {
                    await BOT.SendTextMessageAsync(msg.Chat.Id, Answer);
                }
            }
            catch (Exception ex) when(ex is System.Net.Http.HttpRequestException && ex.Message.Contains("429"))
            {
                logger.Warn(ex, $"Сетевая ошибка при ответе @{msg.Chat.Username}");
            }
        }
Esempio n. 30
0
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
 {
     //Check reply_to_HLS_authentication
     if (e.Index == 1)
     {
         UInt32 ic = 0;
         byte[] secret;
         if (settings.Authentication == Authentication.HighGMAC)
         {
             secret = settings.SourceSystemTitle;
             GXByteBuffer bb = new GXByteBuffer(e.Parameters as byte[]);
             bb.GetUInt8();
             ic = bb.GetUInt32();
         }
         else
         {
             secret = Secret;
         }
         byte[] serverChallenge = GXSecure.Secure(settings, settings.Cipher, ic, settings.StoCChallenge, secret);
         byte[] clientChallenge = (byte[])e.Parameters;
         if (serverChallenge != null && clientChallenge != null && GXCommon.Compare(serverChallenge, clientChallenge))
         {
             if (settings.Authentication == Authentication.HighGMAC)
             {
                 secret = settings.Cipher.SystemTitle;
                 ic     = settings.Cipher.InvocationCounter;
             }
             else
             {
                 secret = Secret;
             }
             AssociationStatus = AssociationStatus.Associated;
             return(GXSecure.Secure(settings, settings.Cipher, ic, settings.CtoSChallenge, secret));
         }
         else //If the password does not match.
         {
             AssociationStatus = AssociationStatus.NonAssociated;
             return(null);
         }
     }
     else if (e.Index == 2)
     {
         byte[] tmp = e.Parameters as byte[];
         if (tmp == null || tmp.Length == 0)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             Secret = tmp;
         }
     }
     else if (e.Index == 3)
     {
         //Add COSEM object.
         GXDLMSObject obj = GetObject(settings, e.Parameters as object[]);
         //Unknown objects are not add.
         if (obj is IGXDLMSBase)
         {
             if (ObjectList.FindByLN(obj.ObjectType, obj.LogicalName) == null)
             {
                 ObjectList.Add(obj);
             }
             if (settings.Objects.FindByLN(obj.ObjectType, obj.LogicalName) == null)
             {
                 settings.Objects.Add(obj);
             }
         }
     }
     else if (e.Index == 4)
     {
         //Remove COSEM object.
         GXDLMSObject obj = GetObject(settings, e.Parameters as object[]);
         //Unknown objects are not removed.
         if (obj is IGXDLMSBase)
         {
             GXDLMSObject t = ObjectList.FindByLN(obj.ObjectType, obj.LogicalName);
             if (t != null)
             {
                 ObjectList.Remove(t);
             }
             //Item is not removed from all objects. It might be that use wants remove object only from association view.
         }
     }
     else if (e.Index == 5)
     {
         object[] tmp = e.Parameters as object[];
         if (tmp == null || tmp.Length != 2)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             UserList.Add(new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1])));
         }
     }
     else if (e.Index == 6)
     {
         object[] tmp = e.Parameters as object[];
         if (tmp == null || tmp.Length != 2)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             UserList.Remove(new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1])));
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
     return(null);
 }
Esempio n. 31
0
 byte[] IGXDLMSBase.Invoke(GXDLMSSettings settings, ValueEventArgs e)
 {
     //Check reply_to_HLS_authentication
     if (e.Index == 1)
     {
         UInt32 ic = 0;
         byte[] secret;
         if (settings.Authentication == Authentication.HighGMAC)
         {
             secret = settings.SourceSystemTitle;
             GXByteBuffer bb = new GXByteBuffer(e.Parameters as byte[]);
             bb.GetUInt8();
             ic = bb.GetUInt32();
         }
         else
         {
             secret = Secret;
         }
         byte[] serverChallenge = GXSecure.Secure(settings, settings.Cipher, ic, settings.StoCChallenge, secret);
         byte[] clientChallenge = (byte[])e.Parameters;
         if (serverChallenge != null && clientChallenge != null && GXCommon.Compare(serverChallenge, clientChallenge))
         {
             if (settings.Authentication == Authentication.HighGMAC)
             {
                 secret = settings.Cipher.SystemTitle;
                 ic     = settings.Cipher.InvocationCounter;
             }
             else
             {
                 secret = Secret;
             }
             settings.Connected = true;
             return(GXSecure.Secure(settings, settings.Cipher, ic, settings.CtoSChallenge, secret));
         }
         else //If the password does not match.
         {
             settings.Connected = false;
             return(null);
         }
     }
     else if (e.Index == 2)
     {
         byte[] tmp = e.Parameters as byte[];
         if (tmp == null || tmp.Length == 0)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             Secret = tmp;
         }
     }
     else if (e.Index == 5)
     {
         object[] tmp = e.Parameters as object[];
         if (tmp == null || tmp.Length != 2)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             UserList.Add(new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1])));
         }
     }
     else if (e.Index == 6)
     {
         object[] tmp = e.Parameters as object[];
         if (tmp == null || tmp.Length != 2)
         {
             e.Error = ErrorCode.ReadWriteDenied;
         }
         else
         {
             UserList.Remove(new KeyValuePair <byte, string>(Convert.ToByte(tmp[0]), Convert.ToString(tmp[1])));
         }
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
     return(null);
 }