コード例 #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FormService"/> class.
 /// </summary>
 public FormService()
 {
     this.applicationManager = Global.DependencyInjectionContainer.Resolve<ApplicationManager>();
     this.organisationManager = Global.DependencyInjectionContainer.Resolve<OrganisationManager>();
     this.securityGateway = Global.DependencyInjectionContainer.Resolve<ISecurityService>();
     if (Global.DependencyInjectionContainer.IsRegistered<IApplicationManagerEventHandler>())
     {
         Global.DependencyInjectionContainer.Resolve<IApplicationManagerEventHandler>()
             .Register(this.applicationManager);
     }
 }
コード例 #2
0
        public void GetAllOrganisations_Successfull()
        {
            //Arrange
            OrganisationManager organisationManager = new OrganisationManager("test");

            //Act
            var result = organisationManager.GetAllOrganisations();

            //Assert
            Assert.AreEqual(2, result.Count);
        }
コード例 #3
0
        public void GetOrganisationByID_IDisNull()
        {
            //Arrange
            OrganisationManager organisationManager = new OrganisationManager("test");
            string OrgID = null;

            //Act
            var result = organisationManager.GetOrganisationByID(OrgID);

            //Assert
            Assert.IsNull(result);
        }
コード例 #4
0
        public void GetOrganisationByID_Successfull()
        {
            //Arrange
            OrganisationManager organisationManager = new OrganisationManager("test");
            string OrgID = "1";

            //Act
            var result = organisationManager.GetOrganisationByID(OrgID);

            //Assert
            Assert.AreEqual("1", result.ID);
        }
コード例 #5
0
        public void CreateHostLink_Successfull()
        {
            //Arrange
            OrganisationManager organisationManager = new OrganisationManager("test");
            string OrgID         = "1";
            string CorrectString = $"https://f4dedtournaments-dev-as.azurewebsites.net/Tournament/CreateTournament?OrganisationID={OrgID}";


            //Act
            var result = organisationManager.CreateHostLink(OrgID);

            //Assert
            Assert.AreEqual(CorrectString, result);
        }
コード例 #6
0
        public void Initialize()
        {
            playlistManager          = new PlaylistManager(new PlaylistRepository(new EFDbContext(ContextEnum.BeatBuddyTest)), new UserRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            userManager              = new UserManager(new UserRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            organisationManager      = new OrganisationManager(new OrganisationRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            _userWithOrganisation    = userManager.CreateUser("*****@*****.**", "matthias", "test", "acidshards", "");
            _userWithoutOrganisation = userManager.CreateUser("*****@*****.**", "heylen", "jos", "acidshards", "");

            playlist = playlistManager.CreatePlaylistForUser("testplaylist", "gekke playlist om te testen", "125", 5, true, "", _userWithOrganisation);
            _userControllerWithAuthenticatedUserWithOrganisation = MyWebApi.Controller <UserController>()
                                                                   .WithResolvedDependencyFor <PlaylistManager>(playlistManager)
                                                                   .WithResolvedDependencyFor <UserManager>(userManager)
                                                                   .WithResolvedDependencyFor <OrganisationManager>(organisationManager)
                                                                   .WithAuthenticatedUser(
                u => u.WithIdentifier("NewId")
                .WithUsername(_userWithOrganisation.Email)
                .WithClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, _userWithOrganisation.Email))
                .WithClaim(new System.Security.Claims.Claim("sub", _userWithOrganisation.Email))
                );

            _userControllerWithAuthenticatedUserWithoutOrganisation = MyWebApi.Controller <UserController>()
                                                                      .WithResolvedDependencyFor <PlaylistManager>(playlistManager)
                                                                      .WithResolvedDependencyFor <UserManager>(userManager)
                                                                      .WithResolvedDependencyFor <OrganisationManager>(organisationManager)
                                                                      .WithAuthenticatedUser(
                u => u.WithIdentifier("NewId")
                .WithUsername(_userWithOrganisation.Email)
                .WithClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, _userWithoutOrganisation.Email))
                .WithClaim(new System.Security.Claims.Claim("sub", _userWithoutOrganisation.Email))
                );

            Track track = new Track()
            {
                Artist      = "Metallica",
                Title       = "Master of Puppets (live)",
                CoverArtUrl = "",
                Duration    = 800,
                TrackSource = new TrackSource
                {
                    SourceType = SourceType.YouTube,
                    Url        = "https://www.youtube.com/watch?v=kV-2Q8QtCY4"
                }
            };
            Track addedtrack = playlistManager.AddTrackToPlaylist(playlist.Id, track);


            organisation = organisationManager.CreateOrganisation("gek organisatie test", "", _userWithOrganisation);
        }
コード例 #7
0
        public void CreateOrganisation_NameUsed()
        {
            //Arrange
            OrganisationManager organisationManager = new OrganisationManager("test");
            OrganisationDTO     organisationDTO     = new OrganisationDTO()
            {
                ID = "",
                CountryOfOrigin = Countries.France,
                Description     = "Test Description",
                Name            = "A used name",
            };

            //Act
            var result = organisationManager.CreateOrganisation(organisationDTO);

            //Assert
            Assert.AreEqual(OrganisationErrorCodes.NameAlreadyExists, result);
        }
