public ActionResult Index() { List <PostDisplay> postsList = null; var identity = (ClaimsIdentity)User.Identity; var id = identity.Claims.FirstOrDefault(x => x.Value == "Id"); var result = int.TryParse(id?.ValueType, out var intOut); if (result) { using (var db = new SocialContext()) { var query = db.Friends.Where(x => x.UserId0 == intOut).ToList(); var joinQuery = from post in db.Posts join friend in db.Friends on post.UserId equals friend.UserId1 where friend.UserId0.Equals(intOut) select new PostDisplay() { Text = post.Text, User = db.Users.FirstOrDefault(x => x.Id == post.UserId).Name, Posted = post.Posted }; //produces flat sequence postsList = joinQuery.OrderBy(x => x.Posted).ToList(); } } ViewBag.Title = "Default"; return(View(postsList)); }
public async Task <ActionResult> Login(LoginInfo modeLogin) { if (!ModelState.IsValid) { return(View()); } using (var db = new SocialContext()) { var verifyUser = await db.Users.FirstOrDefaultAsync(x => x.Name == modeLogin.User && x.Password == modeLogin.Password); if (verifyUser != null) { var claims = new List <Claim> { new Claim(ClaimTypes.Name, verifyUser.Name), new Claim(ClaimTypes.Email, verifyUser.Email), new Claim("Id", "Id", verifyUser.Id.ToString()) }; var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie); Request.GetOwinContext().Authentication.SignIn(id); RedirectToAction("Default", "index"); } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); return(View()); } } return(View()); }
public void AoCadastrarContaApiDeveRetornar201() { //arrange var options = new DbContextOptionsBuilder <SocialContext>() .UseInMemoryDatabase("SocialContext") .Options; var contexto = new SocialContext(options); var repoConta = new ContaRepository(contexto); var repoTransf = new TransferenciaRepository(contexto); var contaService = new ContaService(repoConta); var transacoesService = new TransacoesService(repoTransf, repoConta); var controlador = new ContasController(contaService, transacoesService); var model = new ContaApi { Name = "Bruno", Description = "Daldegan", Status = "ACTIVE", Idenfifier = "65432" }; //act var retorno = controlador.Incluir(model); Assert.IsType <CreatedResult>(retorno); //201 }
public bool EnviarMensagem(Mensagem mensagem, int idBox, int idUsuario) { using (SocialContext ctx = new SocialContext()) { try { Usuario usuarioBuscado = ctx.Usuario.Find(idUsuario); BoxMensagem bx = ctx.BoxMensagem.FirstOrDefault(u => u.IdBoxMensagem == idBox); if (bx == null) { return(false); } else { mensagem.IdUsuarioNavigation = usuarioBuscado; mensagem.IdBoxMensagemDestino = bx.IdBoxMensagem; mensagem.DataMensagem = DateTime.Now; ctx.Add(mensagem); ctx.SaveChanges(); return(true); } }catch (Exception e) { return(false); } } }
static void Main(string[] args) { var context = new SocialContext(); context.SetProvider(new FacebookProvider()); //switch which provider you want to use context.AddComment(new Comment() { Message = "Heres my Comment!" }); }
public SocialDataController(IConfiguration configuration, SocialContext context) { appId = configuration.GetValue <ulong>("VkApi:AppId"); login = configuration.GetSection("VkApi")["Login"]; password = configuration.GetSection("VkApi")["Password"]; //connection = configuration.GetConnectionString("DefaultConnection"); _context = context; }
public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; List<ITopicContent> viewModel = new List<ITopicContent>(); using (var content = new SocialContext()) { var results = (from b in content.BlogPost.Where(b => b.ImageURL != null) select new { ID = b.ID, Type = "Blog", CreatedDate = b.CreatedDate }) .Concat( from q in content.QuotePost.Where(q => q.ImageURL != null) select new { ID = q.ID, Type = "Quote", CreatedDate = q.CreatedDate }) .Concat( from v in content.VideoPost.Where(v => v.ImageURL != null) select new { ID = v.ID, Type = "Video", CreatedDate = v.CreatedDate } ).ToList(); int count = Math.Min(5, results.Count()); var dateSortedResults = results.OrderByDescending(a => a.CreatedDate).Take(count).ToList(); foreach (var item in results) { Console.WriteLine(item); switch (item.Type) { case "Video" : viewModel.Add(content.VideoPost.Where(v => v.ID == item.ID).FirstOrDefault()); break; case "Quote" : viewModel.Add(content.QuotePost.Where(q => q.ID == item.ID).FirstOrDefault()); break; case "Blog" : viewModel.Add(content.BlogPost.Where(b => b.ID == item.ID).FirstOrDefault()); break; } } } return View(viewModel); }
public PartialViewResult Blog(String header) { Boolean isOpinion = header == "opinion"; using (var context = new SocialContext()) { var blogs = context.BlogPost .Include(v => v.Author) .Where(v => v.IsOpinion == isOpinion); ViewBag.isOpinion = isOpinion; return PartialView(blogs.ToList()); } }
public ActionResult Collaborate(CollabRequest request) { if (ModelState.IsValid) { using (var context = new SocialContext()) { context.CollabRequest.Add(request); context.SaveChanges(); } return RedirectToAction("Collaborate"); } return View(); }
public ActionResult Index(Feedback feedback) { if (ModelState.IsValid) { using (var context = new SocialContext()) { context.Feedback.Add(feedback); context.SaveChanges(); } return RedirectToAction("Index"); } return View(); }
public ActionResult Item(int id = -1) { using (var context = new SocialContext()) { var result = context.BlogPost .Include(b => b.Author) .Where(b => b.ID == id).FirstOrDefault(); if (result == null) return RedirectToAction("Http404", "Status", new { id = id.ToString() }); else return View(result); } }
// // GET: /Status/ public ActionResult Http404(String s = "") { using (var context = new SocialContext()) { context.Errors.Add(new HttpError { ID = -1, HttpCode = 404, Message = String.Format("HTTP404:{0}",s) }); context.SaveChanges(); } return View(); }
public List <Mensagem> ListarMensagens() { using (SocialContext ctx = new SocialContext()) { try { return(ctx.Mensagem.ToList()); } catch (Exception e) { return(null); } } }
public ActionResult Delete(Int32 id) { using (var context = new SocialContext()) { YHWProfile currentUser = context.UserProfile.Where(p => p.UserName == User.Identity.Name).FirstOrDefault(); var target = context.ContentComment.Where(cc => cc.ID == id).FirstOrDefault(); String ContentKey = target.ContentKey; if (target.MyAuthor.ID == currentUser.ID) context.ContentComment.Remove(target); context.SaveChanges(); return CommentPartial(ContentKey); } }
public ActionResult New(NewBlogVM vm) { Blog b = new Blog(); using (var context = new SocialContext()) { b.BlogText = vm.BlogText; b.Title = vm.Title; // calculate SubText int textLength = Math.Min(100, b.BlogText.Length); b.SubText = b.BlogText.Substring(0, textLength); if (textLength != b.BlogText.Length) b.SubText += "..."; b.Author = context.UserProfile.Where(u => u.UserName == User.Identity.Name).FirstOrDefault(); if (b.Author == null) return RedirectToAction("Home", "Index"); b.CreatedDate = DateTime.Now; b.IsOpinion = vm.IsOpinion == "on"; // ThumbImage if (vm.ThumbFile != null) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { vm.ThumbFile.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); b.ThumbURL = array; } } // Image if (vm.ImageFile != null) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { vm.ImageFile.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); b.ImageURL = array; } } context.BlogPost.Add(b); context.SaveChanges(); return RedirectToAction("Item", "Blog", new { id = b.ID }); } }
public ActionResult FormPost(String Message, String ContentKey) { using (var context = new SocialContext()) { YHWProfile currentUser = context.UserProfile.Where(p => p.UserName == User.Identity.Name).FirstOrDefault(); Comment newComm = new Comment() { MyAuthor = currentUser, Message = Message, CreationDate = DateTime.Now, ContentKey = ContentKey }; context.ContentComment.Add(newComm); context.SaveChanges(); return CommentPartial(ContentKey); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // services.AddDbContext<efmodel>(); var connString = Environment.GetEnvironmentVariable("SQLSERVER_HOST") ?? "Server=localhost\\SQLEXPRESS;Database=QuizRTSocialDb;Trusted_Connection=True;"; services.AddDbContext <SocialContext>(options => options.UseSqlServer(connString)); Console.WriteLine("dfkadjakjsdkajdajdskasdjaksdsdssssssssss" + connString); services.AddScoped <ITopic, TopicRepo>(); // services.AddSingleton<GraphDbConnection>(); var dbContextOptionsBuilder = new DbContextOptionsBuilder <SocialContext>(); var dbContextOptions = dbContextOptionsBuilder.UseSqlServer(connString).Options; var socialDbContext = new SocialContext(dbContextOptions); services.AddSingleton(s => new TopicConsumer(socialDbContext)); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); services.AddCors(options => { options.AddPolicy("CORS", corsPolicyBuilder => corsPolicyBuilder // Apply CORS policy for any type of origin .AllowAnyMethod() // Apply CORS policy for any type of http methods .AllowAnyHeader() // Apply CORS policy for any headers .AllowCredentials() .AllowAnyOrigin() // .WithOrigins ("http://localhost:4200","http:localhost:4201") ); // Apply CORS policy for all users }); }
public static IEnumerable <Categorie> GetUserFavoriteCategories( VKProvider vkProvider, SocialContext context, RepostCategoriesRequest repostCategoriesRequest) { var result = new List <Categorie>(); var person = vkProvider.GetPerson(repostCategoriesRequest.UserName, repostCategoriesRequest.AnalysisPeriod); if (person == null) { return(null); } //var keyGroups = context.vk_keygroups.ToList(); //FilterRepostGroups(person.GroupReposts, keyGroups); foreach (var gc in person.GroupReposts.Where(q => q.GroupId > 0)) { var Activity = ""; Activity = vkProvider.GetGroupInfo(gc.GroupId.ToString()).Activity; result.Add(new Categorie { Name = Activity, ActionCount = gc.CounterValue }); } //var nn = vkProvider.GetLikers(person.Posts); //StoreLikes(context, nn); var groupedResult = result .GroupBy(p => p.Name) .Select(group => new Categorie { Name = group.Key, ActionCount = group.Sum(n => n.ActionCount) }).ToList(); return(groupedResult); }
public ActionResult New(NewQuoteVM vm) { Quote q = new Quote(); using (var context = new SocialContext()) { q.Author = context.UserProfile.Where(u => u.UserName == User.Identity.Name).FirstOrDefault(); if (q.Author == null) RedirectToAction("Home", "Index"); q.CreatedDate = DateTime.Now; q.Title = vm.Title; q.SubText = vm.SubText; q.IsOpinion = vm.IsOpinion == "on"; // ThumbImage if (vm.ThumbFile != null) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { vm.ThumbFile.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); q.ThumbURL = array; } } // Image if (vm.ImageFile != null) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { vm.ImageFile.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); q.ImageURL = array; } } context.QuotePost.Add(q); context.SaveChanges(); return RedirectToAction("Item", "Quote", new { id = q.ID }); } }
public ActionResult FileUpload(HttpPostedFileBase file) { if (file != null) { String s = file.ContentType; Console.WriteLine(s); using (var context = new SocialContext()) using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { file.InputStream.CopyTo(ms); byte[] array = ms.GetBuffer(); var user = context.UserProfile.Where(p => p.UserName == User.Identity.Name).FirstOrDefault(); user.PortraitURL = array; context.SaveChanges(); } } return RedirectToAction("Index", "Home"); }
private static void StoreLikes(SocialContext context, IEnumerable <VK_Like> likes) { foreach (var key in likes .GroupBy(p => new { p.ObjectId, p.OwnerId }) .Select(group => group.Key).ToList()) { var existing = context.Vk_like.Where(c => c.ObjectId == key.ObjectId).ToList(); var deltaUsers = likes .Where(x => x.ObjectId == key.ObjectId && !existing.Any(y => x.UserId == y.UserId)) .Select(n => n.UserId) .Distinct(); context.Vk_like.AddRange(deltaUsers.Select(x => new VK_Like { ObjectId = key.ObjectId, OwnerId = key.OwnerId, UserId = x })); } context.SaveChangesAsync(); }
public Usuario Login(string email, string senha) { using (SocialContext ctx = new SocialContext()) { try { Usuario usuarioBuscado = ctx.Usuario.FirstOrDefault(u => u.Email == email && u.Senha == senha); if (usuarioBuscado == null) { return(null); } else { return(usuarioBuscado); } } catch (Exception ex) { return(null); } } throw new NotImplementedException(); }
private static void GerarContas() { var gerador = new GeradorAleatorioDeContas(); var contas = new List <Conta>(); Console.WriteLine("Gerando contas aleatórias..."); for (int i = 0; i < 10; i++) { contas.Add(gerador.ContaAleatoria()); } //... e depois persistir essa lista Console.WriteLine("Persistindo a lista..."); var optionsBuilder = new DbContextOptionsBuilder <SocialContext>(); optionsBuilder .UseSqlServer("Server=localhost;Database=SOCIAL;Trusted_Connection=True;MultipleActiveResultSets=true"); using (var ctx = new SocialContext(optionsBuilder.Options)) { ctx.Contas.AddRange(contas); ctx.SaveChanges(); } }
public PartialViewResult CommentPartial(String id) { if (id == null) throw new ArgumentException("id cannot be null"); using (var context = new SocialContext()) { var results = context.ContentComment .Include(cc => cc.MyAuthor) .Include(cc => cc.Ratings) .Where(cc => cc.ContentKey == id) .OrderByDescending(cc => cc.CreationDate); CommentPartialVM vm = new CommentPartialVM { Comments = results.ToList(), ContentKey = id }; // I guess it uses the request to figure out which view to use // and since I call this from different actions we need to specify // to use the view specific to this action return PartialView("CommentPartial",vm); } }
public TopicConsumer(SocialContext socialContext) { this.topicObj = new TopicRepo(socialContext); GetTopicsFromRabbitMQ(); }
public TweetsModel(SocialContext socialContext, ILogger <TweetsModel> logger) { _socialContext = socialContext; _logger = logger; Tweets = new List <Tweet>(); }
public ApplicationUserRepository(SocialContext dbContext) : base(dbContext) { }
public TopicRepo(SocialContext _context, GraphDb _graph) { this.context = _context; this.graphobj = _graph; }
public JsonResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl) { string provider = null; string providerUserId = null; if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId)) { return Json(new { Success = false, Error = "External Login Data invalid! Please try again." }); } if (ModelState.IsValid) { // Insert a new user into the database using (UsersContext db = new UsersContext()) using (SocialContext context = new SocialContext()) { UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower()); // Check if user already exists if (user == null) { // Insert name into the profile table db.UserProfiles.Add(new UserProfile { UserName = model.UserName }); db.SaveChanges(); OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false); context.UserProfile.Add(new YHWProfile { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, Birthday = model.Birthday, IsMale = model.IsMale }); context.SaveChanges(); return Json(new { Success = true, Redirect = Url.Action("Index", "Home") }); } else { return Json(new { Success = false, Error = "User Name exists" }); } } } return Json(new { Success = false, Error = "Server side Error, Registration failed, please try again!" }); }
public FriendsRepository(SocialContext context) { this.context = context; }
public UnitOfWork(SocialContext dbContext) { DbContext = dbContext; }
public ValuesController(SocialContext dbContext) { _dbContext = dbContext; }
public SocialContextEventsTest() { _socialContext = new SocialContext(); _contextFeature = new ValueContextFeature <string>("", ""); }
public CommentRepository(SocialContext context) : base(context) { }
public FollowRepository(SocialContext context) : base(context) { }
public PartialViewResult Generic(String header) { if (header == "") { using (var context = new SocialContext()) { List<YHW.Models.Content.ITopicContent> results = new List<ITopicContent>(); var items = (from v in context.VideoPost select new { v.ID, ContentType = "Video", v.CreatedDate }) .Union( from b in context.BlogPost select new { b.ID, ContentType = "Blog", b.CreatedDate }) .Union( from q in context.QuotePost select new { q.ID, ContentType = "Quote", q.CreatedDate }).ToList(); foreach (var item in items) { switch (item.ContentType) { case "Video": var vid = context.VideoPost .Include(v => v.Author) .Where(v => v.ID == item.ID).FirstOrDefault(); if (vid != null) results.Add(vid); break; case "Quote": var quote = context.QuotePost .Include(q => q.Author) .Where(q => q.ID == item.ID).FirstOrDefault(); if (quote != null) results.Add(quote); break; case "Blog": var blog = context.BlogPost .Include(b => b.Author) .Where(b => b.ID == item.ID).FirstOrDefault(); if (blog != null) results.Add(blog); break; } } return PartialView("DualView", results); } } Boolean isOpinion = header == "opinion"; using (var context = new SocialContext()) { List<YHW.Models.Content.ITopicContent> results = new List<ITopicContent>(); var items = (from v in context.VideoPost where v.IsOpinion == isOpinion select new { v.ID, ContentType = "Video", v.CreatedDate }) .Union( from b in context.BlogPost where b.IsOpinion == isOpinion select new { b.ID, ContentType = "Blog", b.CreatedDate }) .Union( from q in context.QuotePost where q.IsOpinion == isOpinion select new { q.ID, ContentType = "Quote", q.CreatedDate }).ToList(); foreach(var item in items) { switch (item.ContentType) { case "Video": var vid = context.VideoPost .Include(v => v.Author) .Where(v => v.ID == item.ID).FirstOrDefault(); if (vid != null) results.Add(vid); break; case "Quote": var quote = context.QuotePost .Include(q => q.Author) .Where(q => q.ID == item.ID).FirstOrDefault(); if (quote != null) results.Add(quote); break; case "Blog": var blog = context.BlogPost .Include(b => b.Author) .Where(b => b.ID == item.ID).FirstOrDefault(); if (blog != null) results.Add(blog); break; } } ViewBag.isOpinion = isOpinion; return PartialView(results); } }
public CommentsController(SocialContext context) { _context = context; }
public JsonResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { if (WebSecurity.UserExists(model.UserName)) return Json(new { Success = false, Error = "User Name exists"}); WebSecurity.CreateUserAndAccount(model.UserName, model.Password); WebSecurity.Login(model.UserName, model.Password); using (var context = new SocialContext()) { context.UserProfile.Add(new YHWProfile { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, Birthday = model.Birthday, IsMale = model.IsMale }); context.SaveChanges(); } return Json(new { Success = true, Redirect = Url.Action("Index", "Home") }); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return Json(new { Success = false, Error = "Serverside Error!" }); }
protected RepositoryBase(SocialContext dataContext) { DbContext = dataContext; dbSet = DbContext.Set <T>(); }
public PostRepository(SocialContext context) : base(context) { }
public ProfileRepository(SocialContext context) : base(context) { }
public TopicRepo(SocialContext _context) { this.context = _context; }
public SocialContextSeedData(SocialContext context, UserManager<SocialUser> userManager) { _context = context; _userManager = userManager; }
public LikeRepository(SocialContext context) : base(context) { }
public FrameCreationTest() { _frame = new Frame(); _context = new SocialContext(); }
public ProductsController(SocialContext context) { _context = context; }
public SocialRepository(SocialContext context, ILogger<SocialRepository> logger) { _context = context; _logger = logger; }