예제 #1
0
 public T ObterPorId(int Id)
 {
     using (var banco = new GeneralContext(_OptionsBuilder))
     {
         return(banco.Set <T>().Find());
     }
 }
예제 #2
0
        public ApiException(string message) : base(message)
        {
            _error = this;
            var contextAccessor = GeneralContext.GetService <IHttpContextAccessor>();

            contextAccessor.HttpContext.Features.Set <IExceptionHandlerFeature>(this);
        }
예제 #3
0
 public IList <T> Listar()
 {
     using (var banco = new GeneralContext(_OptionsBuilder))
     {
         return(banco.Set <T>().AsNoTracking().ToList());
     }
 }
        public static ApiResponse GetResponseDetails(this HttpContext context, Exception apiException = null, string message = null)
        {
            ApiResponse response = null;

            try
            {
                // get action  action ReturnType
                Type           responseDeclaredType = context.GetActionReturnType();
                HttpStatusCode statusCode           = apiException != null ? HttpStatusCode.Conflict : (HttpStatusCode)context.Response.StatusCode;

                // create api response
                response = new ApiResponse(context.Response.StatusCode)
                {
                    TraceId    = GeneralContext.CreateTraceId(),
                    RequestUrl = context.GetRequestUrl(),
                    Value      = responseDeclaredType?.GetDefault(),
                    ActionType = responseDeclaredType,
                    StatusCode = $"{(int)statusCode}: {statusCode}",
                    Message    = message ?? apiException?.GetApiMessageInfo() ?? ((HttpStatusCode)context.Response.StatusCode).ToString(),
                    Error      = apiException != null ? new ApiError(apiException) : null
                };

                GeneralContext.Logger.Error($"traceId: {response.TraceId}, error: {response.Message}");
            }
            catch (Exception ex)
            {
                GeneralContext.Logger.Error(ex.GetApiMessageInfo("Unhandled exception"));
                //context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            }

            return(response);
        }
예제 #5
0
        protected override void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: dispose managed state (managed objects)
                    using var tempServiceScope = GeneralContext.CreateServiceScope();
                    var userService = GeneralContext.GetService <UserService>();
                    userService.DbContext = tempServiceScope.ServiceProvider.GetService <CRPMContext>();
                    // remove testusers
                    var results = userService.DbContext.User.AsEnumerable()
                                  .Where(x => int.Parse(x.UserId) < 0 && x.UserName.Contains("only_for_test"));
                    if (results != null && results.Any())
                    {
                        userService.DbContext.User.RemoveRange(results);
                    }

                    userService.OkResult().Wait();

                    base.Dispose(disposing);
                }
                disposedValue = true;
            }
        }
예제 #6
0
 public List <TReminder> GetAll()
 {
     using (GeneralContext database = new GeneralContext())
     {
         return(database.Reminder.ToList());
     }
 }
예제 #7
0
 public List <TReminder> GetAll(ulong userId)
 {
     using (GeneralContext database = new GeneralContext())
     {
         return(database.Reminder.Where(x => x.UserId.Equals(userId)).ToList());
     }
 }
예제 #8
0
 public void TestGetPosts1()
 {
     using (var context = new GeneralContext())
     {
         var user1 = context.ImagePosts.FirstOrDefault(x => x.Id == 2);
     }
 }
예제 #9
0
        private async Task InitializeAsync()
        {
            this._serviceCollection.AddSingleton(this._client);
            this._serviceCollection.AddSingleton(this._commandService);
            this._serviceCollection.AddSingleton(RemindService.GetInstance(this._client));

            this._serviceProvider = this._serviceCollection.BuildServiceProvider(true);

            await this._commandService.AddModulesAsync(Assembly.GetEntryAssembly());

            this._commandService.AddTypeReader <TimeUnitTypeReader>(new TimeUnitTypeReader());
            this._commandService.AddTypeReader <LeagueRoleTypeReader>(new LeagueRoleTypeReader());

            DiscordEventHandler eventHandler = new DiscordEventHandler(this._serviceProvider);

            this._client.Log             += Logger.Log;
            this._commandService.Log     += Logger.Log;
            this._client.Ready           += eventHandler.HandleReady;
            this._client.MessageReceived += eventHandler.HandleMessageReceived;

            using (GeneralContext database = new GeneralContext())
            {
                await database.Database.EnsureCreatedAsync();
            }
        }
