Beispiel #1
0
        public bool Add(T entity)
        {
            db.Set <T>().Add(entity);
            int i = db.SaveChanges();

            return(i > 0);
        }
        public static void Build(BusinessDbContext db, string tenantId)
        {
            var     roles = StaticRoles.GetRoles();
            Company company;
            Tenant  tenant;

            if (string.IsNullOrWhiteSpace(tenantId))
            {
                company  = db.Companies.FirstOrDefault(x => x.Name == StaticCompany.Host);
                tenant   = db.Tenants.FirstOrDefault(x => x.Name == StaticTenant.Host);
                tenantId = tenant?.Id;
            }
            else
            {
                company = db.Companies.FirstOrDefault(x => x.TenantId == tenantId);
                tenant  = db.Tenants.FirstOrDefault(x => x.Id == tenantId);
            }

            if (tenant?.Name != StaticTenant.Host)
            {
                roles = roles.Where(x => x.Name != StaticRoles.SystemAdmin.Name).ToList();
            }

            if (!db.Roles.Any(x => x.TenantId == tenantId))
            {
                foreach (var role in roles)
                {
                    db.Roles.Add(new Role
                    {
                        Id          = Guid.NewGuid().ToString(),
                        Name        = role.Name,
                        DisplayName = role.DisplayName,
                        AccessLevel = role.AccessLevel,
                        TenantId    = tenant?.Id,
                        CompanyId   = company?.Id
                    });
                }

                db.SaveChanges();
            }

            else
            {
                foreach (var role in roles.Where(role => db.Roles.FirstOrDefault(x => x.Name == role.Name && x.TenantId == tenantId) == null))
                {
                    db.Roles.Add(new Role {
                        Id = Guid.NewGuid().ToString(), Name = role.Name
                    });
                }

                db.SaveChanges();
            }
        }
        public bool Add(Customer customer)
        {
            db.Customers.Add(customer);

            int isExecuted = db.SaveChanges();

            if (isExecuted > 0)
            {
                return(true);
            }

            return(false);
        }
Beispiel #4
0
        public bool Add(Product product)
        {
            int isExecuted = 0;

            db.Products.Add(product);
            isExecuted = db.SaveChanges();

            if (isExecuted > 0)
            {
                return(true);
            }

            return(false);
        }
Beispiel #5
0
        public bool Add(Supplier supplier)
        {
            int isExecuted = 0;

            db.Suppliers.Add(supplier);
            isExecuted = db.SaveChanges();

            if (isExecuted > 0)
            {
                return(true);
            }

            return(false);
        }
Beispiel #6
0
        public bool Add(Catalog catalog)
        {
            int isExecuted = 0;

            db.Catalogs.Add(catalog);
            isExecuted = db.SaveChanges();

            if (isExecuted > 0)
            {
                return(true);
            }

            return(false);
        }
Beispiel #7
0
        public bool UpsertProductsByDealer(Sale sale)
        {
            BusinessDbContext db = this.Repository.Db as BusinessDbContext;
            List <string>     productDetailIds = db.Sales.Where(x => x.DealerId == sale.DealerId && x.ShopId == sale.ShopId).Include(x => x.SaleDetails)
                                                 .SelectMany(x => x.SaleDetails).Select(x => x.ProductDetailId).Distinct().ToList();

            //foreach (SaleDetail detail in sale.SaleDetails)
            foreach (var productDetailId in productDetailIds)
            {
                List <SaleDetail> saleDetailsByProduct =
                    db.Sales.Where(x => x.DealerId == sale.DealerId && x.ShopId == sale.ShopId)
                    .Include(x => x.SaleDetails).SelectMany(x => x.SaleDetails)
                    .Where(x => x.ProductDetailId == productDetailId).ToList();

                double productQuantity   = saleDetailsByProduct.Sum(x => x.Quantity);
                var    productTotalPrice = saleDetailsByProduct.Sum(x => x.Total);

                var product = db.DealerProducts.FirstOrDefault(x =>
                                                               x.ShopId == sale.ShopId && x.DealerId == sale.DealerId &&
                                                               x.ProductDetailId == productDetailId);

                if (product == null)
                {
                    product = new DealerProduct
                    {
                        ProductDetailId = productDetailId,
                        DealerId        = sale.DealerId,
                        Quantity        = productQuantity,
                        TotalPrice      = productTotalPrice,
                        ShopId          = sale.ShopId,
                    };
                    product.Due = product.TotalPrice - product.Paid;
                    AddCommonValues(sale, product);
                    // populate with other info
                    db.DealerProducts.Add(product);
                    db.SaveChanges();
                }
                else
                {
                    product.Quantity   = productQuantity;
                    product.TotalPrice = productTotalPrice;
                    product.Due        = product.TotalPrice - product.Paid;

                    db.SaveChanges();
                }
            }

            return(true);
        }
