public string CreateUser(string msg, int clientId) { string[] fields = msg.Split("$$", StringSplitOptions.RemoveEmptyEntries); string username = fields[0].Split(':', StringSplitOptions.RemoveEmptyEntries)[1]; string password = fields[1].Split(':', StringSplitOptions.RemoveEmptyEntries)[1]; string IV = fields[2].Split(':', StringSplitOptions.RemoveEmptyEntries)[1]; string keyHash = fields[3].Split(':', StringSplitOptions.RemoveEmptyEntries)[1]; DbMethods dbConnection = new DbMethods(); lock (activeUsers[clientId]) { dbConnection = activeUsers[clientId].dbConnection; } if (dbConnection.CheckIfNameExist(username)) { return(TransmisionProtocol.CreateServerMessage(ErrorCodes.USER_ALREADY_EXISTS, Options.CREATE_USER)); } password = Security.HashPassword(password); if (dbConnection.AddNewUser(username, password, IV, keyHash)) { return(TransmisionProtocol.CreateServerMessage(ErrorCodes.NO_ERROR, Options.CREATE_USER)); } else { return(TransmisionProtocol.CreateServerMessage(ErrorCodes.NO_ERROR, Options.CREATE_USER)); } }
public OutputData CheckInput(string id) { try { int?inputId = CheckIdValue(id); if (!inputId.HasValue) { throw new WebFaultException(HttpStatusCode.BadRequest); } Differ diff = new DbMethods(new DifferContext()).GetDiffer(inputId.Value); if (diff == null) { throw new WebFaultException(HttpStatusCode.NotFound); } OutputData output = new OutputData(); DifferMethods differMethods = new DifferMethods(); output.ResultType = differMethods.AreInputsEqual(diff.LeftInput, diff.RightInput).ToString(); if (output.ResultType == DiffResultType.ContentDoesNotMatch.ToString()) { output.Diffs = differMethods.ReportDiffs(diff.LeftInput, diff.RightInput); } return(output); } catch (Exception ex) { throw ex; } }
/// <summary> /// Проверить номер джампера на корректность /// </summary> /// <param name="number">Номер джампера</param> /// <returns></returns> public (bool status, string reason) CheckJumperNumber(int?number) { if (number == null) { return(false, "недопустимый номер"); } if (Jumpers.Any(j => j.Number == number)) { var dvm = new DialogViewModel("Номер уже существует, хотите ли вы поменять их местами?", DialogType.Question); WinMan.ShowDialog(dvm); switch (dvm.DialogResult) { case DialogResult.YesAction: var jumper = Jumpers.First(j => j.Number == number); jumper.Number = SelectedJumper.Number; DbMethods.UpdateDbCollection(jumper); return(true, "Операция успешно завершена"); case DialogResult.NoAction: return(false, "Данный номер уже существует"); default: return(false, "Операция отменена"); } } return(number > Jumpers.Count ? (false, "Все номера должны быть по порядку без пропусков") : (true, "Операция успешно завершена")); }
public HttpStatusCode AddInput(string id, InputData data, bool leftInput) { try { DbMethods dbMethods = new DbMethods(new DifferContext()); int? inputId = CheckIdValue(id); if (!inputId.HasValue || data.Data == null) { throw new WebFaultException <string>("Input has no value or data is null", HttpStatusCode.BadRequest); } if (leftInput) { dbMethods.AddOrUpdate(inputId.Value, data.Data); } else { dbMethods.AddOrUpdate(inputId.Value, null, data.Data); } WebOperationContext ctx = WebOperationContext.Current; if (ctx == null) { return(HttpStatusCode.Created); } ctx.OutgoingResponse.StatusCode = HttpStatusCode.Created; return(ctx.OutgoingResponse.StatusCode); } catch (Exception ex) { throw ex; } }
public ClientProcessing() { functions = new List <Functions>(); functions.Add(new Functions(Logout)); functions.Add(new Functions(Login)); functions.Add(new Functions(CreateUser)); functions.Add(new Functions(CheckUserName)); functions.Add(new Functions(Disconnect)); functions.Add(new Functions(GetFriends)); functions.Add(new Functions(SendConversation)); functions.Add(new Functions(ActivateConversation)); functions.Add(new Functions(SendMessage)); functions.Add(new Functions(NewMessages)); functions.Add(new Functions(Notification)); functions.Add(new Functions(AddFriend)); functions.Add(new Functions(DhExchange)); functions.Add(new Functions(SendInvitations)); functions.Add(new Functions(DeclineFriend)); functions.Add(new Functions(AcceptFriend)); functions.Add(new Functions(SendConversationKey)); functions.Add(new Functions(SendAcceptedFriends)); dbMethods = new DbMethods(); activeUsers = new List <User>(); invitations = dbMethods.GetInvitations(); messagesToSend = new Dictionary <int, Dictionary <int, List <Message> > >(); notifications = new Dictionary <int, Dictionary <int, Notification> >(); activeConversations = new Dictionary <int, int>(); }
public Film_s_Page(DbMethods _methods, Film _film) { InitializeComponent(); methods = _methods; film = _film; FilmTitle.Text = film.Title; Description.Text = film.Description; string actors; foreach (var a in film.Actors) { Actors.Text += a.Name; if (a != film.Actors.Last()) { Actors.Text += ","; } } string stringpath = film.PosterLink; Uri imageuri = new Uri(stringpath, UriKind.Relative); BitmapImage imagebitmap = new BitmapImage(imageuri); Poster.Source = imagebitmap; if (methods.User.FavFilms.Any(f => f.Title == film.Title) == true) { AddtoFavourites.Visibility = Visibility.Collapsed; DeleteFromFavourites.Visibility = Visibility.Visible; } if (methods.User.FavFilms.Any(f => f.Title == film.Title) == false) { AddtoFavourites.Visibility = Visibility.Visible; DeleteFromFavourites.Visibility = Visibility.Collapsed; } }
/// <summary> /// Обработка команды ShowStat /// </summary> /// <param name="command"></param> private void CommandShowStat(Command command) { string channelName = command.GetParam("name"); if (string.IsNullOrWhiteSpace(channelName)) { Debug.Error("Введите параметр [username=ChannelName]!"); return; } using (Db db = new Db(HelperDatabase.DB_OPTIONS)) { TelegramChannel channel = DbMethods.GetChannelFromDb(db, channelName); if (channel == null) { Debug.Error($"В базе данных нет канала [{channelName}]"); return; } //Получить статистику по подписчикам string subsStat = DbMethods.GetSubscribersStatistics(db, channel); string postStat = DbMethods.GetViewsStatistics(db, channel); Debug.Log($"\n{subsStat}\n\n{postStat}\n"); } }
public ClientProcessing() { syncFunctions = new Dictionary <Options, Functions>(); asyncFunctions = new Dictionary <Options, AsyncFunctions>(); syncFunctions.Add(Options.LOGOUT, new Functions(Logout)); syncFunctions.Add(Options.LOGIN, new Functions(Login)); syncFunctions.Add(Options.CREATE_USER, new Functions(CreateUser)); syncFunctions.Add(Options.CHECK_USER_NAME, new Functions(CheckUserName)); syncFunctions.Add(Options.GET_FRIENDS, new Functions(GetFriends)); syncFunctions.Add(Options.DELETE_ACCOUNT, new Functions(DeleteAccount)); syncFunctions.Add(Options.ADD_FRIEND, new Functions(AddFriend)); syncFunctions.Add(Options.ACCEPT_FRIEND, new Functions(AcceptFriend)); syncFunctions.Add(Options.DECLINE_FRIEND, new Functions(DeclineFriend)); asyncFunctions.Add(Options.ACTIVE_FRIENDS, new AsyncFunctions(SendActiveFriends)); asyncFunctions.Add(Options.FRIEND_INVITATIONS, new AsyncFunctions(SendInvitations)); asyncFunctions.Add(Options.INCOMMING_CALL, new AsyncFunctions(SendCall)); dbMethods = new DbMethods(); activeUsers = new List <User>(); eventHandlers = new Dictionary <string, EventWaitHandle>(); userLoginHandler = new Dictionary <int, EventWaitHandle>(); invitations = dbMethods.GetInvitations(); userInvitationsIds = dbMethods.GetUsersInvitationsIds(); whichFunction = new Dictionary <string, List <Tuple <Options, string> > >(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; }); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); // Allow CORS app.UseCors("mypolicy"); app.UseAuthentication(); app.UseAuthorization(); DbMethods.InitializeDB(); app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireCors("mypolicy"); }); }
protected override void Delete(SimpleActionExecuteEventArgs args) { //окно с предупреждением уже прошло //здесь будет проверка на возможность удаления объекта //если элемент нужно снять с регистрации, то это лучше сделать здесь int _idTypeDirectory = 0; int _idCataloge = 0; IRegistrationObject _regObject = args.CurrentObject as IRegistrationObject; if (_regObject != null) { _idTypeDirectory = _regObject.GetIdTypeDirectory(); _idCataloge = _regObject.GetIdCatalog(); } base.Delete(args); if (_idTypeDirectory > 0 && _idCataloge > 0) { if (!DbMethods.UnRegistration( _idTypeDirectory, _idCataloge )) { return; } } }
public string CreateUser(string msg, int clientId) { // Get message as object Login login = MessageProccesing.DeserializeObject(msg) as Login; // Check if user doesnt already exists in DB DbMethods dbConnection = new DbMethods(); lock (activeUsers[clientId]) { dbConnection = activeUsers[clientId].dbConnection; } if (dbConnection.CheckIfNameExist(login.username)) { return(MessageProccesing.CreateMessage(ErrorCodes.USER_ALREADY_EXISTS)); } // Hash password login.passwordHash = Security.HashPassword(login.passwordHash); if (dbConnection.AddNewUser(login.username, login.passwordHash)) { return(MessageProccesing.CreateMessage(ErrorCodes.NO_ERROR)); } else { return(MessageProccesing.CreateMessage(ErrorCodes.NO_ERROR)); } }
public void AddressInfoCheck(AddressInfo addressInfo) { var episode = DbMethods.GetEpisodeFromDbById(addressInfo.Episode.Id); episode.AddressInfo = addressInfo; DbMethods.UpdateDbCollection(episode); AddressInfoList = new BindableCollection <AddressInfo>(SelectedEpisode.AddressInfoList); }
public User() { userName = ""; dbConnection = new DbMethods(); redis = new Redis(); activeConversation = -1; logged = false; }
public FavouritesWindow(DbMethods _methods) { InitializeComponent(); methods = _methods; dataGridFavourites.ItemsSource = methods.User.FavFilms; }
public void AddressInfoUncheck(AddressInfo addressInfo) { var episode = DbMethods.GetEpisodeFromDbById(addressInfo.Episode.Id); episode.AddressInfo = AddressInfoList.FirstOrDefault(a => a.Id != addressInfo.Id); DbMethods.UpdateDbCollection(episode); AddressInfoList = new BindableCollection <AddressInfo>(SelectedEpisode.AddressInfoList); }
public void RunBeforeAnyTests() { _testContext = new DifferContext(); // Clear table so each test has the same starting point. _testContext.Database.ExecuteSqlCommand("TRUNCATE TABLE [Differs]"); _testContext = new DifferContext(); _sut = new DbMethods(_testContext); }
static void Main(string[] args) { DbMethods m = new DbMethods(); Console.WriteLine(TransmisionProtocol.CreateServerMessage(0, 1, m.GetMatchHistoryData("test"))); //ServerConnection server = new ServerConnection(); //server.RunServer(); }
/// <summary> /// Запускаем ежечасно, желательно в отдельном потоке, поставить приоритет потока на высокий, а потом выполнять параллельно. /// </summary> public void Process(object intChannelDelaySeconds) { this.RequestsDelaySeconds = (int)intChannelDelaySeconds; using (Db db = new Db(HelperDatabase.DB_OPTIONS)) { //1) Взять из базы список всех каналов. List <TelegramChannel> channels = DbMethods.GetAllChannels(db); if (channels == null || channels.Count == 0) { Debug.Error("Нет каналов в базе для сбора статистики!"); return; } //Thread.Sleep(this.RequestsDelaySeconds); Thread.Sleep(new Random(Convert.ToInt32(DateTime.Now.Ticks % 100000)).Next(10, 20) * 1000); //Запускаем цикл по каналам //Получить запросом канал Добавить в базу кол-во подписчиков канала на текущий час. foreach (var channel in channels) { Debug.Log($"Берем статистику канала [{channel.Username}]"); var channelInfo = ChannelMethods.GetAllInfoChannel(GlobalVars.Client, channel.Username).Result; DbMethods.AddStatisticsChannelToDb(db, channelInfo); //Взять все посты у канала, через запрос. var posts = ChannelMethods.GetAllPosts(GlobalVars.Client, channel.Username).Result; foreach (var post in posts) { var p = post as TLMessage; if (Equals(p, null)) { continue; } //Если пост новый и еще не добавлен в базу, то добавить в базу. TelegramPost telePost = DbMethods.AddTelegramPostIfNeed(db, channel, p); DbMethods.AddStatisticsPostToDb(db, channel, p); } //Делаем задержку по времени, чтобы не банили запросы за превыщение лимита //Берем данные по каналу, по его постам и делаем задержку. //Thread.Sleep(this.RequestsDelaySeconds * 1000); Thread.Sleep(new Random(Convert.ToInt32(DateTime.Now.Ticks % 100000)).Next(10, 20) * 1000); } Debug.Log("Сбор статистики завершен!"); } }
/// <summary> /// Creates a new data field in the Mdb table. /// Any pending changes to the collection will be lost. /// </summary> /// <param name="fieldName">The string name of the field to be added. Spaces in the field name are replaced.</param> /// <param name="typeName">The data type of the field to be added. Default is TEXT(255).</param> public virtual void AddDataField(string fieldName, string typeName = "TEXT(255)") { if (Table.Columns.Contains(fieldName)) { return; } DbMethods.AddDbField(Application.MdbPath, Table.TableName, fieldName, typeName); Application.MdbDatabase = null; Refresh(); }
public Expert getAllTheExpertInfo(string tuid) { DbMethods DbMethods = new DbMethods(); Expert expertProfileObj = new Expert(); //add information from ExpertProfile table DataSet expertInfoDS = DbMethods.GetExpertInfo(tuid); expertProfileObj.tuID = expertInfoDS.Tables[0].Rows[0][0].ToString(); expertProfileObj.firstName = expertInfoDS.Tables[0].Rows[0][3].ToString(); expertProfileObj.lastName = expertInfoDS.Tables[0].Rows[0][2].ToString(); expertProfileObj.username = expertInfoDS.Tables[0].Rows[0][1].ToString(); expertProfileObj.email = expertInfoDS.Tables[0].Rows[0][4].ToString(); expertProfileObj.dateJoined = Convert.ToDateTime(expertInfoDS.Tables[0].Rows[0][5].ToString()); expertProfileObj.phoneNumber = expertInfoDS.Tables[0].Rows[0][6].ToString(); expertProfileObj.aboutMe = expertInfoDS.Tables[0].Rows[0][7].ToString(); expertProfileObj.college = expertInfoDS.Tables[0].Rows[0][8].ToString(); expertProfileObj.major = expertInfoDS.Tables[0].Rows[0][9].ToString(); expertProfileObj.linkedIn = expertInfoDS.Tables[0].Rows[0][10].ToString(); expertProfileObj.isActive = Convert.ToBoolean(expertInfoDS.Tables[0].Rows[0][12].ToString()); expertProfileObj.skillGroupID = Convert.ToInt32(expertInfoDS.Tables[0].Rows[0][13].ToString()); expertProfileObj.genderID = Convert.ToInt32(expertInfoDS.Tables[0].Rows[0][14].ToString()); expertProfileObj.ethnicityID = Convert.ToInt32(expertInfoDS.Tables[0].Rows[0][15].ToString()); expertProfileObj.lastUpdateDate = Convert.ToDateTime(expertInfoDS.Tables[0].Rows[0][16].ToString()); expertProfileObj.lastUpdateUser = expertInfoDS.Tables[0].Rows[0][17].ToString(); expertProfileObj.picture = (byte[])expertInfoDS.Tables[0].Rows[0][11]; //add skill group name expertProfileObj.SkillGroupName = DbMethods.GetSkillGroupName(expertProfileObj.skillGroupID).ToString(); //add roles and venture names DataSet roleAndVentureNameDS = DbMethods.GetExpertRoleAndVenture(tuid); for (int i = 0; i < roleAndVentureNameDS.Tables[0].Select().Length; i++) { string role = roleAndVentureNameDS.Tables[0].Rows[i][0].ToString(); string ventureName = roleAndVentureNameDS.Tables[0].Rows[i][1].ToString(); expertProfileObj.roleVentureNameList.Add(new Tuple <string, string>(ventureName, role)); } //get all expert sklls and add them to the expert object DataTable expertSklls = DbMethods.GetExpertsSkills(tuid).Tables[0]; for (int z = 0; z < expertSklls.Rows.Count; z++) { int SkillID = Convert.ToInt32(expertSklls.Rows[z][0]); string SkillName = expertSklls.Rows[z][1].ToString(); expertProfileObj.AllExpertSkills.Add(new Tuple <int, string>(SkillID, SkillName)); } return(expertProfileObj); }
public string CheckUserName(string msg, int clientId) { string[] fields = msg.Split("$$"); string username = fields[0].Split(':')[1]; DbMethods dbConnection = new DbMethods(); lock (activeUsers[clientId]) { dbConnection = activeUsers[clientId].dbConnection; } if (!dbConnection.CheckIfNameExist(username)) { return(TransmisionProtocol.CreateServerMessage(ErrorCodes.NO_ERROR, Options.CHECK_USER_NAME)); } return(TransmisionProtocol.CreateServerMessage(ErrorCodes.USER_ALREADY_EXISTS, Options.CHECK_USER_NAME)); }
public void storeVentureDataInSession(int ventureID) { DbMethods DbMethods = new DbMethods(); Venture ventureObj = new Venture(); ventureObj = DbMethods.GetVenture(ventureID); //store all wanted skills DataSet allVentureSkills = DbMethods.GetVentureSkills(ventureID); for (int i = 0; i < allVentureSkills.Tables[0].Select().Length; i++) { int SkillID = (int)allVentureSkills.Tables[0].Rows[i][0]; string SkillName = allVentureSkills.Tables[0].Rows[i][1].ToString(); ventureObj.AllVentureSkills.Add(new Tuple <int, string>(SkillID, SkillName)); } //store members and roles DataSet ventureMembersAndRolesDS = DbMethods.GetVentureMembersAndRoles(ventureID); for (int i = 0; i < ventureMembersAndRolesDS.Tables[0].Select().Length; i++) { string role = ventureMembersAndRolesDS.Tables[0].Rows[i][0].ToString(); string firstName = ventureMembersAndRolesDS.Tables[0].Rows[i][1].ToString(); string lastName = ventureMembersAndRolesDS.Tables[0].Rows[i][2].ToString(); string memberName = firstName + " " + lastName; string username = ventureMembersAndRolesDS.Tables[0].Rows[i][3].ToString(); ventureObj.memberNameAndRoleList.Add(new Tuple <string, string, string>(username, memberName, role)); } //store static members and roles DataSet staticMembersAndRolesDS = DbMethods.GetAllStaticMembersByVentureID(ventureID); for (int i = 0; i < staticMembersAndRolesDS.Tables[0].Select().Length; i++) { int StaticMemberID = (int)staticMembersAndRolesDS.Tables[0].Rows[i][0]; string firstName = staticMembersAndRolesDS.Tables[0].Rows[i][1].ToString(); string lastName = staticMembersAndRolesDS.Tables[0].Rows[i][2].ToString(); string role = staticMembersAndRolesDS.Tables[0].Rows[i][3].ToString(); string staticMemberName = firstName + " " + lastName; ventureObj.staticMembersList.Add(new Tuple <string, string, int>(staticMemberName, role, StaticMemberID)); } //store object in session Session["ventureObj"] = ventureObj; }
static void Main(string[] args) { DbMethods dbMethods = new DbMethods("Accounts"); Log log = new Log(); string fileName; for (int i = 1; i < 111; i++) { fileName = i.ToString(); ImportTXT importTXT = new ImportTXT(@"C:\Users\fcermak\Downloads\Exploit.in\" + fileName + ".txt"); } Console.ReadLine(); }
public Game(DbMethods _methods) { InitializeComponent(); methods = _methods; films = methods.GetAllFilms(); Film film = new Film(); film = films[0]; string stringpath = film.PhotoLink1; Uri imageuri = new Uri(stringpath, UriKind.Relative); BitmapImage imagebitmap = new BitmapImage(imageuri); FilmImage.Source = imagebitmap; }
public string CheckUserName(string msg, int clientId) { // Get message as object Username username = MessageProccesing.DeserializeObject(msg) as Username; // Check if user doesnt already exists in DB DbMethods dbConnection = new DbMethods(); lock (activeUsers[clientId]) { dbConnection = activeUsers[clientId].dbConnection; } if (!dbConnection.CheckIfNameExist(username)) { return(MessageProccesing.CreateMessage(ErrorCodes.NO_ERROR)); } return(MessageProccesing.CreateMessage(ErrorCodes.USER_ALREADY_EXISTS)); }
/// <summary> /// Установить значение фильмов /// </summary> /// <param name="value">Тип фильма</param> public void SetFilms(FilmType?value) { Films = value == null ? new BindableCollection <Film>() : new BindableCollection <Film>(DbMethods.GetDbCollection <Film>() .FindAll(film => film.FilmType == value).OrderBy(f => f.Name)) { new Film { Name = NewFilmName, FilmType = SelectedFilmType ?? FilmType.Видео } }; SelectedFilm = null; NotifyOfPropertyChange(() => Films); NotifyOfPropertyChange(() => CanCancelFilmTypeSelection); NotifyOfPropertyChange(() => FilmsVisibility); }
public async Task <IActionResult> deleteRatingsAsync([FromBody] UserCred userCred, [FromHeader] string Authorization) { int movieId = userCred.MovieId; string email = tokenObj.GetNameClaims(Authorization); if (!(await RatingMethods.deleteRatingAsync(movieId, email))) { return(NotFound()); } string json = JsonConvert.SerializeObject("200: description: Successfully deleted rating", Formatting.Indented); await DbMethods.dbcloseAsync(); return(Ok(json)); }
public async Task <IActionResult> GetMovieUserRatingsAsync([FromHeader] string Authorization, int movieId, int page) { string email = tokenObj.GetNameClaims(Authorization); Dictionary <string, string> dictionary = new Dictionary <string, string>(); Rating rating = await RatingMethods.getMovieSingleRatingAsync(movieId, email); if (rating == null) { dictionary.Add("Message:", "NotFound"); dictionary.Add("Description:", "Rating not found"); return(NotFound(dictionary)); } await DbMethods.dbcloseAsync(); return(Ok(JsonConvert.SerializeObject(rating, Formatting.Indented))); }
public FilmsEditingViewModel(Film film) { CurrentFilm = film; if (film.Id != 0) { OriginalFilm = DbMethods.GetFilmFromDbById(film.Id); NotifyOfPropertyChange(() => CanSelectSeason); } Seasons = film.Id != 0 ? new BindableCollection <Season>(OriginalFilm.Seasons) : new BindableCollection <Season>(); SelectedSeason = Seasons.FirstOrDefault(); NotifyOfPropertyChange(() => CreateFilmVisibility); NotifyOfPropertyChange(() => SaveChangesVisibility); }
public async Task <IActionResult> GetMovieAverageAsync(int movieId) { Dictionary <string, decimal> retDict = await RatingMethods.getMovieAverageAsync(movieId); if (retDict["percentage"] == -1) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("Message:", "NotFound"); dictionary.Add("Description:", "Ratings not found"); return(NotFound(dictionary)); } string json = JsonConvert.SerializeObject(retDict, Formatting.Indented); await DbMethods.dbcloseAsync(); return(Ok(json)); }