예제 #10
0
 // Clean test data
 protected override void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         if (disposing)
         {
             // TODO: dispose managed state (managed objects)
             using var tempServiceScope = GeneralContext.CreateServiceScope();
             var dbContext   = tempServiceScope.ServiceProvider.GetService <CRPMContext>();
             var formResults = dbContext.Form.Where(x => x.FormGuid.Contains("only_for_test"));
             if (formResults != null && formResults.Any())
             {
                 dbContext.Form.RemoveRange(formResults);
             }
             var formTemplates = dbContext.FormTemplate.Where(x => x.Description.Contains("only_for_test"));
             if (formTemplates != null && formTemplates.Any())
             {
                 dbContext.FormTemplate.RemoveRange(formTemplates);
             }
             dbContext.SaveChanges();
             base.Dispose(disposing);
         }
         disposedValue = true;
     }
 }
예제 #11
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (var db = new GeneralContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
예제 #12
0
 public void Adcionar(T Objeto)
 {
     using (var banco = new GeneralContext(_OptionsBuilder))
     {
         banco.Set <T>().Add(Objeto);
         banco.SaveChangesAsync();
     }
 }
예제 #13
0
 public void Atualizar(T Objeto)
 {
     using (var banco = new GeneralContext(_OptionsBuilder))
     {
         banco.Set <T>().Update(Objeto);
         banco.SaveChangesAsync();
     }
 }
예제 #14
0
 public void Excluir(T Objeto)
 {
     using (var banco = new GeneralContext(_OptionsBuilder))
     {
         banco.Set <T>().Remove(Objeto);
         banco.SaveChangesAsync();
     }
 }
예제 #15
0
 public void TestUserMessages1()
 {
     using (var context = new GeneralContext())
     {
         var user1 = context.Users.FirstOrDefault(x => x.Id == 1);
         var test  = user1.PrivateMessagesSent;
     }
 }
예제 #16
0
 public void TestUserPosts1()
 {
     using (var context = new GeneralContext())
     {
         var user1 = context.Users.FirstOrDefault(x => x.Id == 4);
         var test  = user1.ReceivedPosts;
     }
 }
예제 #17
0
 public async Task RemoveByUserAsync(ulong userId)
 {
     using (GeneralContext database = new GeneralContext())
     {
         database.Reminder.RemoveRange(database.Reminder.Where(x => x.UserId.Equals(userId)));
         await database.SaveChangesAsync().ConfigureAwait(false);
     }
 }
예제 #18
0
        public TService GetChildScopeService <TService>() where TService : BaseService
        {
            var _serviceScope = GeneralContext.CreateServiceScope();
            var service       = _serviceScope.ServiceProvider.GetService <TService>();

            service.DbContext = _serviceScope.ServiceProvider.GetService <CRPMContext>();
            return(service as TService);
        }
예제 #19
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            UoW = GeneralContext.GetService(typeof(IUnitOfWork <IDbContext>)) as IUnitOfWork <IDbContext>;
            System.Diagnostics.Trace.WriteLine("Scoped UoW " + UoW.SessionId);

            //Uow.Commit(); here you would commit
            System.Diagnostics.Trace.WriteLine("GlobalConfig UoW " + UoW.SessionId);
        }
예제 #20
0
        /// <summary> On setup migrations </summary>
        private void OnSetUp(MigrationBuilderEnsured migrationBuilder)
        {
            using var initServiceScope = GeneralContext.CreateServiceScope();
            var initServiceProvider = initServiceScope.ServiceProvider;

            this.Init(migrationBuilder, initServiceProvider);
            this.Up(migrationBuilder);
            this.Down(migrationBuilder);
        }
예제 #21
0
        public static void Clear(this IRequestCookieCollection cookies)
        {
            var httpContext = GeneralContext.GetService <IHttpContextAccessor>().HttpContext;

            foreach (var cookie in cookies.Keys)
            {
                httpContext.Response.Cookies.Delete(cookie);
            }
        }
예제 #22
0
        /// <summary> temp Exists method </summary>
        private bool Exists_(string tableName)
        {
            using var completeServiceScope = GeneralContext.CreateServiceScope();
            var services = completeServiceScope.ServiceProvider;

            using var dbContext = services.GetService <CRPMContext>() as CRPMContext;
            var count = dbContext.Database.ExecuteSqlRaw("SELECT FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relname = @p0)", tableName);

            return(count > 0);
        }