Beispiel #8
0
        public bool UpsertProductsBySupplier(Purchase purchase)
        {
            BusinessDbContext db = this.Repository.Db as BusinessDbContext;

            var productDetailIds = db.Purchases.Where(x => x.SupplierId == purchase.SupplierId && x.ShopId == purchase.ShopId)
                                   .Include(x => x.PurchaseDetails).SelectMany(x => x.PurchaseDetails).Select(x => x.ProductDetailId)
                                   .Distinct().ToList();

            foreach (string productDetailId in productDetailIds)
            {
                List <PurchaseDetail> purchaseDetailsByProduct =
                    db.Purchases.Where(x => x.SupplierId == purchase.SupplierId && x.ShopId == purchase.ShopId)
                    .Include(x => x.PurchaseDetails).SelectMany(x => x.PurchaseDetails)
                    .Where(x => x.ProductDetailId == productDetailId).ToList();

                double productQuantity   = purchaseDetailsByProduct.Sum(x => x.Quantity);
                var    productTotalPrice = purchaseDetailsByProduct.Sum(x => x.CostTotal);

                var product = db.SupplierProducts.FirstOrDefault(x =>
                                                                 x.ShopId == purchase.ShopId && x.SupplierId == purchase.SupplierId &&
                                                                 x.ProductDetailId == productDetailId);

                if (product == null)
                {
                    product = new SupplierProduct
                    {
                        ProductDetailId = productDetailId,
                        SupplierId      = purchase.SupplierId,
                        Quantity        = productQuantity,
                        TotalPrice      = productTotalPrice,
                        ShopId          = purchase.ShopId,
                    };
                    product.Due = product.TotalPrice - product.Paid;
                    AddCommonValues(purchase, product);
                    db.SupplierProducts.Add(product);
                    db.SaveChanges();
                }
                else
                {
                    product.Quantity   = productQuantity;
                    product.TotalPrice = productTotalPrice;
                    product.Due        = product.TotalPrice - product.Paid;

                    db.SaveChanges();
                }
            }

            return(true);
        }
        public bool AddCategory(Category category)
        {
            db.Categories.Add(category);

            int isExecuted = 0;

            isExecuted = db.SaveChanges();

            if (isExecuted > 0)
            {
                return(true);
            }

            return(false);
        }
        public Notification UpdateProcess(BusinessDbContext context, long notificationId)
        {
            var notification = context.Notifications.FirstOrDefault(x => x.Id == notificationId);

            notification.Title    = Title;
            notification.Details  = Details;
            notification.Location = new PostgisPoint(Location.Coordinates[0], Location.Coordinates[1])
            {
                SRID = Constants.SRID
            };
            var affectedCoordinates = AffectedArea.Coordinates.Select(coor => new Coordinate2D(coor[0], coor[1])).ToArray();

            notification.AffectedArea = new PostgisPolygon(new[]
            {
                affectedCoordinates
            });

            notification.Category  = Category;
            notification.Status    = Status;
            notification.Published = Published;
            notification.Source    = Source;
            notification.Severity  = Severity;


            context.SaveChanges();
            return(notification);
        }
        public async Task SeedAsync(BusinessDbContext context, IHostingEnvironment env, IOptions <BusinessSettings> settings, ILogger <BusinessDbContextSeed> logger)
        {
            var policy = CreatePolicy(logger, nameof(BusinessDbContextSeed));

            await policy.ExecuteAsync(async() =>
            {
                var useCustomizationData = settings.Value.UseCustomizationData;
                var contentRootPath      = env.ContentRootPath;
                var picturePath          = env.WebRootPath;

                if (!context.Sites.Any())
                {
                    await context.Sites.AddRangeAsync(GetPreconfiguredSites());

                    await context.SaveChangesAsync();
                }

                if (!context.Locations.Any())
                {
                    logger.LogDebug("Seeding locations ...");
                    await context.Locations.AddRangeAsync(GetLocationsFromFile(contentRootPath, context, logger));
                    await context.SaveChangesAsync();

                    context.Locations.UpdateRange(GetLocationsFromFile2(contentRootPath, context, logger));
                    context.SaveChanges();

                    //GetCatalogItemPictures(contentRootPath, picturePath);
                }
            });
        }
        private void SeedAccountManagers(ApplicationDbContext context)
        {
            BusinessDbContext bctx = new BusinessDbContext(); // Note this call will trigger the database initialiser for BusinessContext
            // The first time around
            // Create and Attach Account Managers to the Accounts

            var roles = context.Roles.Where(r => r.Name == "Manager");

            if (roles.Any())
            {
                var users = context.Users.ToList();
                // Get users in roles
                var AccountManagers = (from c in users
                                       where c.Roles.Any(r => r.RoleId == roles.First().Id)
                                       select c);
                // Assign a random user to a company
                foreach (var orders in bctx.Orders)
                {
                    // Select a random account manager id
                    orders.OrderedBy = AccountManagers
                                       .Select(m => new { id = m.Id, order = Guid.NewGuid().ToString() })
                                       .OrderBy(o => o.order)
                                       .Select(r => r.id)
                                       .First();
                }
            }
            bctx.SaveChanges();
        }
        public static void AddCompanySettings(BusinessDbContext context)
        {
            if (context.CompanySettings.Any())
            {
                return;
            }

            var tenant  = context.Tenants.FirstOrDefault(x => x.Name == StaticTenant.Host);
            var company = context.Companies.FirstOrDefault(x => x.Name == StaticTenant.Host);

            var id = Guid.NewGuid().ToString();
            var companySettings = new CompanySetting
            {
                Id         = id,
                Active     = true,
                Created    = DateTime.Now,
                CreatedBy  = null,
                Modified   = DateTime.Now,
                ModifiedBy = null,

                HostingValidTill = null,
                PoweredBy        = "Powered by www.datacrud.com",

                TenantId  = tenant?.Id,
                CompanyId = company?.Id
            };

            context.CompanySettings.Add(companySettings);
            context.SaveChanges();
        }