コード例 #8
0
        public void CreateOrganisation_Successfull()
        {
            //Arrange
            OrganisationManager organisationManager = new OrganisationManager("test");
            OrganisationDTO     organisationDTO     = new OrganisationDTO()
            {
                ID = "",
                CountryOfOrigin = Countries.France,
                Description     = "Test Description",
                Name            = "Test Name",
            };

            //Act
            var result = organisationManager.CreateOrganisation(organisationDTO);

            //Assert
            Assert.AreEqual(OrganisationErrorCodes.NoError, result);
        }
コード例 #9
0
        public void Initialize()
        {
            userManager         = new UserManager(new UserRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            organisationManager = new OrganisationManager(new OrganisationRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            user = userManager.CreateUser("*****@*****.**", "matthias", "test", "acidshards", "");

            _organisationControllerWithAuthenticatedUser = MyWebApi.Controller <OrganisationsController>()
                                                           .WithResolvedDependencyFor <IUserManager>(userManager)
                                                           .WithResolvedDependencyFor <IOrganisationManager>(organisationManager)
                                                           .WithAuthenticatedUser(
                u => u.WithIdentifier("NewId")
                .WithUsername(user.Email)
                .WithClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, user.Email))
                .WithClaim(new System.Security.Claims.Claim("sub", user.Email))
                );

            organisation = organisationManager.CreateOrganisation("testorganisatie", "", user);
        }