예제 #23
0
        public string GetConnectionString()
        {
            string connectionString = GeneralContext.GetConnectionString("CRPMDatabase");

            if (string.IsNullOrEmpty(connectionString) || connectionString.Contains("{0}"))
            {
                GeneralContext.Logger.Error("connectionString is null or empty or not valid");
            }

            return(connectionString);
        }
예제 #24
0
 static void Main(string[] args)
 {
     using (var ctx = new GeneralContext()) {
         SalesRepresentative emp = new SalesRepresentative()
         {
             Name = "Prashant"
         };
         ctx.SalesRepresentatives.Add(emp);
         ctx.SaveChanges();
     }
 }
예제 #25
0
        /// <summary>
        /// Resets the database context and creates a new context to work with
        /// </summary>
        protected virtual void ResetContext()
        {
            var options = new DbContextOptionsBuilder <GeneralContext>()
                          .UseInMemoryDatabase("HobbyTest")
                          .EnableSensitiveDataLogging()
                          .Options;

#pragma warning disable CS0618 // Type or member is obsolete
            // Create mem database
            this.context = new GeneralContext(options);
#pragma warning restore CS0618 // Type or member is obsolete
        }
예제 #26
0
        public void TestSeed1()
        {
            using (var temp = new GeneralContext())
            {
                var user = new User()
                {
                    Age                     = 28,
                    FirstName               = "Harry",
                    LastName                = "Person",
                    Friends                 = new List <User>(),
                    SentPosts               = new List <Post>(),
                    ReceivedPosts           = new List <Post>(),
                    PrivateMessagesReceived = new List <PrivateMessage>(),
                    PrivateMessagesSent     = new List <PrivateMessage>()
                };

                var user2 = new User()
                {
                    Age       = 28,
                    FirstName = "Steven",
                    LastName  = "Lister",
                    Friends   = new List <User>()
                    {
                        user
                    },
                    SentPosts               = new List <Post>(),
                    ReceivedPosts           = new List <Post>(),
                    PrivateMessagesReceived = new List <PrivateMessage>(),
                    PrivateMessagesSent     = new List <PrivateMessage>()
                };

                var user3 = new User()
                {
                    Age       = 28,
                    FirstName = "Jane",
                    LastName  = "Bottle",
                    Friends   = new List <User>()
                    {
                        user,
                        user2
                    },
                    SentPosts               = new List <Post>(),
                    ReceivedPosts           = new List <Post>(),
                    PrivateMessagesReceived = new List <PrivateMessage>(),
                    PrivateMessagesSent     = new List <PrivateMessage>()
                };

                temp.Users.Add(user);
                temp.Users.Add(user2);
                temp.Users.Add(user3);
                temp.SaveChanges();
            }
        }
예제 #27
0
 public string GetValue(Property property)
 {
     using (GeneralContext database = new GeneralContext())
     {
         TProperty match = database.Properties.FirstOrDefault(x => x.Name.Equals(property.Name));
         if (match != null)
         {
             return(match.Value);
         }
     }
     throw new NotExistingException();
 }
예제 #28
0
        public void TestUserFriends1()
        {
            using (var context = new GeneralContext())
            {
                var user1 = context.Users.FirstOrDefault(x => x.Id == 4);
                var test  = user1.Friends;

                foreach (var user in test)
                {
                    Trace.WriteLine(user.UserName);
                }
            }
        }
예제 #29
0
        public UserService(GeneralContext context)
        {
            _context = context;

            /*if(this._context.Users.CountAsync().Result<1){
             *  var usr = new User();
             *  usr.Nombre = "Vidal";
             *  usr.Cedula = "1065";
             *  usr.Rol = "Admin";
             *  this._context.Users.Add(usr);
             *  this._context.SaveChanges();
             * }*/
        }
예제 #30
0
        public ActionResult Guardar(string nombre, string apellido, string correo)
        {
            GeneralContext db      = new GeneralContext();
            Clientes       cliente = new Clientes();

            cliente.nombre   = nombre;
            cliente.apellido = apellido;
            cliente.correo   = correo;
            db.Clientes.Add(cliente);
            db.SaveChanges();

            return(PartialView("Lista", db.Clientes.ToList()));
        }