Beispiel #14
0
        public void Process(BusinessDbContext context)
        {
            var admin = GetAdmin(context);

            if (admin == null)
            {
                throw new ProcessEventException(Constants.Messages.UserNotFound);
            }

            if (!string.IsNullOrWhiteSpace(Name))
            {
                admin.Name = Name;
            }


            if (!string.IsNullOrWhiteSpace(Email))
            {
                admin.Email = Email;
            }

            if (string.IsNullOrWhiteSpace(NewPassowrd) || string.IsNullOrWhiteSpace(ExistingPassword))
            {
                var check = admin.VerifyPassowrd(ExistingPassword);
                if (check == PasswordVerificationResult.Success)
                {
                    admin.SetPassword(NewPassowrd);
                }
            }

            context.SaveChanges();
        }
        public static void AddCompany(BusinessDbContext context)
        {
            if (context.Companies.Any())
            {
                return;
            }

            var tenant = context.Tenants.FirstOrDefault(x => x.Name == StaticTenant.Host);

            var id      = Guid.NewGuid().ToString();
            var company = new Company()
            {
                Id         = id,
                Active     = true,
                Created    = DateTime.Now,
                CreatedBy  = null,
                Modified   = DateTime.Now,
                ModifiedBy = null,

                Name    = StaticCompany.Host,
                Address = "Dhaka",
                Email   = "*****@*****.**",
                Phone   = "01715189043",

                TenantId = tenant?.Id,
                Web      = "http://datacrud.com",
            };

            context.Companies.Add(company);
            context.SaveChanges();
        }
        private static void AddTenant(BusinessDbContext context)
        {
            if (context.Tenants.Any())
            {
                return;
            }

            var edition = context.Editions.FirstOrDefault(x => x.Name == StaticEdition.Deluxe);

            context.Tenants.Add(new Tenant()
            {
                Id       = Guid.NewGuid().ToString(),
                Created  = DateTime.Now,
                Modified = DateTime.Now,
                IsActive = true,
                Active   = true,

                ConnectionString    = null,
                EditionId           = edition?.Id,
                IsInTrialPeriod     = false,
                Name                = StaticTenant.Host,
                TenancyName         = TenantHelper.BuildTenancyName(StaticTenant.Host),
                SubscriptionEndTime = DateTime.Today.AddYears(100),
                Url = $"http://{StaticTenant.Host.ToLower()}" +
                      $".datacrud.com"
            });

            context.SaveChanges();
        }
        public static void AddSubscription(BusinessDbContext db)
        {
            if (db.Subscriptions.Any())
            {
                return;
            }

            var tenant  = db.Tenants.FirstOrDefault(x => x.Name == StaticTenant.Host);
            var company = db.Companies.FirstOrDefault(x => x.Name == StaticCompany.Host);
            var edition = db.Editions.FirstOrDefault(x => x.Name == StaticEdition.Deluxe);

            db.Subscriptions.Add(new Subscription
            {
                Id         = Guid.NewGuid().ToString(),
                Created    = DateTime.Now,
                CreatedBy  = null,
                Modified   = DateTime.Now,
                ModifiedBy = null,
                Active     = true,

                TenantId  = tenant?.Id,
                CompanyId = company?.Id,

                EditionId          = edition?.Id,
                Package            = SubscriptionPackage.LifeTime,
                Price              = 0,
                Status             = SubscriptionStatus.Active,
                ExpireOn           = DateTime.Today.AddYears(100),
                IsPaymentCompleted = true,
                PaymentStatus      = SubscriptionPaymentStatus.Paid
            });

            db.SaveChanges();
        }
        public static void AddWarehouses(BusinessDbContext db)
        {
            if (db.Warehouses.Any())
            {
                return;
            }

            var tenant  = db.Tenants.FirstOrDefault(x => x.Name == StaticTenant.Host);
            var company = db.Companies.FirstOrDefault(x => x.Name == StaticCompany.Host);

            db.Warehouses.Add(new Warehouse
            {
                Id      = Guid.NewGuid().ToString(),
                Created = DateTime.Now,

                CreatedBy = null,

                Active = true,
                Code   = "HO",
                Name   = "Head Office",
                Type   = WarehouseType.HeadOffice,

                TenantId  = tenant?.Id,
                CompanyId = company?.Id
            });

            db.SaveChanges();
        }
