public async Task<IdentityResult> RegisterUser(Account userModel) { IdentityUser user = new IdentityUser { UserName = userModel.username }; var result = await _userManager.CreateAsync(user, userModel.password); if (result.Succeeded) { using (var db = new MemoryDB()) { User newUser = new User(); List<Media> mediaList = new List<Media>(); List<User> friendList = new List<User>(); newUser.friendList = friendList; newUser.username = userModel.username; newUser.email = userModel.email; newUser.mediaList = mediaList; db.User.Add(newUser); db.SaveChanges(); } } return result; }
public void MemoryDBShouldBeEnumerable(int repeats) { // memdb var db = new MemoryDB(); // 랜덤키 밸류 생성 Dictionary <byte[], byte[]> expected = new Dictionary <byte[], byte[]>(new ByteArrayComparer()); for (int i = 0; i < repeats; i++) { expected.Add(SecureRandom.GetBytes(32), SecureRandom.GetBytes(64)); } // insert to db foreach (var kv in expected) { db.Put(kv.Key, kv.Value); } // enumerate int items = 0; foreach (var kv in db.AsEnumerable()) { byte[] key = kv.Key; byte[] value = kv.Value; Assert.True(expected.ContainsKey(key)); Assert.Equal(expected[key], value); items++; } Assert.Equal(expected.Count, items); }
/// <summary> /// 根据属性查询数据。框架已经给对象的所有属性做了索引。 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="propertyName">属性名称</param> /// <param name="val">属性的值</param> /// <returns>返回数据列表</returns> public static List <T> findBy <T>(String propertyName, Object val) where T : CacheObject { findAll <T>(); IList list = MemoryDB.FindBy(typeof(T), propertyName, val); return(db.getResults <T>(list)); }
// DELETE api/media/5 public void Delete(int id) { var identity = User.Identity as System.Security.Claims.ClaimsIdentity; string username = identity.Claims.ElementAt(0).Value; using (var db = new MemoryDB()) { var media = (from m in db.Media where m.id == id select m).SingleOrDefault(); var user = (from u in db.User where u.id == media.user.id select u).SingleOrDefault(); if (media != null && user != null) { try { db.Media.Remove(media); db.SaveChanges(); } catch (Exception e) { var responseErrorMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(responseErrorMsg); } } else { throw new HttpResponseException(HttpStatusCode.NotFound); } } }
async public Task <HttpResponseMessage> SavePlayer(GameResultViewModel player) { List <string> errors = new List <string>(); var game = db.games.Where(g => g.GameId == player.GameId).SingleOrDefault(); if (game == null) { errors.Add("No such game found"); } // no errors if (errors.Count == 0) { try { game.Player = player.Player; await db.SaveChangesAsync(); // update cache for top players list foreach (var item in MemoryDB.GetTopPlayers()) { if (item.Value == game.GameId) { item.Key.Name = game.Player; } } return(Request.CreateResponse(HttpStatusCode.Accepted)); } catch { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } } else { return(Request.CreateResponse <List <string> >(HttpStatusCode.BadRequest, errors)); } }
// /api/v1/user/<username> // GET: Returns the user with username <username>. public User Get(String username) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User where us.username == username select us).FirstOrDefault(); if (dbUser == null) { var responseMsg = new HttpResponseMessage { Content = new StringContent("There was no user found.") }; throw new HttpResponseException(responseMsg); } else { return dbUser; } } }
/// <summary> /// 从内存中删除数据,并同步磁盘中内容。 /// </summary> /// <param name="obj"></param> public static void delete(CacheObject obj) { MemoryDB.Delete(obj); }
/// <summary> /// 更新对象,并将对象同步持久化的磁盘,同时更新索引 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static Result update(CacheObject obj) { return(MemoryDB.Update(obj)); }
/// <summary> /// 插入时,只针对特定属性做索引,提高速度 /// </summary> /// <param name="propertyName">需要做索引的属性</param> /// <param name="pValue">属性的值</param> public static void insertByIndex(CacheObject obj, String propertyName, Object pValue) { MemoryDB.InsertByIndex(obj, propertyName, pValue); }
async public Task <HttpResponseMessage> SaveGame(GameResultViewModel result) { var modelStateErrors = ModelState.Values.ToList(); List <string> errors = new List <string>(); foreach (var s in modelStateErrors) { foreach (var e in s.Errors) { if (e.ErrorMessage != null && e.ErrorMessage.Trim() != "") { errors.Add(e.ErrorMessage); } } } var cacheProvider = new InMemoryCache(); var game = (Game)HttpContext.Current.Cache[result.GameId.ToString()]; if (game == null) { errors.Add("The game has expired."); } if (game == null || game.Ip != HttpContext.Current.Request.UserHostAddress || game.GameId != result.GameId || (DateTime.UtcNow - game.DateCreated).TotalMilliseconds < result.Time) { errors.Add("This is not a valid game."); } if (errors.Count == 0) { //try //{ // store the result db.games.Add(new GameHistory { Ip = game.Ip, Player = result.Player, Time = result.Time, GameId = result.GameId, Moves = null //TODO }); // remove the game from cache cacheProvider.Remove(game.GameId.ToString()); await db.SaveChangesAsync(); MemoryDB.AddTopPlayers(new TopPlayer { Name = result.Player, Time = result.Time }, game.GameId); return(Request.CreateResponse(HttpStatusCode.Accepted)); //} //catch //{ // return Request.CreateResponse(HttpStatusCode.InternalServerError); //} } else { return(Request.CreateResponse <List <string> >(HttpStatusCode.BadRequest, errors)); } }
// POST: Adds a user as a friend to the user with username <username>. //public IHttpActionResult Post(String id, String modifier, [FromBody]String friendsname) //{ // string username = id; // if (modifier.Equals("friends")) // { // using (var db = new MemoryDB()) // { // var dbUser = (from us in db.User.Include("friendList") where us.username == username select us).SingleOrDefault(); // var dbFriend = (from us in db.User where us.username == friendsname select us).SingleOrDefault(); // if ((dbUser != null) && (dbFriend != null)) // { // try // { // dbUser.friendList.Add(dbFriend); // db.SaveChanges(); // return Ok("Friend was successfully added."); // } // catch (Exception e) // { // var responseErrorMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; // throw new HttpResponseException(responseErrorMsg); // } // } // else // { // var responseMsg = new HttpResponseMessage { Content = new StringContent("User not found or friend not found.") }; // throw new HttpResponseException(responseMsg); // } // } // } // else // { // var responseMsg = new HttpResponseMessage { Content = new StringContent("You did not use the correct modifier.") }; // throw new HttpResponseException(responseMsg); // } //} // /api/v1/user/<username>/media // GET: Returns a list of media the user with username <username> has. /*public List<Media> Get(String username, String modifier) { if (modifier.Equals("media")) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User.Include("mediaList") where us.username == username select us).SingleOrDefault(); if (dbUser != null) { return dbUser.mediaList.ToList(); } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("The user was not found.") }; throw new HttpResponseException(responseMsg); } } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("You did not use the correct modifier.") }; throw new HttpResponseException(responseMsg); } }*/ // /api/v1/user/<username>/friends/<friendsUsername> // DELETE: Removes the user with username <friendsUsername> as a friend to the user with username <username>. public IHttpActionResult Delete(String id, String modifier, String id2) { string username = id; string friendsUsername = id2; if (modifier.Equals("friends")) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User.Include("friendList") where us.username == username select us).SingleOrDefault(); var dbFriend = (from us in db.User where us.username == friendsUsername select us).SingleOrDefault(); if ((dbUser != null) && (dbFriend != null)) { dbUser.friendList.Remove(dbFriend); db.SaveChanges(); return Ok("Friend has been successfully removed."); } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("User not found or friend not found.") }; throw new HttpResponseException(responseMsg); } } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("The modifier was incorrect.") }; throw new HttpResponseException(responseMsg); } }
/// <summary> /// 查询类型 T 的所有数据 /// </summary> /// <typeparam name="T"></typeparam> /// <returns>返回所有数据的列表</returns> public static List <T> findAll <T>() where T : CacheObject { IList list = MemoryDB.FindAll(typeof(T)); return(db.getResults <T>(list)); }
public void ClearMemoryDB() { MemoryDB.Clear(); }
public AuthRepository() { _ctx = new MemoryDB(); _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx)); }
// DELETE: Deletes everything related to the user with username <username>. public IHttpActionResult Delete(String username) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User.Include("mediaList") where us.username == username select us).FirstOrDefault(); if (dbUser != null) { try { foreach (var media in dbUser.mediaList) { dbUser.mediaList.Remove(media); } db.User.Remove(dbUser); db.SaveChanges(); return Ok("User has been successfully deleted."); } catch (Exception e) { var responseErrorMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(responseErrorMsg); } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("The user was not found.") }; throw new HttpResponseException(responseMsg); } } }
/// <summary> /// 根据 id 查询某条数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns>返回某条数据</returns> public static T findById <T>(int id) where T : CacheObject { Object obj = MemoryDB.FindById(typeof(T), id); return((T)obj); }
// /api/v1/user/<username>/<modifier> (friends, media, media-object) // GET (friends): Returns a list of friends the user with username <username> has. // GET (media): Returns a list of media the user with username <username> has. public object Get(String id, String modifier) { string username = id; if (modifier.Equals("friends")) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User.Include("friendList") where us.username == username select us).SingleOrDefault(); if (dbUser != null) { return dbUser.friendList.ToList(); } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("The user was not found.") }; throw new HttpResponseException(responseMsg); } } } else if (modifier.Equals("media")) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User.Include("mediaList") where us.username == username select us).SingleOrDefault(); if (dbUser != null) { return dbUser.mediaList.ToList(); } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("The user was not found.") }; throw new HttpResponseException(responseMsg); } } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("You did not use the correct modifier.") }; throw new HttpResponseException(responseMsg); } }
/// <summary> /// 插入数据,并对所有属性做索引,速度较慢。新插入的数据会被同步持久化到磁盘。 /// </summary> public static void insert(CacheObject obj) { MemoryDB.Insert(obj); }
// /api/v1/user/<username>/media-objects // GET: Returns a list of media objects for the user. /*public List<Media> Get(String username, String modifier) { if (modifier.Equals("media-objects")) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User where us.username == username select us).SingleOrDefault(); if (dbUser == null) { var responseMsg = new HttpResponseMessage { Content = new StringContent("There was no user found.") }; throw new HttpResponseException(responseMsg); } var dbMedia = (from me in db.Media where me.user.id == dbUser.id select me).ToList(); if (dbMedia == null) { var responseMsg = new HttpResponseMessage { Content = new StringContent("There were no media files found.") }; throw new HttpResponseException(responseMsg); } else { return dbMedia; } } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("The modifier was not correct.") }; throw new HttpResponseException(responseMsg); } }*/ // /api/v1/user/<username>/<modifier> (sounds, videos, pictures) // POST: Create new media file. In body must be either "sound-file", "video-file" or "picture-file". public IHttpActionResult Post(String id, String modifier,[FromBody]String id2) { string username = id; string friendsname = id2; string bucketName = "memorybucket"; string awsAccessKeyId = ""; string awsSecretAccessKey = ""; string URLforFile = "http://memoryapi-dev.elasticbeanstalk.com/"; var DB = new MemoryDB(); User userObj = DB.User.FirstOrDefault(x => x.username == username); if(modifier.Equals("pictures")) { var uploadFile = HttpContext.Current.Request.Files["picture-file"]; if ((uploadFile != null) && (uploadFile.ContentLength > 0)) { byte[] dataArr = new byte[uploadFile.ContentLength]; uploadFile.InputStream.Read(dataArr, 0, uploadFile.ContentLength); Stream stream = new MemoryStream(dataArr); var fileName = Convert.ToString(DateTime.Now.ToFileTime()); string file = uploadFile.FileName; string fileType = file.Substring(file.IndexOf('.') + 1); var pictureObj = new PictureMedia { fileUrl = URLforFile + fileName + "." + fileType, container = uploadFile.ContentType, width = Convert.ToInt32(HttpContext.Current.Request.QueryString["width"]), height = Convert.ToInt32(HttpContext.Current.Request.QueryString["height"]) }; try { using (var ac = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, Amazon.RegionEndpoint.EUCentral1)) { ac.PutObject(new PutObjectRequest() { InputStream = stream, BucketName = bucketName, Key = fileName + "." + fileType }); } } catch (Exception e) { var errorResponseMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(errorResponseMsg); } using (var db = new MemoryDB()) { try { userObj.mediaList.Add(pictureObj); db.SaveChanges(); return Ok("The picture file has been uploaded."); } catch (Exception e) { var errorResponseMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(errorResponseMsg); } } } } if (modifier.Equals("sounds")) { var uploadFile = HttpContext.Current.Request.Files["sound-file"]; if ((uploadFile != null) && (uploadFile.ContentLength > 0)) { byte[] dataArr = new byte[uploadFile.ContentLength]; uploadFile.InputStream.Read(dataArr, 0, uploadFile.ContentLength); Stream stream = new MemoryStream(dataArr); var fileName = Convert.ToString(DateTime.Now.ToFileTime()); string file = uploadFile.FileName; string fileType = file.Substring(file.IndexOf('.') + 1); var soundObj = new SoundMedia { fileUrl = URLforFile + fileName + "." + fileType, container = uploadFile.ContentType, duration = Convert.ToInt32(HttpContext.Current.Request.QueryString["duration"]), codec = Convert.ToString(HttpContext.Current.Request.QueryString["codec"]), bitRate = Convert.ToInt32(HttpContext.Current.Request.QueryString["bitrate"]), channels = Convert.ToInt32(HttpContext.Current.Request.QueryString["channels"]), samplingRate = Convert.ToInt32(HttpContext.Current.Request.QueryString["samplingrate"]) }; try { using (var ac = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, Amazon.RegionEndpoint.EUCentral1)) { ac.PutObject(new PutObjectRequest() { InputStream = stream, BucketName = bucketName, Key = fileName + "." + fileType }); } } catch (Exception e) { var errorResponseMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(errorResponseMsg); } using (var db = new MemoryDB()) { try { userObj.mediaList.Add(soundObj); db.SaveChanges(); return Ok("The sound file has been uploaded."); } catch (Exception e) { var errorResponseMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(errorResponseMsg); } } } } if (modifier.Equals("videos")) { var uploadFile = HttpContext.Current.Request.Files["video-file"]; if ((uploadFile != null) && (uploadFile.ContentLength > 0)) { byte[] dataArr = new byte[uploadFile.ContentLength]; uploadFile.InputStream.Read(dataArr, 0, uploadFile.ContentLength); Stream stream = new MemoryStream(dataArr); var fileName = Convert.ToString(DateTime.Now.ToFileTime()); string file = uploadFile.FileName; string fileType = file.Substring(file.IndexOf('.'), +1); var videoObj = new VideoMedia { fileUrl = URLforFile + fileName + "." + fileType, container = uploadFile.ContentType, width = Convert.ToInt32(HttpContext.Current.Request.QueryString["width"]), height = Convert.ToInt32(HttpContext.Current.Request.QueryString["height"]), videoCodec = Convert.ToString(HttpContext.Current.Request.QueryString["videocodec"]), videoBitRate = Convert.ToInt32(HttpContext.Current.Request.QueryString["videobitrate"]), frameRate = Convert.ToInt32(HttpContext.Current.Request.QueryString["framerate"]), audioCodec = Convert.ToString(HttpContext.Current.Request.QueryString["audiocodec"]), audioBitRate = Convert.ToInt32(HttpContext.Current.Request.QueryString["audiobitrate"]), samplingRate = Convert.ToInt32(HttpContext.Current.Request.QueryString["samplingRate"]) }; try { using (var ac = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, Amazon.RegionEndpoint.EUCentral1)) { ac.PutObject(new PutObjectRequest() { InputStream = stream, BucketName = bucketName, Key = fileName + "." + fileType }); } } catch (Exception e) { var errorResponseMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(errorResponseMsg); } using (var db = new MemoryDB()) { try { userObj.mediaList.Add(videoObj); db.SaveChanges(); return Ok("The video file has been uploaded."); } catch (Exception e) { var errorResponseMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(errorResponseMsg); } } } if (modifier.Equals("friends")) { using (var db = new MemoryDB()) { var dbUser = (from us in db.User.Include("friendList") where us.username == username select us).SingleOrDefault(); var dbFriend = (from us in db.User where us.username == friendsname select us).SingleOrDefault(); if ((dbUser != null) && (dbFriend != null)) { try { dbUser.friendList.Add(dbFriend); db.SaveChanges(); return Ok("Friend was successfully added."); } catch (Exception e) { var responseErrorMsg = new HttpResponseMessage { Content = new StringContent(string.Format("This is wrong: {0}", e)) }; throw new HttpResponseException(responseErrorMsg); } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("User not found or friend not found.") }; throw new HttpResponseException(responseMsg); } } } else { var responseMsg = new HttpResponseMessage { Content = new StringContent("You did not use the correct modifier.") }; throw new HttpResponseException(responseMsg); } } var lastErrorMsg = new HttpResponseMessage { Content = new StringContent(string.Format("The modifier was wrong, please state the correct one!")) }; throw new HttpResponseException(lastErrorMsg); }
public IList <TopPlayer> TopPlayers() { return(MemoryDB.GetTopPlayers().Keys); }