Beispiel #1
0
        public static async void InitializeAsync(IServiceProvider serviceProvider)
        {
            Debug.AutoFlush = true;
            using (var context = new ApplicationDbContext(
                       serviceProvider.GetRequiredService <
                           DbContextOptions <ApplicationDbContext> >()))
            {
                // Look for any movies.
                IGDBApi client = Client.Create(""); //your IGDB API Key here
                if (context.Game.Any())
                {
                    return;   // db has been seeded
                }
                GameJSON[] GameJSONs = new GameJSON[1000];

                // Task.Run(async () =>
                //{
                var coverSmall     = "";
                var artworkImageId = "";
                //loop through the API and add Games to Database
                for (int i = 32001; i <= 33000; i++)
                {
                    try
                    {
                        GameJSONs = await client.QueryAsync <GameJSON>(Client.Endpoints.Games, query : "fields name,cover.*,genres.*,platforms.*,artworks.image_id,release_dates.*,involved_companies.*,aggregated_rating,storyline,summary,rating_count; where id =(" + i.ToString() + ");");

                        System.Diagnostics.Trace.WriteLine(client.ToString());



                        if (GameJSONs.FirstOrDefault() != null)
                        {
                            var genres    = "";
                            var platforms = "";
                            var developer = "";

                            var bigCover = "";
                            if (coverSmall != null)
                            {
                                foreach (var item in GameJSONs)
                                {
                                    if (item != null)
                                    {
                                        if (item.Artworks != null)
                                        {
                                            artworkImageId = item.Artworks.Values.First().ImageId;
                                        }
                                        else
                                        {
                                            artworkImageId = "";
                                        }
                                        // coverSmall = ImageHelper.GetImageUrl(imageId: artworkImageId, size: ImageSize.CoverBig, retina: false);
                                        if (artworkImageId != "")
                                        {
                                            bigCover = ImageHelper.GetImageUrl(imageId: artworkImageId, size: ImageSize.ScreenshotBig, retina: false);
                                        }
                                        foreach (var item2 in item.Genres.Values)
                                        {
                                            genres = genres + item2.Name + "/";
                                        }
                                        foreach (var item2 in item.Platforms.Values)
                                        {
                                            platforms += item2.Name + "/";
                                        }
                                        //we need to trim the storyline and summary if higher than 4000 characters
                                        if (item.Storyline.Length > 4000)
                                        {
                                            game = new Game(item.Id, item.Name, DateTimeOffset.Parse(item.ReleaseDates.Values.First().Human), "http:" + item.Cover.Value.Url, genres, platforms, item.AggregatedRating, developer, "http:" + bigCover, item.Storyline.Substring(0, 4000), item.Summary, item.AggregatedRatingCount);
                                        }
                                        else if (item.Summary.Length > 4000)
                                        {
                                            game = new Game(item.Id, item.Name, DateTimeOffset.Parse(item.ReleaseDates.Values.First().Human), "http:" + item.Cover.Value.Url, genres, platforms, item.AggregatedRating, developer, "http:" + bigCover, item.Storyline, item.Summary.Substring(0, 4000), item.AggregatedRatingCount);
                                        }
                                        else
                                        {
                                            game = new Game(item.Id, item.Name, DateTimeOffset.Parse(item.ReleaseDates.Values.First().Human), "http:" + item.Cover.Value.Url, genres, platforms, item.AggregatedRating, developer, "http:" + bigCover, item.Storyline, item.Summary, item.AggregatedRatingCount);
                                        }
                                        //used for testing locally
                                        // Game.GetAllProperties(game);
                                        if (game != null)
                                        {
                                            games.Prepend(game);
                                        }
                                        try
                                        {
                                            await context.AddAsync(game);
                                        }
                                        catch (Exception e1)
                                        {
                                            System.Diagnostics.Trace.WriteLine(e1.ToString());
                                        }
                                    }
                                    genres    = "";
                                    platforms = "";
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Trace.WriteLine(client.ToString());
                        System.Diagnostics.Trace.WriteLine(e.ToString());
                    }
                }//end for
                context.SaveChanges();
            }
        }
 public async Task AddAsync(Campaign campaign)
 {
     await _dbContext.AddAsync(campaign);
 }
        public async Task CreateExchangeAsync(Exchange exchange)
        {
            await _context.AddAsync(exchange);

            await Save();
        }
        public async Task <IActionResult> Channel(Guid id)
        {
            var currentUser = await _userManager.GetUserAsync(User);

            var userwithUserRoomList = await _dbContext.Users
                                       .Include(u => u.UserRoomList)
                                       .ThenInclude(c => c.Chatroom.Messages)
                                       .FirstOrDefaultAsync(u => u.Id == currentUser.Id);

            var currentChatroom = await _dbContext.Chatrooms
                                  .Include(u => u.ChatroomMembers.UserChatroomMembers)
                                  .ThenInclude(u => u.User)
                                  .FirstOrDefaultAsync(c => c.Id == id);

            var currentChatroomWithMembers = currentChatroom.ChatroomMembers.UserChatroomMembers.Select(u => u.User);

            if (currentChatroomWithMembers.Any(c => c.Id == currentUser.Id) == false)
            {
                var userChatroomMember = new UserChatroomMember
                {
                    ChatroomMembers = currentChatroom.ChatroomMembers,
                    User            = currentUser
                };
                await _dbContext.AddAsync(userChatroomMember);

                await _dbContext.SaveChangesAsync();
            }

            var userRoomList = new UserRoomList
            {
                Chatroom          = currentChatroom,
                ChatroomId        = id,
                ChatroomStatus    = 0,
                ApplicationUserId = currentUser.Id
            };

            if (currentUser.UserRoomList != null)
            {
                if (!((userwithUserRoomList.UserRoomList.Any(c => c.ChatroomId == currentChatroom.Id)) &&
                      (userwithUserRoomList.UserRoomList.Any(c => c.ApplicationUserId == currentUser.Id))))
                {
                    await _dbContext.AddAsync(userRoomList);

                    currentUser.UserRoomList.Add(userRoomList);
                    _dbContext.Update(currentUser);
                    await _dbContext.SaveChangesAsync();
                }
            }
            var customemodel = await _dbContext.Chatrooms
                               .Include(a => a.ChatroomMembers.UserChatroomMembers)
                               .ThenInclude(a => a.User)
                               .Include(chatroom => chatroom.Messages)
                               .Where(chatroom => chatroom.Id == id)
                               .Select(m => new ChannelViewModel
            {
                Chatroom   = m,
                ChatroomId = m.Id,
                UserId     = currentUser.Id
            }).FirstOrDefaultAsync();

            var users = _userManager.Users;

            ViewBag.Users = users.Select(x =>
                                         new SelectListItem()
            {
                Text  = x.UserName,
                Value = x.ToString()
            });
            ViewBag.UserRoomList = await _dbContext.Users
                                   .Include(u => u.UserRoomList)
                                   .ThenInclude(c => c.Chatroom.Messages)
                                   .Where(c => c.UserRoomList
                                          .Any(u => u.ApplicationUserId == currentUser.Id))
                                   .FirstOrDefaultAsync(u => u.Id == currentUser.Id);

            return(View(customemodel));
        }
Beispiel #5
0
        public async Task <bool> AddTeamAsync(Team team)
        {
            await _dbContext.AddAsync(team);

            return(await SaveAsync());
        }
Beispiel #6
0
        private async Task <bool> SaveAsync()
        {
            _dataInput = Input;
            bool value = false;

            var prueba  = Input;
            var prueba2 = ModelState;
            var stop    = "hola";

            if (ModelState.IsValid)
            {
                IdentityUser userEmailExists = _userHelper.GetUserByEmail(Input.Email);

                if (userEmailExists == null)
                {
                    var strategy = _context.Database.CreateExecutionStrategy();
                    await strategy.ExecuteAsync(async() =>
                    {
                        using (var transaction = _context.Database.BeginTransaction())
                        {
                            var user = new IdentityUser
                            {
                                Email       = Input.Email,
                                PhoneNumber = Input.PhoneNumber,
                                UserName    = Input.Email
                            };

                            try
                            {
                                var result = await _userHelper.CreateAsync(user, Input.Password);
                                if (result.Succeeded)
                                {
                                    await _userHelper.AddToRoleAsync(user, Input.Role);
                                    var dataUser  = _userHelper.GetUserByEmail(Input.Email);
                                    var imageByte = await _imageHelper.ByteAvatarImageAsync(
                                        Input.AvatarImage,
                                        _environment,
                                        "images/images/default.png");
                                    var tUser    = _converterHelper.ToTUserModel(Input);
                                    tUser.Image  = imageByte;
                                    tUser.IdUser = dataUser.Id;

                                    await _context.AddAsync(tUser);
                                    await _context.SaveChangesAsync();

                                    transaction.Commit();
                                    _dataInput = null;
                                    value      = true;
                                }
                                else
                                {
                                    _dataInput.ErrorMessage = result.Errors.ToString();
                                    value = false;
                                }
                            }
                            catch (System.Exception ex)
                            {
                                _dataInput.ErrorMessage = ex.Message;
                                transaction.Rollback();
                                value = false;
                            }
                        }
                    });
                }
                else
                {
                    _dataInput.ErrorMessage = $"There email {Input.Email} already exists";
                    value = false;
                }
            }
            else
            {
                _dataInput.ErrorMessage = "Select a Role";
                value = false;
            }

            return(value);
        }
Beispiel #7
0
 public async Task <EntityEntry <T> > AddAsync <T>(T entity) where T : User
 {
     return(await _context.AddAsync(entity));
 }
        private async Task <bool> ReportIssues(CheckStatus status, int vehicleId)
        {
            DateTime currentTime = DateTime.Now;
            bool     update      = false;
            Issue    issue;

            // Create issues to add into issues table
            if (status.Tire)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "Tire", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (status.BodyRepair)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "BodyRepair", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (status.InteriorCleaning)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "InteriorCleaning", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (status.WindowsRepair)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "Windows", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (status.DashboardLights)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "DashboardLights", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (status.ElectronicsRepair)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "Electronics", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (status.Supplies)
            {
                issue = new Issue()
                {
                    ServiceNeeded = "Supplies", VehicleId = vehicleId, TimeReported = currentTime
                };
                await _context.AddAsync(issue);

                update = true;
            }
            if (update)
            {
                await _context.SaveChangesAsync();
            }
            return(update);
        }
 public async Task AddAsync(T t) => await _context.AddAsync(t);
Beispiel #10
0
 public async Task AddAsync <T>(T added)
 {
     await db.AddAsync(added);
 }
        public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (dbContext.Apartments.Any())
            {
                return;
            }

            var apartments = new Apartment[]
            {
                new Apartment
                {
                    ApartmentNumber   = "33",
                    Floor             = 1,
                    NumberOfResidents = 1,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "34",
                    Floor             = 1,
                    NumberOfResidents = 2,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "35",
                    Floor             = 1,
                    NumberOfResidents = 6,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "36",
                    Floor             = 1,
                    NumberOfResidents = 3,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "37",
                    Floor             = 2,
                    NumberOfResidents = 2,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "38",
                    Floor             = 2,
                    NumberOfResidents = 1,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "39",
                    Floor             = 2,
                    NumberOfResidents = 1,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "40",
                    Floor             = 2,
                    NumberOfResidents = 2,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "41",
                    Floor             = 3,
                    NumberOfResidents = 2,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "42",
                    Floor             = 3,
                    NumberOfResidents = 2,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "43",
                    Floor             = 3,
                    NumberOfResidents = 1,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "44",
                    Floor             = 3,
                    NumberOfResidents = 3,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "45",
                    Floor             = 4,
                    NumberOfResidents = 3,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "46",
                    Floor             = 4,
                    NumberOfResidents = 1,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "47",
                    Floor             = 4,
                    NumberOfResidents = 2,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "48",
                    Floor             = 4,
                    NumberOfResidents = 1,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "49",
                    Floor             = 5,
                    NumberOfResidents = 3,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "50",
                    Floor             = 5,
                    NumberOfResidents = 1,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "51",
                    Floor             = 5,
                    NumberOfResidents = 2,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "52",
                    Floor             = 5,
                    NumberOfResidents = 1,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "53",
                    Floor             = 6,
                    NumberOfResidents = 2,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "54",
                    Floor             = 6,
                    NumberOfResidents = 1,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "55",
                    Floor             = 6,
                    NumberOfResidents = 2,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "56",
                    Floor             = 6,
                    NumberOfResidents = 2,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "57",
                    Floor             = 7,
                    NumberOfResidents = 1,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "58",
                    Floor             = 7,
                    NumberOfResidents = 2,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "59",
                    Floor             = 7,
                    NumberOfResidents = 3,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "60",
                    Floor             = 7,
                    NumberOfResidents = 1,
                    Area       = 85.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "61",
                    Floor             = 8,
                    NumberOfResidents = 2,
                    Area       = 68.80,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "62",
                    Floor             = 8,
                    NumberOfResidents = 2,
                    Area       = 40.25,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "63",
                    Floor             = 8,
                    NumberOfResidents = 1,
                    Area       = 59.45,
                    EntranceId = 1,
                },
                new Apartment
                {
                    ApartmentNumber   = "64",
                    Floor             = 8,
                    NumberOfResidents = 2,
                    Area       = 85.80,
                    EntranceId = 1,
                },
            };

            foreach (var apartment in apartments)
            {
                await dbContext.AddAsync(apartment);

                await dbContext.SaveChangesAsync();
            }
        }
Beispiel #12
0
        public async Task CreateUserAsync(Database.User user = null)
        {
            Database.User newUser;
            if (user is null)
            {
                newUser = (await context.AddAsync(new Database.User
                {
                    UserId = Guid.NewGuid().ToString(),
                    FirstName = "",
                    MiddleName = "",
                    LastName = "",
                    Email = ""
                })).Entity;
                await context.AddAsync(new Database.Device
                {
                    UserId   = newUser.UserId,
                    Name     = "This Device",
                    DeviceId = Guid.NewGuid(),
                    //TODO
                });
            }
            else
            {
                var id = user.UserId;
                await context.AddAsync(new Database.User
                {
                    FirstName  = user.FirstName,
                    MiddleName = user.MiddleName,
                    LastName   = user.LastName,
                    Email      = user.Email,
                    UserId     = id
                });

                await context.AddRangeAsync(
                    from item in user.Item
                    select new Database.Item
                {
                    Name   = item.Name,
                    ItemId = item.ItemId,
                    UserId = id,
                });

                await context.AddRangeAsync(
                    from device in user.Device
                    select new Database.Device
                {
                    Name     = device.Name,
                    DeviceId = device.DeviceId,
                    UserId   = id
                });

                await context.AddRangeAsync(
                    from t in user.Transaction
                    select new Database.Transaction
                {
                    TransactionId          = t.TransactionId,
                    Name                   = t.Name,
                    OccurrenceDate         = t.OccurrenceDate,
                    ExpectedCompletionDate = t.ExpectedCompletionDate,
                    CompletionDate         = t.CompletionDate,
                    Description            = t.Description,
                    TransactionType        = t.TransactionType,
                    UserId                 = id,
                    DeviceId               = t.DeviceId,
                    ItemId                 = t.ItemId
                });

                await context.AddAsync(new Database.Device
                {
                    UserId   = user.UserId,
                    Name     = "This Device",
                    DeviceId = Guid.NewGuid()
                });
            }
            await context.SaveChangesAsync();

            var thisDeviceId = context.Devices.First()?.DeviceId.ToString();

            Settings.DeviceId = thisDeviceId;
        }
        public async Task AddAsync(Client entity)
        {
            await Context.AddAsync(entity);

            Context.SaveChanges();
        }
Beispiel #14
0
 public async Task InsertCitaTecnico(CitaTecnico citaTecnico)
 {
     await _context.AddAsync(citaTecnico);
 }
Beispiel #15
0
 /// <summary>
 /// Async metod som lägger till Module
 /// </summary>
 /// <typeparam name="T">Module objekt</typeparam>
 /// <param name="added">Module som skall skapas</param>
 /// <returns></returns>
 public async Task AddAsync <T>(T added)
 {
     await m_Context.AddAsync(added);
 }
Beispiel #16
0
        public async Task <IActionResult> Register([FromBody] RegisterModel register)
        {
            var transaction = _context.Database.BeginTransaction();

            try
            {
                var user = new IdentityUser {
                    Email = register.Email, UserName = register.Email
                };
                var result = await _userManager.CreateAsync(user, register.Password);

                if (result.Succeeded)
                {
                    var account = new Account
                    {
                        Id            = KeyGen.Generate(),
                        AccounBlocked = false,
                        Address       = register.Address,
                        Contact       = register.Contact,
                        Email         = register.Email,
                        FirstName     = register.FirstName,
                        LastName      = register.LastName,
                        UserAccountId = user.Id,
                        CreateTime    = DateTime.UtcNow
                    };

                    _context.Add(account);
                    await _context.SaveChangesAsync();

                    var nresult = await _signInManager.PasswordSignInAsync(register.Email, register.Password, false, false);

                    if (nresult.Succeeded)
                    {
                        var token = GenerateJwtToken(user.Email, user);
                        //var role = new object();

                        try
                        {
                            //var getrole = _context.UserRoles.SingleOrDefault(u => u.UserId == user.Id);
                            //role = _context.Roles.SingleOrDefault(u => u.Id == getrole.RoleId);

                            var checkPrevious = _context.Tokens.AsNoTracking().SingleOrDefault(u => u.AccountId == user.Id);
                            if (checkPrevious == null)
                            {
                                var newToken = new UserTokens
                                {
                                    Id        = KeyGen.Generate(),
                                    AccountId = user.Id,
                                    Expiry    = TokenExpire,
                                    Token     = token.ToString()
                                };

                                await _context.AddAsync(newToken);

                                await _context.SaveChangesAsync();

                                transaction.Commit();
                            }
                            else
                            {
                                checkPrevious.Token  = token.ToString();
                                checkPrevious.Expiry = TokenExpire;

                                _context.Entry(checkPrevious).State = EntityState.Modified;
                                _context.Update(checkPrevious);
                                await _context.SaveChangesAsync();

                                transaction.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            return(StatusCode(200, new
                            {
                                status = 500,
                                ex.Message
                            }));
                        }
                        try
                        {
                            return(StatusCode(200, new
                            {
                                status = 100,
                                message = "Log in successful",
                                data = new
                                {
                                    user = new
                                    {
                                        id = user.Id,
                                        username = user.UserName,
                                        email = user.Email,
                                    },
                                    //role,
                                    accesstoken = new
                                    {
                                        token,
                                        expire = TokenExpire
                                    }
                                }
                            }));
                        }
                        catch (Exception ex)
                        {
                            transaction.Rollback();
                            return(StatusCode(200, new
                            {
                                status = 500,
                                ex.Message
                            }));
                        }
                    }
                    else
                    {
                        transaction.Rollback();
                        return(StatusCode(200, new
                        {
                            status = 500,
                            data = result.Errors
                        }));
                    }
                }
                else
                {
                    //return StatusCode(200, new AppResult
                    //{
                    //    Status = Statuses.Fail,
                    //    Data = result.Errors.ToList()
                    //});
                    transaction.Rollback();
                    return(StatusCode(200, new
                    {
                        status = 500,
                        data = result.Errors
                    }));
                }
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                return(StatusCode(200, new
                {
                    status = 500,
                    ex.Message
                }));
            }
        }
        public async Task <IActionResult> CreateDiary(string id, string companyId, List <InternshipTask> tasks)
        {
            var student = await context.Students
                          .Include(x => x.Internships)
                          .SingleAsync(x => x.Id == id);

            var diary = new Diary
            {
                Id          = Guid.NewGuid(),
                Student     = student,
                Internships = student.Internships.Where(x => x.IsActive).ToList(),
            };
            var internship = new Internship()
            {
                Student   = student,
                StudentId = student.Id,
                IsActive  = true,
                Diary     = diary,
                DiaryId   = diary.Id,
                CompanyId = Guid.Parse(companyId)
            };

            foreach (var studentInternship in student.Internships)
            {
                studentInternship.IsActive = false;
            }

            student.Internships.Add(internship);

            HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri("http://12cfc75fc22c.ngrok.io/");
            foreach (var task in tasks)
            {
                task.Id      = Guid.NewGuid();
                task.DiaryId = diary.Id;
                task.Id      = Guid.NewGuid();
                task.DiaryId = diary.Id;
                var response = httpClient.GetAsync($"/predict/{task.InternshipTaskName}").Result;
                if (!response.IsSuccessStatusCode)
                {
                    continue;
                }
                var res        = response.Content.ReadAsStringAsync().Result;
                var prediction = JsonConvert.DeserializeObject <Prediction>(res);
                prediction.TaskId = task.Id;
                context.Add(prediction);
                task.Prediction = prediction;
            }

            await context.AddRangeAsync(tasks);

            await context.AddAsync(diary);

            await context.AddAsync(internship);

            context.Update(student);
            await context.SaveChangesAsync();

            return(Ok(diary.Id));
        }
Beispiel #18
0
        public async Task Post(Measures model)
        {
            await _dbContext.AddAsync(model);

            await _dbContext.SaveChangesAsync();
        }
 public async Task Add(Project project)
 {
     await _context.AddAsync(project);
 }
        public async Task CreateAsync(Employee newEmployee)
        {
            await _context.AddAsync(newEmployee);

            await _context.SaveChangesAsync();
        }
Beispiel #21
0
        public async Task <ActionResult <WikiPage> > PostWikiPage()
        {
            bool parseCampaignId = int.TryParse(Request.Form["campaignID"], out int sentCampaignId);
            bool parseWikiPageId = int.TryParse(Request.Form["wikiPageID"], out int sentWikiPageId);

            if (!parseCampaignId || !parseWikiPageId || sentCampaignId == 0)
            {
                return(BadRequest());
            }

            WikiPage sentWikiPage = new WikiPage
            {
                WikiContent = string.IsNullOrWhiteSpace(Request.Form["wikiContent"]) ? "No Content has been added to this page yet." : Request.Form["wikiContent"].ToString(),
                PageName    = string.IsNullOrWhiteSpace(Request.Form["pageName"]) ? "New Page" : Request.Form["pageName"].ToString(),
                ImageFile   = (Request.Form.Files.Count > 0) ? Request.Form.Files[0] : null,
                CardContent = Request.Form["cardContent"].ToString()
            };

            string currentUser = User.FindFirstValue(ClaimTypes.NameIdentifier);

            if (sentWikiPageId != 0)
            {
                //Update Existing Wiki Page
                WikiPage currentWikiPage = _context.WikiPages.Find(sentWikiPageId);

                currentWikiPage.WikiContent = sentWikiPage.WikiContent;
                currentWikiPage.PageName    = sentWikiPage.PageName;
                currentWikiPage.CardContent = sentWikiPage.CardContent;

                if (currentWikiPage.UserId != currentUser)
                {
                    return(BadRequest());
                }

                if (!string.IsNullOrWhiteSpace(currentWikiPage.ImagePath) && sentWikiPage.ImageFile != null)
                {
                    currentWikiPage.ImageFile = sentWikiPage.ImageFile;
                    await DeleteOldImageBlobIfNotEqual(currentWikiPage);

                    currentWikiPage.ImagePath = await UploadWikiImage(currentWikiPage);
                }

                _context.Entry(currentWikiPage).State = EntityState.Modified;

                try
                {
                    await _context.SaveChangesAsync();

                    //return currentWikiPage;
                    currentWikiPage.ImageFile = null;
                    return(currentWikiPage);
                    //return CreatedAtAction("GetWikiPage", new { id = sentWikiPage.WikiPageID }, sentWikiPage);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WikiPageExists(currentWikiPage.WikiPageID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                //Create New Wiki Page
                if (!_context.Campaigns.Where(x => x.CampaignID == sentCampaignId).Any())
                {
                    return(BadRequest());
                }

                sentWikiPage.UserId     = currentUser;
                sentWikiPage.CampaignID = sentCampaignId;
                if (sentWikiPage.ImageFile != null)
                {
                    sentWikiPage.ImagePath = await UploadWikiImage(sentWikiPage);
                }

                await _context.AddAsync(sentWikiPage);

                await _context.SaveChangesAsync();

                sentWikiPage.ImageFile = null;
                return(sentWikiPage);
            }
        }
Beispiel #22
0
 public Task <bool> CreateAsync(T entity)
 {
     context.AddAsync(entity);
     return(SaveAsync());
 }
Beispiel #23
0
        public async Task CreateVideoAsync(Video video)
        {
            await _context.AddAsync(video);

            //await _context.SaveChangesAsync();
        }
 public async Task AddAsync(ApplicationUserGymClass userClass)
 {
     await _context.AddAsync(userClass);
 }
Beispiel #25
0
        public async Task Post(PizzaVotes model)
        {
            await _dbContext.AddAsync(model);

            await _dbContext.SaveChangesAsync();
        }
        public async Task <IActionResult> Approval(int id)
        {
            if (id == 0)
            {
                return(RedirectToAction(nameof(Index)));
            }
            var timesheet = await _context.Timesheets.Where(m => m.TimesheetId == id).FirstOrDefaultAsync();

            var user = await _context.Employees.Where(e => e.Id == timesheet.EmployeeId).FirstOrDefaultAsync();

            var employeePay = await _context.EmployeePays.Where(ep => ep.EmployeeId == user.Id).Where(ep => ep.Status == EmployeePay.VALID).FirstOrDefaultAsync();

            var rows = await _context.TimesheetRows.Where(r => r.TimesheetId == id).ToListAsync();

            timesheet.Status = Timesheet.SUBMITTED_APPROVED;
            user.FlexTime    = timesheet.FlexTime;

            foreach (var row in rows)
            {
                Budget budget = new Budget
                {
                    WorkPackageId = row.WorkPackageId,
                    WeekNumber    = timesheet.WeekNumber,
                    Hour          = row.SatHour + row.SunHour + row.MonHour + row.TueHour + row.WedHour + row.ThuHour + row.FriHour,
                    PayGradeId    = employeePay.PayGradeId,
                    PayGrade      = employeePay.PayGrade,
                    Status        = Budget.VALID,
                    Type          = Budget.ACTUAL,
                    WorkPackage   = row.WorkPackage
                };
                await _context.AddAsync(budget);
            }

            var vacTimesheetRow = await _context.TimesheetRows
                                  .Include(tr => tr.WorkPackage)
                                  .Where(tr => tr.TimesheetId == id)
                                  .Where(tr => tr.WorkPackage.WorkPackageCode == "VACN")
                                  .FirstOrDefaultAsync();

            if (vacTimesheetRow != null)
            {
                var vacCounter = 0.0;
                vacCounter += vacTimesheetRow.MonHour;
                vacCounter += vacTimesheetRow.TueHour;
                vacCounter += vacTimesheetRow.WedHour;
                vacCounter += vacTimesheetRow.ThuHour;
                vacCounter += vacTimesheetRow.FriHour;
                if (vacCounter > timesheet.Employee.VacationTime)
                {
                    TempData["TimesheetMessage"] = "Vacation time on the timesheet exceeds the time that the employee has.";
                    return(RedirectToAction(nameof(TimesheetView), new { id = id }));
                }
                timesheet.Employee.VacationTime -= vacCounter;
            }

            var sickTimesheetRow = await _context.TimesheetRows
                                   .Include(tr => tr.WorkPackage)
                                   .Where(tr => tr.TimesheetId == id)
                                   .Where(tr => tr.WorkPackage.WorkPackageCode == "SICK")
                                   .FirstOrDefaultAsync();

            if (sickTimesheetRow != null)
            {
                var sickCounter = 0.0;
                sickCounter += sickTimesheetRow.MonHour;
                sickCounter += sickTimesheetRow.TueHour;
                sickCounter += sickTimesheetRow.WedHour;
                sickCounter += sickTimesheetRow.ThuHour;
                sickCounter += sickTimesheetRow.FriHour;
                timesheet.Employee.SickLeave += sickCounter;
            }

            _context.Update(timesheet);
            await _userManager.UpdateAsync(user);

            _context.SaveChanges();
            await ApprovalConfirmed(id);

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #27
0
        public async Task <T> CreateAsync(T model)
        {
            await _context.AddAsync(model);

            return(model);
        }
        public async Task <IActionResult> Create(EmployeeManagement employeeManagement)
        {
            if (ModelState.IsValid)
            {
                if (_context.Employees.Where(e => e.Email == employeeManagement.Employee.Email).FirstOrDefault() != null)
                {
                    ViewBag.ErrorMessage = "There is an employee already with the email you entered.";
                    return(await Create());
                }
                employeeManagement.Employee.Status      = Employee.CURRENTLY_EMPLOYEED;
                employeeManagement.Employee.CreatedTime = DateTime.Now;
                employeeManagement.Employee.UserName    = employeeManagement.Employee.Email;
                await _userManager.CreateAsync(employeeManagement.Employee, defaultPassword);

                employeeManagement.EmployeePay.EmployeeId   = employeeManagement.Employee.Id;
                employeeManagement.EmployeePay.AssignedDate = DateTime.Now;
                employeeManagement.EmployeePay.Status       = EmployeePay.VALID;
                await _context.AddAsync(employeeManagement.EmployeePay);

                await _context.SaveChangesAsync();

                if (employeeManagement.Employee.Title == Employee.HR_MANAGER)
                {
                    await _userManager.AddToRoleAsync(employeeManagement.Employee, ApplicationRole.HR);
                }
                if (employeeManagement.Employee.Title == Employee.ADMIN)
                {
                    await _userManager.AddToRoleAsync(employeeManagement.Employee, ApplicationRole.AD);
                }

                var internalProjects = await _context.Projects
                                       .Where(p => p.Status == Project.INTERNAL)
                                       .Include(p => p.WorkPackages)
                                       .ToListAsync();

                foreach (Project internalProject in internalProjects)
                {
                    var workPackages = internalProject.WorkPackages;
                    foreach (WorkPackage workPackage in workPackages)
                    {
                        if (workPackage.WorkPackageCode == "00000")
                        {
                            continue;
                        }
                        var projectEmployee = new ProjectEmployee
                        {
                            EmployeeId    = employeeManagement.Employee.Id,
                            ProjectId     = internalProject.ProjectId,
                            WorkPackageId = workPackage.WorkPackageId,
                            Status        = ProjectEmployee.CURRENTLY_WORKING,
                            Role          = ProjectEmployee.EMPLOYEE
                        };
                        _context.Add(projectEmployee);
                        await _context.SaveChangesAsync();

                        await _userManager.AddToRoleAsync(employeeManagement.Employee, ApplicationRole.EM);
                    }
                }

                var supervisor = _context.Employees.Find(employeeManagement.Employee.SupervisorId);
                await _userManager.AddToRoleAsync(supervisor, ApplicationRole.LM);

                var approver = _context.Employees.Find(employeeManagement.Employee.ApproverId);
                await _userManager.AddToRoleAsync(approver, ApplicationRole.TA);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(employeeManagement));
        }
        public async Task <bool> Create(Item entity)
        {
            await _db.AddAsync(entity);

            return(await Save());
        }
        public async void Add(AuditViolation auditViolation)
        {
            await _context.AddAsync(auditViolation);

            await _context.SaveChangesAsync();
        }