Beispiel #19
0
        private static void AddTrade(BusinessDbContext context)
        {
            if (context.Trades.Any())
            {
                return;
            }

            context.Trades.AddOrUpdate(new Trade()
            {
                Id = 1.ToString(),

                Name = "Asphalt Concrete Paving",

                Created    = DateTime.Now,
                CreatedBy  = "Seed",
                Modified   = DateTime.Now,
                ModifiedBy = "Seed",
            });

            context.Trades.AddOrUpdate(new Trade()
            {
                Id = 2.ToString(),

                Name = "Bulldozer Operation",

                Created    = DateTime.Now,
                CreatedBy  = "Seed",
                Modified   = DateTime.Now,
                ModifiedBy = "Seed",
            });

            context.Trades.AddOrUpdate(new Trade()
            {
                Id = 3.ToString(),

                Name = "Bricklaying",

                Created    = DateTime.Now,
                CreatedBy  = "Seed",
                Modified   = DateTime.Now,
                ModifiedBy = "Seed",
            });

            context.Trades.AddOrUpdate(new Trade()
            {
                Id = 4.ToString(),

                Name = "Bored Micro-Piling Operation",

                Created    = DateTime.Now,
                CreatedBy  = "Seed",
                Modified   = DateTime.Now,
                ModifiedBy = "Seed",
            });

            context.SaveChanges();
        }
        public static void Build(BusinessDbContext db, string tenantId)
        {
            var tenant = TenantBuilder.GetTenant(db, tenantId);

            var permissions = new List <Permission>();

            var roles            = db.Roles.Where(x => x.TenantId == tenant.Id).ToList();
            var privateResources = db.Resources.Where(x => x.IsPublic == false).ToList();

            #region System Admin Role Permissions

            if (string.IsNullOrWhiteSpace(tenantId))
            {
                var systemAdminRole = roles.First(x => x.Name == StaticRoles.SystemAdmin.Name);
                permissions.AddRange(from resource in privateResources
                                     let id = Guid.NewGuid().ToString()
                                              select new Permission()
                {
                    Id         = id,
                    RoleId     = systemAdminRole.Id,
                    ResourceId = resource.Id,
                    TenantId   = tenant?.Id
                });
            }

            #endregion


            #region Admin Role Permission

            var adminRole      = roles.FirstOrDefault(x => x.Name == StaticRoles.Admin.Name);
            var adminResources = privateResources.Where(x => x.ResourceOwner == ResourceOwner.Tenant || x.ResourceOwner == ResourceOwner.Both).ToList();

            permissions.AddRange(from privateResource in adminResources
                                 let id = Guid.NewGuid().ToString()
                                          select new Permission()
            {
                Id         = id,
                RoleId     = adminRole?.Id,
                ResourceId = privateResource.Id,
                TenantId   = tenant?.Id
            });

            #endregion


            foreach (var permission in permissions)
            {
                if (!db.Permissions.Any(x => x.RoleId == permission.RoleId && x.ResourceId == permission.ResourceId && x.TenantId == permission.TenantId))
                {
                    db.Permissions.Add(permission);
                }
            }

            db.SaveChanges();
        }
        public static void Build(BusinessDbContext db)
        {
            var resourceBinders = StaticResource.GetResources();

            if (!db.Resources.Any())
            {
                foreach (var resourceBinder in resourceBinders)
                {
                    var resource = new Resource
                    {
                        Id            = Guid.NewGuid().ToString(),
                        Name          = resourceBinder.Name,
                        Route         = resourceBinder.State,
                        IsPublic      = resourceBinder.IsPublic,
                        Order         = resourceBinder.Order,
                        DisplayName   = resourceBinder.DisplayName,
                        ResourceOwner = resourceBinder.ResourceOwner,
                        ParentRoute   = resourceBinder.ParentState
                    };
                    db.Resources.Add(resource);
                }
                db.SaveChanges();
            }
            else
            {
                foreach (var resourceBinder in resourceBinders.Where(resource => db.Resources.FirstOrDefault(x => x.Route == resource.State) == null))
                {
                    var resource = new Resource
                    {
                        Id            = Guid.NewGuid().ToString(),
                        Name          = resourceBinder.Name,
                        Route         = resourceBinder.State,
                        IsPublic      = resourceBinder.IsPublic,
                        Order         = resourceBinder.Order,
                        DisplayName   = resourceBinder.DisplayName,
                        ResourceOwner = resourceBinder.ResourceOwner,
                        ParentRoute   = resourceBinder.ParentState
                    };
                    db.Resources.Add(resource);
                }
                db.SaveChanges();
            }
        }
        private static void AddEditionFeature(BusinessDbContext context)
        {
            var            staticEditionFeatures = StaticEditionFeature.GetAll();
            List <Feature> features = new List <Feature>();

            var editions = context.Editions.ToList();

            foreach (var staticEditionFeature in staticEditionFeatures)
            {
                var edition = editions.FirstOrDefault(x => x.Name == staticEditionFeature.EditionName);
                if (edition != null)
                {
                    Feature feature = new Feature
                    {
                        Id         = Guid.NewGuid().ToString(),
                        Active     = true,
                        Created    = DateTime.Now,
                        CreatedBy  = null,
                        Modified   = DateTime.Now,
                        ModifiedBy = null,

                        EditionId = edition.Id,
                        Name      = staticEditionFeature.Name,
                        Value     = staticEditionFeature.Value,
                        ValueType = staticEditionFeature.ValueType,

                        Order = staticEditionFeature.Order,

                        IsEnabled        = true,
                        IsFeature        = false,
                        IsEditionFeature = true,
                        IsTenantFeature  = false
                    };

                    features.Add(feature);
                }
            }

            if (!context.Features.Any())
            {
                context.Features.AddRange(features);
            }
            else
            {
                foreach (var feature in features)
                {
                    if (!context.Features.Any(x =>
                                              x.Name == feature.Name && !x.IsFeature && x.IsEditionFeature && !x.IsTenantFeature))
                    {
                        context.Features.Add(feature);
                    }
                }
            }
            context.SaveChanges();
        }
        private async Task GetUSGS(BusinessDbContext context)
        {
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync(USGS);


                if (!response.IsSuccessStatusCode)
                {
                    Log.Error("Failed to pull from USGS");
                }

                var admin = context.Admins.FirstOrDefault();
                if (admin == null)
                {
                    throw new ProcessEventException("Could not find an admin to create new events");
                }

                var resultStr = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject <EarthquakeSourceWrapper>(resultStr);
                foreach (var feature in result.Features)
                {
                    var attr = feature.Attributes;

                    var existing = context.Notifications.FirstOrDefault(x => x.SourceId == "USGS" + attr.Id);
                    if (existing != null)
                    {
                        continue;
                    }

                    DateTime created;
                    var      didGetDate = DateTime.TryParse(attr.ObserveDateTime, out created);
                    var      noti       = new Notification()
                    {
                        Title    = attr.Magnitude + " magnitude earthquake",
                        Details  = attr.Region,
                        Location = new PostgisPoint(attr.Latitude, attr.Longititude)
                        {
                            SRID = Constants.SRID
                        },
                        Category = Category.Earthquake,
                        Source   = "USGS",
                        SourceId = "USGS" + attr.Id,
                        Severity = attr.Magnitude > 5 ? Severity.Emergency : Severity.NonEmergency,
                        Status   = NotiStatus.New,
                        Created  = (didGetDate) ? created : DateTime.Now,
                        AuthorId = admin.Id
                    };
                    context.Notifications.Add(noti);
                    context.SaveChanges();
                }
            }
        }