コード例 #10
0
        public async Task <ActionResult> SignUp(SignUpViewModel model, FormCollection collection)
        {
            try
            {
                if (model.Password == model.ConfirmPassword)
                {
                    if (model.IsManager == true)
                    {
                        string code = collection.Get("CountryCode");
                        string cell = string.Empty;
                        if (model.Cell.StartsWith("0"))
                        {
                            cell = code + model.Cell.Substring(0, 1);
                        }
                        else
                        {
                            cell = code + model.Cell;
                        }

                        Organisation        newOrganisation;
                        OrganisationManager orgManager;
                        var orguser = new User
                        {
                            UserName       = model.Email,
                            Email          = model.Email,
                            FirstName      = model.FirstName,
                            LastName       = model.LastName,
                            Cell           = cell,
                            PhoneNumber    = cell,
                            IsManager      = model.IsManager,
                            EmailConfirmed = true,
                            ConnectionId   = "",
                            IsOnline       = false,
                            LastOnline     = DateTime.Now
                        };
                        if (model.Password != model.ConfirmPassword)
                        {
                            return(View(model));
                        }
                        else
                        {
                            var orgResult = await UserManager.CreateAsync(orguser, model.Password);

                            if (orgResult.Succeeded)
                            {
                                int orgId = 0;
                                newOrganisation = new Organisation()
                                {
                                    Approved = false, Name = model.OrganisationName
                                };
                                db.Organisations.Add(newOrganisation);
                                db.SaveChanges();
                                while (orgId == 0)
                                {
                                    orgId = newOrganisation.OrganisationId;
                                }
                                orgManager = new OrganisationManager()
                                {
                                    Position = "Organisation Manager", UserId = orguser.Id, OrganisationId = orgId
                                };
                                db.OrganisationManagers.Add(orgManager);
                                db.SaveChanges();
                                Email EmailFault = new Email();
                                EmailFault.ProcessOrganisation(newOrganisation, db);
                                string data_uri  = collection.Get("base64");
                                string newUserId = string.Empty;
                                while (newUserId == string.Empty)
                                {
                                    newUserId = (from x in db.Users where x.Id == orguser.Id select x.Id).FirstOrDefault();
                                }
                                User newUser = (from x in db.Users where x.Id == orguser.Id select x).FirstOrDefault();
                                if (data_uri != "")
                                {
                                    string Base64 = string.Empty;
                                    if (data_uri.Contains(ExpectedImagePrefixJpeg))
                                    {
                                        Base64 = data_uri.Substring(ExpectedImagePrefixJpeg.Length);
                                    }
                                    else
                                    {
                                        Base64 = data_uri.Substring(ExpectedImagePrefixPng.Length);
                                    }
                                    byte[] bytes     = Convert.FromBase64String(Base64);
                                    string directory = "~/Content/uploads/profiles/" + newUser.Id + "/";
                                    Image  image;
                                    using (MemoryStream ms = new MemoryStream(bytes))
                                    {
                                        image = Image.FromStream(ms);
                                        if (Directory.Exists(directory))
                                        {
                                            directory.Substring(directory.Length - 1);
                                            image.Save(Server.MapPath(directory + "Profile.jpg"));
                                            newUser.UserPhotoUrl = directory + "Profile.jpg";
                                        }
                                        else
                                        {
                                            Directory.CreateDirectory(Server.MapPath(directory));
                                            directory.Substring(directory.Length - 1);
                                            image.Save(Server.MapPath(directory + "Profile.jpg"));
                                            newUser.UserPhotoUrl = directory + "Profile.jpg";
                                        }
                                    }
                                }
                                db.Entry(newUser).State = System.Data.Entity.EntityState.Modified;
                                db.SaveChanges();
                                await SignInManager.SignInAsync(newUser, isPersistent : false, rememberBrowser : false);

                                return(RedirectToAction("Index", "Manage"));
                            }
                        }
                    }
                    else
                    {
                        string code = collection.Get("CountryCode");
                        string cell = string.Empty;
                        if (model.Cell.StartsWith("0"))
                        {
                            cell = code + model.Cell.Substring(0, 1);
                        }
                        else
                        {
                            cell = code + model.Cell;
                        }

                        var pUser = new User {
                            UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Cell = cell, PhoneNumber = cell, IsManager = model.IsManager, EmailConfirmed = true
                        };
                        var result = await UserManager.CreateAsync(pUser, model.Password);

                        if (result.Succeeded)
                        {
                            try
                            {
                                PublicUser publicUser = new PublicUser()
                                {
                                    UserId = pUser.Id
                                };
                                db.PublicUsers.Add(publicUser);
                                db.SaveChanges();
                                string data_uri  = collection.Get("base64");
                                string newUserId = string.Empty;
                                while (newUserId == string.Empty)
                                {
                                    newUserId = (from x in db.Users where x.Id == pUser.Id select x.Id).FirstOrDefault();
                                }
                                User newUser = (from x in db.Users where x.Id == pUser.Id select x).FirstOrDefault();

                                if (data_uri != null)
                                {
                                    string Base64 = string.Empty;
                                    if (data_uri.Contains(ExpectedImagePrefixJpeg))
                                    {
                                        Base64 = data_uri.Substring(ExpectedImagePrefixJpeg.Length);
                                    }
                                    else
                                    {
                                        Base64 = data_uri.Substring(ExpectedImagePrefixPng.Length);
                                    }
                                    byte[] bytes     = Convert.FromBase64String(Base64);
                                    string directory = "~/Content/uploads/profiles/" + newUser.Id + "/";
                                    Image  image;
                                    using (MemoryStream ms = new MemoryStream(bytes))
                                    {
                                        image = Image.FromStream(ms);
                                        if (Directory.Exists(directory))
                                        {
                                            directory.Substring(directory.Length - 1);
                                            image.Save(Server.MapPath(directory + "Profile.jpg"));
                                            newUser.UserPhotoUrl = directory + "Profile.jpg";
                                        }
                                        else
                                        {
                                            Directory.CreateDirectory(Server.MapPath(directory));
                                            directory.Substring(directory.Length - 1);
                                            image.Save(Server.MapPath(directory + "Profile.jpg"));
                                            newUser.UserPhotoUrl = directory + "Profile.jpg";
                                        }
                                    }

                                    db.Entry(newUser).State = System.Data.Entity.EntityState.Modified;
                                    db.SaveChanges();
                                    await SignInManager.SignInAsync(pUser, isPersistent : false, rememberBrowser : false);

                                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                                    // Send an email with this link
                                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                                    return(RedirectToAction("Index", "Manage"));
                                }
                            }
                            catch (Exception ex)
                            {
                                ViewBag.ErrorMessage = ex.Message;
                            }
                        }
                    }
                }
                else
                {
                    return(RedirectToAction("SignUp", "Account", new { id = 1 }));
                }
            }
            catch
            {
                return(RedirectToAction("SignUp", "Account", null));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #11
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl, FormCollection collection)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                if (model.IsManager)
                {
                    Organisation        newOrganisation;
                    OrganisationManager orgManager;
                    string code    = collection.Get("OrgCountryCode");
                    string cell    = code + model.Cell;
                    var    orguser = new User
                    {
                        UserName       = model.Email,
                        Email          = model.Email,
                        FirstName      = model.FirstName,
                        LastName       = model.LastName,
                        Cell           = cell,
                        PhoneNumber    = cell,
                        IsManager      = model.IsManager,
                        UserPhotoUrl   = model.UserPhoto,
                        EmailConfirmed = true,
                        ConnectionId   = "",
                        LastOnline     = DateTime.Now,
                        IsOnline       = false
                    };
                    var orgresult = await UserManager.CreateAsync(orguser);

                    if (orgresult.Succeeded)
                    {
                        orgresult = await UserManager.AddLoginAsync(orguser.Id, info.Login);

                        if (orgresult.Succeeded)
                        {
                            int orgId = 0;
                            newOrganisation = new Organisation()
                            {
                                Approved = false, Name = model.OrganisationName
                            };
                            db.Organisations.Add(newOrganisation);
                            db.SaveChanges();
                            while (orgId == 0)
                            {
                                orgId = newOrganisation.OrganisationId;
                            }
                            orgManager = new OrganisationManager()
                            {
                                Position = "Organisation Manager", UserId = orguser.Id, OrganisationId = orgId
                            };
                            db.OrganisationManagers.Add(orgManager);
                            db.SaveChanges();
                            Email EmailFault = new Email();
                            EmailFault.ProcessOrganisation(newOrganisation, db);
                            string data_uri  = collection.Get("orgbase64");
                            string newUserId = string.Empty;
                            while (newUserId == string.Empty)
                            {
                                newUserId = (from x in db.Users where x.Id == orguser.Id select x.Id).FirstOrDefault();
                            }
                            User newUser = (from x in db.Users where x.Id == orguser.Id select x).FirstOrDefault();
                            if (data_uri != null)
                            {
                                string Base64 = string.Empty;
                                if (data_uri.Contains(ExpectedImagePrefixJpeg))
                                {
                                    Base64 = data_uri.Substring(ExpectedImagePrefixJpeg.Length);
                                }
                                else
                                {
                                    Base64 = data_uri.Substring(ExpectedImagePrefixPng.Length);
                                }
                                byte[] bytes     = Convert.FromBase64String(Base64);
                                string directory = "~/Content/uploads/profiles/" + newUser.Id + "/";
                                Image  image;
                                using (MemoryStream ms = new MemoryStream(bytes))
                                {
                                    image = Image.FromStream(ms);
                                    if (Directory.Exists(directory))
                                    {
                                        directory.Substring(directory.Length - 1);
                                        image.Save(Server.MapPath(directory + ".jpg"));
                                        newUser.UserPhotoUrl = directory + ".jpg";
                                    }
                                    else
                                    {
                                        Directory.CreateDirectory(Server.MapPath(directory));
                                        directory.Substring(directory.Length - 1);
                                        image.Save(Server.MapPath(directory + ".jpg"));
                                        newUser.UserPhotoUrl = directory + ".jpg";
                                    }
                                }
                            }

                            db.Entry(newUser).State = System.Data.Entity.EntityState.Modified;
                            db.SaveChanges();
                            await SignInManager.SignInAsync(orguser, isPersistent : false, rememberBrowser : false);

                            return(RedirectToAction("Index", "Manage"));
                        }
                    }
                }
                else
                {
                    string code  = collection.Get("CountryCode");
                    string cell  = code + model.Cell;
                    var    pUser = new User {
                        UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Cell = cell, PhoneNumber = cell, IsManager = model.IsManager, EmailConfirmed = true
                    };
                    var result = await UserManager.CreateAsync(pUser);

                    if (result.Succeeded)
                    {
                        result = await UserManager.AddLoginAsync(pUser.Id, info.Login);

                        if (result.Succeeded)
                        {
                            PublicUser publicUser = new PublicUser()
                            {
                                UserId = pUser.Id
                            };
                            db.PublicUsers.Add(publicUser);
                            db.SaveChanges();
                            string data_uri  = collection.Get("base64");
                            string newUserId = string.Empty;
                            while (newUserId == string.Empty)
                            {
                                newUserId = (from x in db.Users where x.Id == pUser.Id select x.Id).FirstOrDefault();
                            }
                            User newUser = (from x in db.Users where x.Id == pUser.Id select x).FirstOrDefault();

                            if (data_uri != null)
                            {
                                string Base64 = string.Empty;
                                if (data_uri.Contains(ExpectedImagePrefixJpeg))
                                {
                                    Base64 = data_uri.Substring(ExpectedImagePrefixJpeg.Length);
                                }
                                else
                                {
                                    Base64 = data_uri.Substring(ExpectedImagePrefixPng.Length);
                                }
                                byte[] bytes     = Convert.FromBase64String(Base64);
                                string directory = "~/Content/uploads/profiles/" + newUser.Id + "/";
                                Image  image;
                                using (MemoryStream ms = new MemoryStream(bytes))
                                {
                                    image = Image.FromStream(ms);
                                    if (Directory.Exists(directory))
                                    {
                                        directory.Substring(directory.Length - 1);
                                        image.Save(Server.MapPath(directory + "Profile.jpg"));
                                        newUser.UserPhotoUrl = directory + "Profile.jpg";
                                    }
                                    else
                                    {
                                        Directory.CreateDirectory(Server.MapPath(directory));
                                        directory.Substring(directory.Length - 1);
                                        image.Save(Server.MapPath(directory + "Profile.jpg"));
                                        newUser.UserPhotoUrl = directory + "Profile.jpg";
                                    }
                                }
                            }
                            db.Entry(newUser).State = System.Data.Entity.EntityState.Modified;
                            db.SaveChanges();
                            await SignInManager.SignInAsync(pUser, isPersistent : false, rememberBrowser : false);

                            return(RedirectToAction("Index", "Manage"));
                        }
                    }
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
コード例 #12
0
        public ActionResult Management()
        {
            var userId = HttpContext.User.Identity.GetUserId();
            OrganisationManager orgMan = (from x in db.OrganisationManagers where x.UserId == userId select x).FirstOrDefault();

            if (orgMan == null)
            {
                return(RedirectToAction("Login", "Account", null));
            }
            else
            {
                var db = new EFDbContext();
                IEnumerable <Department>        AllDept      = null;
                IEnumerable <DepartmentManager> AllManagers  = null;
                List <Fault>                    allFaults    = null;
                IEnumerable <Fault>             OrgFaultsUR  = null;
                IEnumerable <Fault>             OrgFaultsR   = null;
                IEnumerable <DepartmentManager> OrgsManagers = null;
                List <DepartmentManager>        orgsManagers = new List <DepartmentManager>();
                int                    orgId             = 0;
                Organisation           org               = null;
                List <Fault>           orgsFaults        = new List <Fault>();
                IEnumerable <Country>  countries         = (from x in db.Countries select x).ToList();
                var                    selectCountry     = new SelectList(countries, "CountryName", "CountryName", "South Africa");
                var                    selectCountryCode = new SelectList(countries, "CountryAccessCode", "CountryName", "+27");
                IEnumerable <Category> catsForSelect     = (from x in db.Categories orderby x.Count descending select x).ToList();
                Category               firstCat          = (from x in catsForSelect select x).First();
                var                    CategorySelect    = new SelectList(catsForSelect, "CategoryId", "Name", firstCat.CategoryId);
                if (userId != null)
                {
                    orgMan = (from x in db.OrganisationManagers where x.UserId == userId select x).FirstOrDefault();
                    if (orgMan != null)
                    {
                        org         = (from x in db.Organisations where x.OrganisationId == orgMan.OrganisationId select x).FirstOrDefault();
                        orgId       = org.OrganisationId;
                        AllManagers = (from x in db.DepartmentManagers select x).ToList();
                        AllDept     = (from x in db.Departments where x.OrganisationId == orgId select x).ToList();
                        foreach (var dept in AllDept)
                        {
                            foreach (var man in AllManagers)
                            {
                                if (dept.DepartmentId == man.DepartmentId)
                                {
                                    orgsManagers.Add(man);
                                }
                            }
                        }
                        if (orgsManagers == null)
                        {
                            OrgsManagers = null;
                        }
                        else
                        {
                            OrgsManagers = orgsManagers as IEnumerable <DepartmentManager>;
                        }
                        allFaults = (from x in db.Faults select x).ToList();
                        var helper = new Helpers();
                        OrgFaultsUR = helper.GetRelevantFaults(db, org, allFaults, false);
                        OrgFaultsR  = helper.GetRelevantFaults(db, org, allFaults, true);
                    }
                }
                Department selectDept       = null;
                SelectList selectDepartment = null;
                if (AllDept.Any())
                {
                    selectDept       = (from x in AllDept select x).First();
                    selectDepartment = new SelectList(AllDept, "DepartmentId", "Name", selectDept.DepartmentId);
                }
                if (org.Approved)
                {
                    ViewBag.SelectDept        = selectDept;
                    ViewBag.SelectDepartment  = selectDepartment;
                    ViewBag.OrgFaultsUR       = OrgFaultsUR;
                    ViewBag.OrgFaultsR        = OrgFaultsR;
                    ViewBag.AllDept           = AllDept;
                    ViewBag.OrgsManagers      = OrgsManagers;
                    ViewBag.CountrySelect     = selectCountry;
                    ViewBag.CountryCodeSelect = selectCountryCode;
                    ViewBag.CategorySelect    = CategorySelect;
                    ViewBag.Org = org;
                    return(View());
                }
                else
                {
                    return(RedirectToAction("ErrorNotApproved", new { @id = org.OrganisationId }));
                }
            }
        }
コード例 #13
0
        public ActionResult Dashboard()
        {
            var userString             = HttpContext.User.Identity.GetUserId();
            OrganisationManager orgMan = (from x in db.OrganisationManagers where x.UserId == userString select x).FirstOrDefault();
            var depMan = (from x in db.DepartmentManagers where x.UserId == userString select x).FirstOrDefault();

            if (orgMan != null)
            {
                Organisation org = (from x in db.Organisations where x.OrganisationId == orgMan.OrganisationId select x).FirstOrDefault();
                if (org.Approved)
                {
                    var suburbs     = (from b in db.ReportSuburbs select b).ToList();
                    var faults      = (from q in db.Faults select q).ToList();
                    var chartValues = suburbs.GroupBy(o => o.Suburb).Select(o => new { xVal = o.Key, yVal = o.Distinct().Count() });
                    var getVals     = (from u in faults orderby u.DateCreated ascending group u by u.DateCreated.Date into t select new { day = t.Key, count = t.Count() });

                    var lineChartValues = getVals;
                    //Create a string that will act as the javascipt that will populate charts in the view
                    StringBuilder lineChartlabels     = new StringBuilder();
                    StringBuilder lineChartQuantities = new StringBuilder();
                    StringBuilder pieData             = new StringBuilder();
                    //the data needs to be started with a label id
                    lineChartlabels.Append("labels:[");
                    lineChartQuantities.Append("data: [");
                    pieData.Append("var PieData = [");
                    //Populate data from the x and y values that you have determined from your objects
                    foreach (var chartVal in chartValues)
                    {
                        var color          = "#" + Guid.NewGuid().ToString().Substring(0, 6);
                        var colorHighlight = "#" + Guid.NewGuid().ToString().Substring(0, 6);
                        //add each chart value to each label value

                        pieData.Append("{value:" + chartVal.yVal + ",color:'" + color + "',highlight:'" + colorHighlight + "',label:'" + chartVal.xVal + "'},");
                    }
                    foreach (var chartLineVal in lineChartValues)
                    {
                        lineChartlabels.Append("'" + chartLineVal.day.ToShortDateString() + "',");
                        lineChartQuantities.Append("'" + chartLineVal.count + "',");
                    }
                    //Since we had to add a comma to the end of each x/y value. We have to remove the
                    //last comma so it makes semantic sense
                    //More data to add so "]," needs to be added
                    string lineChartlabelsResult = lineChartlabels.ToString().Remove(lineChartlabels.ToString().Length - 1, 0) + "],";
                    //This is the last data to be added, so no comma needed
                    string lineChartQuantitiesResult = lineChartQuantities.ToString().Remove(lineChartQuantities.ToString().Length - 1, 0) + "]";
                    string pieResult = pieData.ToString().Remove(pieData.ToString().Length - 1, 0) + "];";

                    //Append to View
                    ViewBag.Labels     = lineChartlabelsResult.ToString();
                    ViewBag.Quantities = lineChartQuantitiesResult.ToString();
                    ViewBag.PieData    = pieResult.ToString();

                    //Create Map Canvas and populate markers
                    IEnumerable <Fault>    inFaults   = (from t in db.Faults select t).ToList();
                    IEnumerable <Category> categories = (from q in db.Categories select q).ToList();
                    double x = 0;
                    double y = 0;
                    double z = 0;

                    foreach (Fault f in inFaults)
                    {
                        var latitude  = f.Latitude * Math.PI / 180;;
                        var longitude = f.Longitude * Math.PI / 180;
                        x += Math.Cos(latitude) * Math.Cos(longitude);
                        y += Math.Cos(latitude) * Math.Sin(longitude);
                        z += Math.Sin(latitude);
                    }
                    var total = inFaults.Count();
                    x = x / total;
                    y = y / total;
                    z = z / total;

                    var centralLongitude  = (Math.Atan2(y, x)) / (Math.PI / 180);
                    var centralSquareRoot = Math.Sqrt(x * x + y * y);
                    var centralLatitude   = (Math.Atan2(z, centralSquareRoot)) / (Math.PI / 180);
                    #region Javascript String
                    //Generate javascipt to render google map
                    StringBuilder sb = new StringBuilder();
                    sb.Append("var map; function initMap(){");
                    sb.Append("map = new google.maps.Map(document.getElementById('map'), {");
                    sb.Append("zoom: 12,");
                    //Input central coordinates for initial state of the map
                    sb.Append("center: new google.maps.LatLng(" + centralLatitude.ToString().Replace(",", ".") + ", " + centralLongitude.ToString().Replace(",", ".") + "), ");
                    sb.Append("mapTypeId: google.maps.MapTypeId.TERRAIN");
                    sb.Append("});");
                    //Get Icon resource
                    sb.Append("var iconBase = '../Content/img/';");
                    sb.Append("var icons = {");
                    foreach (Category c in categories)
                    {
                        sb.Append(c.Name.ToString().Replace(" ", "") + ": {");
                        sb.Append("icon: iconBase + '" + c.Image.Replace(".png", "Pin.png") + "'");
                        sb.Append("},");
                    }
                    var ind = sb.ToString().LastIndexOf(',');
                    if (ind >= 0)
                    {
                        sb.Remove(ind, 1);
                    }
                    sb.Append(" };");
                    sb.Append("function addMarker(feature) {");
                    sb.Append("var marker = new google.maps.Marker({");
                    sb.Append("position: feature.position,");
                    sb.Append("icon: icons[feature.type].icon,");
                    sb.Append("map: map,");
                    sb.Append("opacity: feature.opacity");
                    sb.Append(" });");
                    sb.Append("}");
                    //Get marker coordinates for each fault
                    sb.Append("var features = [");
                    foreach (Fault f in inFaults)
                    {
                        Category cat = db.Categories.Find(f.CategoryId);
                        sb.Append("{");
                        sb.Append("position: new google.maps.LatLng(" + f.Latitude.ToString().Replace(",", ".") + ", " + f.Longitude.ToString().Replace(",", ".") + "),");
                        sb.Append("type: '" + cat.Name.ToString().Replace(" ", "") + "',");
                        var severity = f.SeverityId;
                        switch (severity)
                        {
                        case 1:
                            sb.Append("opacity: " + (0.1).ToString().Replace(",", "."));
                            break;

                        case 2:
                            sb.Append("opacity: " + (0.2).ToString().Replace(",", "."));
                            break;

                        case 3:
                            sb.Append("opacity: " + (0.3).ToString().Replace(",", "."));
                            break;

                        case 4:
                            sb.Append("opacity: " + (0.4).ToString().Replace(",", "."));
                            break;

                        case 5:
                            sb.Append("opacity: " + (0.5).ToString().Replace(",", "."));
                            break;

                        case 6:
                            sb.Append("opacity: " + (0.6).ToString().Replace(",", "."));
                            break;

                        case 7:
                            sb.Append("opacity: " + (0.7).ToString().Replace(",", "."));
                            break;

                        case 8:
                            sb.Append("opacity: " + (0.8).ToString().Replace(",", "."));
                            break;

                        case 9:
                            sb.Append("opacity: " + (0.9).ToString().Replace(",", "."));
                            break;

                        case 10:
                            sb.Append("opacity: " + 1);
                            break;

                        default:
                            sb.Append("opacity: " + 1);
                            break;
                        }
                        sb.Append("},");
                    }
                    var index = sb.ToString().LastIndexOf(',');
                    if (index >= 0)
                    {
                        sb.Remove(index, 1);
                    }
                    sb.Append("];");
                    sb.Append("for (var i = 0, feature; feature = features[i]; i++) {");
                    sb.Append("addMarker(feature);");
                    sb.Append("}}");
                    #endregion

                    //Supply view variables
                    #region
                    var          helper = new WeFix.Logic.Helpers();
                    string       userId = HttpContext.User.Identity.GetUserId();
                    User         user   = db.Users.Find(userId);
                    Organisation organisation;
                    if (orgMan != null)
                    {
                        organisation = db.Organisations.Find(orgMan.OrganisationId);
                    }
                    else
                    {
                        var department = (from w in db.Departments where w.DepartmentId == depMan.DepartmentId select w).FirstOrDefault();
                        organisation = db.Organisations.Find(department.OrganisationId);
                    }

                    var    departments      = (from w in db.Departments where w.OrganisationId == organisation.OrganisationId select w).ToList();
                    var    allFaults        = (from w in db.Faults select w).ToList();
                    var    resolvedFaults   = helper.GetRelevantFaults(db, organisation, allFaults, true);
                    var    unresolvedFaults = helper.GetRelevantFaults(db, organisation, allFaults, false);
                    double unassignmentRate;
                    double responseRate;
                    if ((resolvedFaults.Count() + unresolvedFaults.Count()) != 0)
                    {
                        unassignmentRate = ((from w in resolvedFaults where w.ManagerId != null select w).ToList().Count + (from w in resolvedFaults where w.ManagerId != null select w).ToList().Count) / (resolvedFaults.Count() + unresolvedFaults.Count());
                        double c = Convert.ToDouble((from w in resolvedFaults where w.ManagerId != null select w).ToList().Count);
                        double d = Convert.ToDouble((from w in unresolvedFaults where w.ManagerId != null select w).ToList().Count);
                        double a = Convert.ToDouble(resolvedFaults.Count());
                        double b = Convert.ToDouble(unresolvedFaults.Count());
                        responseRate     = (a / (a + b)) * 100;
                        unassignmentRate = ((c + d) / (a + b)) * 100;
                    }
                    else
                    {
                        unassignmentRate = 0;
                        responseRate     = 0;
                    }

                    int totalUsers     = db.Users.Count();
                    int countNewFaults = (from w in db.Faults where DbFunctions.DiffDays(w.DateCreated, DateTime.Now) > 7 select w).ToList().Count;

                    #endregion

                    ViewBag.CountNewFaults   = countNewFaults;
                    ViewBag.ResponseRate     = responseRate.ToString("#0.##");
                    ViewBag.TotalUsers       = totalUsers;
                    ViewBag.AllFaults        = allFaults;
                    ViewBag.User             = user;
                    ViewBag.UnassignmentRate = unassignmentRate.ToString("#0.##");
                    ViewBag.MapScript        = sb.ToString();
                    return(View());
                }
                else
                {
                    return(RedirectToAction("ErrorNotApproved", new { @id = org.OrganisationId }));
                }
            }
            else if (depMan != null)
            {
                var suburbs     = (from b in db.ReportSuburbs select b).ToList();
                var faults      = (from q in db.Faults select q).ToList();
                var chartValues = suburbs.GroupBy(o => o.Suburb).Select(o => new { xVal = o.Key, yVal = o.Distinct().Count() });
                var getVals     = (from u in faults orderby u.DateCreated ascending group u by u.DateCreated.Date into t select new { day = t.Key, count = t.Count() });

                var lineChartValues = getVals;
                //Create a string that will act as the javascipt that will populate charts in the view
                StringBuilder lineChartlabels     = new StringBuilder();
                StringBuilder lineChartQuantities = new StringBuilder();
                StringBuilder pieData             = new StringBuilder();
                //the data needs to be started with a label id
                lineChartlabels.Append("labels:[");
                lineChartQuantities.Append("data: [");
                pieData.Append("var PieData = [");
                //Populate data from the x and y values that you have determined from your objects
                foreach (var chartVal in chartValues)
                {
                    var color          = "#" + Guid.NewGuid().ToString().Substring(0, 6);
                    var colorHighlight = "#" + Guid.NewGuid().ToString().Substring(0, 6);
                    //add each chart value to each label value

                    pieData.Append("{value:" + chartVal.yVal + ",color:'" + color + "',highlight:'" + colorHighlight + "',label:'" + chartVal.xVal + "'},");
                }
                foreach (var chartLineVal in lineChartValues)
                {
                    lineChartlabels.Append("'" + chartLineVal.day.ToShortDateString() + "',");
                    lineChartQuantities.Append("'" + chartLineVal.count + "',");
                }
                //Since we had to add a comma to the end of each x/y value. We have to remove the
                //last comma so it makes semantic sense
                //More data to add so "]," needs to be added
                string lineChartlabelsResult = lineChartlabels.ToString().Remove(lineChartlabels.ToString().Length - 1, 0) + "],";
                //This is the last data to be added, so no comma needed
                string lineChartQuantitiesResult = lineChartQuantities.ToString().Remove(lineChartQuantities.ToString().Length - 1, 0) + "]";
                string pieResult = pieData.ToString().Remove(pieData.ToString().Length - 1, 0) + "];";

                //Append to View
                ViewBag.Labels     = lineChartlabelsResult.ToString();
                ViewBag.Quantities = lineChartQuantitiesResult.ToString();
                ViewBag.PieData    = pieResult.ToString();

                //Create Map Canvas and populate markers
                IEnumerable <Fault>    inFaults   = (from t in db.Faults select t).ToList();
                IEnumerable <Category> categories = (from q in db.Categories select q).ToList();
                double x = 0;
                double y = 0;
                double z = 0;

                foreach (Fault f in inFaults)
                {
                    var latitude  = f.Latitude * Math.PI / 180;;
                    var longitude = f.Longitude * Math.PI / 180;
                    x += Math.Cos(latitude) * Math.Cos(longitude);
                    y += Math.Cos(latitude) * Math.Sin(longitude);
                    z += Math.Sin(latitude);
                }
                var total = inFaults.Count();
                x = x / total;
                y = y / total;
                z = z / total;

                var centralLongitude  = (Math.Atan2(y, x)) / (Math.PI / 180);
                var centralSquareRoot = Math.Sqrt(x * x + y * y);
                var centralLatitude   = (Math.Atan2(z, centralSquareRoot)) / (Math.PI / 180);
                #region Javascript String
                //Generate javascipt to render google map
                StringBuilder sb = new StringBuilder();
                sb.Append("var map; initMap(){");
                sb.Append("map = new google.maps.Map(document.getElementById('map'), {");
                sb.Append("zoom: 12,");
                //Input central coordinates for initial state of the map
                sb.Append("center: new google.maps.LatLng(" + centralLatitude.ToString().Replace(",", ".") + ", " + centralLongitude.ToString().Replace(",", ".") + "), ");
                sb.Append("mapTypeId: google.maps.MapTypeId.TERRAIN");
                sb.Append("});");
                //Get Icon resource
                sb.Append("var iconBase = '../Content/img/';");
                sb.Append("var icons = {");
                foreach (Category c in categories)
                {
                    sb.Append(c.Name.ToString().Replace(" ", "") + ": {");
                    sb.Append("icon: iconBase + '" + c.Image.Replace(".png", "Pin.png") + "'");
                    sb.Append("},");
                }
                var ind = sb.ToString().LastIndexOf(',');
                if (ind >= 0)
                {
                    sb.Remove(ind, 1);
                }
                sb.Append(" };");
                sb.Append("function addMarker(feature) {");
                sb.Append("var marker = new google.maps.Marker({");
                sb.Append("position: feature.position,");
                sb.Append("icon: icons[feature.type].icon,");
                sb.Append("map: map,");
                sb.Append("opacity: feature.opacity");
                sb.Append(" });");
                sb.Append("}");
                //Get marker coordinates for each fault
                sb.Append("var features = [");
                foreach (Fault f in inFaults)
                {
                    Category cat = db.Categories.Find(f.CategoryId);
                    sb.Append("{");
                    sb.Append("position: new google.maps.LatLng(" + f.Latitude.ToString().Replace(",", ".") + ", " + f.Longitude.ToString().Replace(",", ".") + "),");
                    sb.Append("type: '" + cat.Name.ToString().Replace(" ", "") + "',");
                    var severity = f.SeverityId;
                    switch (severity)
                    {
                    case 1:
                        sb.Append("opacity: " + (0.1).ToString().Replace(",", "."));
                        break;

                    case 2:
                        sb.Append("opacity: " + (0.2).ToString().Replace(",", "."));
                        break;

                    case 3:
                        sb.Append("opacity: " + (0.3).ToString().Replace(",", "."));
                        break;

                    case 4:
                        sb.Append("opacity: " + (0.4).ToString().Replace(",", "."));
                        break;

                    case 5:
                        sb.Append("opacity: " + (0.5).ToString().Replace(",", "."));
                        break;

                    case 6:
                        sb.Append("opacity: " + (0.6).ToString().Replace(",", "."));
                        break;

                    case 7:
                        sb.Append("opacity: " + (0.7).ToString().Replace(",", "."));
                        break;

                    case 8:
                        sb.Append("opacity: " + (0.8).ToString().Replace(",", "."));
                        break;

                    case 9:
                        sb.Append("opacity: " + (0.9).ToString().Replace(",", "."));
                        break;

                    case 10:
                        sb.Append("opacity: " + 1);
                        break;

                    default:
                        sb.Append("opacity: " + 1);
                        break;
                    }
                    sb.Append("},");
                }
                var index = sb.ToString().LastIndexOf(',');
                if (index >= 0)
                {
                    sb.Remove(index, 1);
                }
                sb.Append("];");
                sb.Append("for (var i = 0, feature; feature = features[i]; i++) {");
                sb.Append("addMarker(feature);");
                sb.Append("}}");
                #endregion

                ViewBag.MapScript = sb.ToString();
                return(View());
            }
            else
            {
                return(RedirectToAction("Login", "Account", null));
            }
        }