Beispiel #24
0
        public ActionResult Regist([FromForm] AccountDto input)
        {
            if (string.IsNullOrEmpty(input.MailAddress))
            {
                throw new Exception("请填写邮箱!");
            }
            if (string.IsNullOrEmpty(input.AccountNo))
            {
                throw new Exception("请填写账号!");
            }
            if (string.IsNullOrEmpty(input.Password))
            {
                throw new Exception("请填写密码!");
            }
            string str   = MD5Helper.MD5Encrypt32(input.Password);
            var    model = new Account
            {
                AccountNo   = input.AccountNo,
                MailAddress = input.MailAddress.Trim(),
                Password    = str,
                Status      = AccountStatus.Enabled
            };
            var account = _context.Account.Add(model).Entity;

            _context.SaveChanges();
            var      role     = _context.Role.FirstOrDefault(_ => _.RoleName == "普通用户");
            UserRole userrole = new UserRole
            {
                RoleId = role.Id,
                UserId = account.Id
            };

            _context.UserRole.Add(userrole);
            _context.SaveChanges();
            return(Ok(new ResultViewModel
            {
                success = true,
                data = "注册成功",
                msg = "注册成功"
            }));
        }
Beispiel #25
0
        public virtual IActionResult DeleteAdminById([FromRoute] string id)
        {
            var admin = _context.Admins.FirstOrDefault(x => x.Id.ToString() == id);

            if (admin == null)
            {
                // Our response is vague to avoid leaking information
                return(ResponseShell.Error(Constants.Messages.UserNotFound));
            }

            _context.AllUsers.Remove(admin);
            _context.SaveChanges();

            return(ResponseShell.Ok());
        }
        private async Task Broadcast(string connectionString, ValidationSender sender, List <Rows> users, Notification notification)
        {
            var options = new DbContextOptionsBuilder <BusinessDbContext>();

            options.UseNpgsql(connectionString);


            using (var context = new BusinessDbContext(options.Options))
            {
                foreach (var user in users)
                {
                    try
                    {
                        if (user.ValidatedSms && user.EnabledSms && !string.IsNullOrWhiteSpace(user.PhoneNumber))
                        {
                            Log.Information("Sending out notification to {phone}", user.PhoneNumber);
                            await sender.SendMSMessage(user.PhoneNumber, notification);

                            context.NotificationLog.Add(new BroadCastLogEntry()
                            {
                                NotificationId = notification.Id.Value,
                                UserId         = user.Id,
                                Type           = LogType.Email
                            });
                        }
                        if (user.ValidatedEmail && user.EnabledEmail && !string.IsNullOrEmpty(user.Email))
                        {
                            Log.Information("Sending out notification to {email}", user.Email);
                            await sender.SendEmailMessage(user.Email, notification);

                            context.NotificationLog.Add(new BroadCastLogEntry()
                            {
                                NotificationId = notification.Id.Value,
                                UserId         = user.Id,
                                Type           = LogType.Sms
                            });
                        }

                        context.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Log.Error(e, "Error when broadcasting to user {user}", user);
                    }
                }
                return;
            }
        }
        public WebAdmin Process(BusinessDbContext context)
        {
            var validatedUser = context.Admins.FirstOrDefault(x => x.Email == this.Email);

            if (validatedUser != null)
            {
                return(validatedUser);
            }

            validatedUser = new WebAdmin(Name, Email, Password);
            var result = context.AllUsers.Add(validatedUser);

            context.SaveChanges();
            Log.Information("Created in Admin {Admin}", validatedUser);
            return(validatedUser);
        }
        public Notification Process(BusinessDbContext context, string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ProcessEventException("Could not get the id of the author creating the request");
            }

            var guid = new Guid(id);

            var admin = context.Admins.FirstOrDefault(x => x.Id == guid);

            if (admin == null)
            {
                throw new ProcessEventException("Could not identify the admin which is trying to make the request. Make sure your passing the authentication token of an admin");
            }


            var affectedCoordinates = AffectedArea.Coordinates.Select(coor => new Coordinate2D(coor[0], coor[1])).ToArray();
            var notification        = new Notification()
            {
                Title    = Title,
                Details  = Details,
                Location = new PostgisPoint(Location.Coordinates[0], Location.Coordinates[1])
                {
                    SRID = Constants.SRID
                },
                AffectedArea = new PostgisPolygon(new[]
                {
                    affectedCoordinates
                }),
                Category = Category,
                Source   = Source,
                Severity = Severity,
                Status   = NotiStatus.New,
                Created  = DateTime.Now,
                AuthorId = new Guid(id),
            };


            context.Notifications.Add(notification);
            context.SaveChanges();
            return(notification);
        }
        public static void CreateFiscalYear(BusinessDbContext db, string tenantId = null)
        {
            var tenantIds = string.IsNullOrWhiteSpace(tenantId)
                ? db.Tenants.Select(x => x.Id).ToList()
                : new List <string>()
            {
                tenantId
            };

            foreach (var id in tenantIds)
            {
                var start = new DateTime(DateTime.Today.Year, 1, 1).Date;
                var end   = start.AddYears(1).Date.AddDays(-1);

                var company = db.Companies.FirstOrDefault(x => x.TenantId == id);
                for (int i = 0; i < 10; i++)
                {
                    var fiscalYear = new FiscalYear()
                    {
                        Id        = Guid.NewGuid().ToString(),
                        Created   = DateTime.Now,
                        CreatedBy = null,
                        Active    = true,

                        StartDate = start,
                        EndDate   = end,

                        TenantId  = id,
                        CompanyId = company?.Id
                    };

                    if (!db.FiscalYears.Any(x => x.TenantId == id && x.StartDate == start && x.EndDate == end))
                    {
                        db.FiscalYears.Add(fiscalYear);
                        db.SaveChanges();
                    }

                    start = end.Date.AddDays(1).Date;
                    end   = start.AddYears(1).Date.AddDays(-1);
                }
            }
        }
        static void Main(string[] args)
        {
            Catalog catalog = new Catalog()
            {
                Code = "001",
                Name = "A",
            };

            BusinessDbContext db = new BusinessDbContext();

            db.Catalogs.Add(catalog);
            int rowAffected = db.SaveChanges();

            if (rowAffected > 0)
            {
                Console.WriteLine("Successfully");
            }

            Console.ReadKey();
        }