Beispiel #1
0
        public static List <ApplicationBuild> GetLastestBuildsByApplicationAndPlatform(int appId, string platform)
        {
            List <ApplicationBuild> retval = new List <ApplicationBuild>();

            using (var context = new Repository.BetaDepotContext())
            {
                var latestBuilds = (from b in context.Builds
                                    where (b.Application == context.Applications.Where(w => w.Id == appId).FirstOrDefault()) &&
                                    (b.Platform == platform)
                                    group b by new { b.Application.Id, b.Environment } into g
                                    select new { AppId = g.Key.Id, Date = g.Max(t => t.AddedDtm) }).ToList();

                Console.Write(latestBuilds.Count());

                var join = from l in latestBuilds
                           join b in context.Builds.Include("Environment")
                           .Include("Application")
                           .Include("AddedBy")
                           on l.AppId equals b.Application.Id
                           where l.Date == b.AddedDtm
                           select b;

                retval = join.ToList();
            }

            return(retval);
        }
Beispiel #2
0
        public ActionResult Index()
        {
            HomeSummary summary = new HomeSummary();

            using (var context = new Repository.BetaDepotContext())
            {
                context.Environments.ToList().ForEach(f =>
                {
                    summary.UploadForm.Environments.Add(new Environments()
                    {
                        EnvironmentId   = f.Id,
                        EnvironmentName = f.EnvironmentName
                    });
                });

                Repository.Managers.ApplicationBuildMgr.GetAllBuildsAssignedToMember(User.Identity.GetUserName())
                .ForEach(f => {
                    summary.ApplicationBuilds.Add(new ApplicationBuildSummaryModel()
                    {
                        AppId          = f.Id,
                        AppName        = f.Application.Name,
                        Environment    = f.Environment.EnvironmentName,
                        InstallUrl     = Platforms.Common.GeneratePackageInstallUrl("App", "Download", f.Platform, f.UniqueIdentifier.ToString()),
                        Platform       = f.Platform,
                        UploadedByName = String.Format("{0} {1}", f.AddedBy.FirstName, f.AddedBy.LastName),
                        UploadedDtm    = Common.Functions.GetPrettyDate(f.AddedDtm.ToLocalTime(), "MM/dd/yy"),
                        BuildNotes     = f.Notes
                    });
                });
            }
            return(View(summary));
        }
        public static void NotifyTeamOfNewBuild(int BuildId)
        {
            Dictionary<string,string> NotificationData = new Dictionary<string,string>();
            List<String> TeamMemberEmails = new List<string>();
            using(var context = new Repository.BetaDepotContext())
            {
                var build = context.Builds.Where(w => w.Id == BuildId).FirstOrDefault();
                NotificationData.Add(TEMPLATE_KEY_UPLOADED_BY, string.Format("{0} {1}", build.AddedBy.FirstName, build.AddedBy.LastName));
                NotificationData.Add(TEMPLATE_KEY_APP_NAME, build.Application.Name);
                NotificationData.Add(TEMPLATE_KEY_APP_IDENTIFIER, build.Application.ApplicationIdentifier);
                NotificationData.Add(TEMPLATE_KEY_VERSION, build.versionNumber);
                NotificationData.Add(TEMPLATE_KEY_TARGET_ENVIRONMENT, build.Environment.EnvironmentName);
                NotificationData.Add(TEMPLATE_KEY_NOTES, build.Notes);
                NotificationData.Add(TEMPLATE_KEY_DATE_UPLOADED, String.Format("{0:g}", build.AddedDtm));
                NotificationData.Add(TEMPLATE_KEY_BETA_DEPOT_HOME_URL, Iteedee.BetaDepot.Common.Functions.GetBaseUrl());
                NotificationData.Add(TEMPLATE_KEY_BETA_DEPOT_APP_DOWNLOAD_URL, Platforms.Common.GeneratePackageInstallUrl("App", "Download", build.Platform, build.UniqueIdentifier.ToString()));
                TeamMemberEmails = context.ApplicationTeamMembers.Where(w => w.ApplicationId == build.Application.Id)
                                                                    .Select(s => s.TeamMember.EmailAddress)
                                                                    .ToList();
            }

            string template = GetEmbeddedResource(EMBEDDED_RESOURCE_BUILDNOTIFICATION_HTML);
            string emailBody = Iteedee.TextTemplater.Templify.PopulateTemplate(template, NotificationData);
            TeamMemberEmails.ForEach(f => {
                SendEmail(f, "Beta Depot - Build Notification", emailBody);
            });
            
        }
        public ActionResult Index()
        {
            HomeSummary summary = new HomeSummary();
            using (var context = new Repository.BetaDepotContext())
            {
                context.Environments.ToList().ForEach(f =>
                {
                    summary.UploadForm.Environments.Add(new Environments()
                    {
                        EnvironmentId = f.Id,
                        EnvironmentName = f.EnvironmentName
                    });
                });

                Repository.Managers.ApplicationBuildMgr.GetAllBuildsAssignedToMember(User.Identity.GetUserName())
                     .ForEach(f => {

                         summary.ApplicationBuilds.Add(new ApplicationBuildSummaryModel()
                         {
                             AppId = f.Id,
                             AppName = f.Application.Name,
                             Environment = f.Environment.EnvironmentName,
                             InstallUrl = Platforms.Common.GeneratePackageInstallUrl("App", "Download", f.Platform, f.UniqueIdentifier.ToString()),
                             Platform = f.Platform,
                             UploadedByName = String.Format("{0} {1}", f.AddedBy.FirstName, f.AddedBy.LastName),
                             UploadedDtm = Common.Functions.GetPrettyDate(f.AddedDtm.ToLocalTime(), "MM/dd/yy"),
                             BuildNotes = f.Notes

                         });
                     });
            }
            return View(summary);
        }
Beispiel #5
0
        public ActionResult ContinuousIntegration(int id, string platform)
        {
            Models.PlatformContinuousIntegration mdl = new Models.PlatformContinuousIntegration();

            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMemberInRole(User.Identity.GetUserName(), id, Common.Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR))
            {
                throw new HttpException(403, "You are not allowed to have access to this app.");
            }

            string currentUser = User.Identity.GetUserName().ToLower();

            using (var context = new Repository.BetaDepotContext())
            {
                Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                if (app != null)
                {
                    mdl.AppId      = app.Id;
                    mdl.AppName    = app.Name;
                    mdl.AppIconUrl = Platforms.Common.GenerateAppIconUrl(app.ApplicationIdentifier);
                    mdl.AppToken   = app.AppToken;
                    Repository.TeamMember CIUser = Repository.Managers.ApplicationMgr.GetSystemCIUser();
                    mdl.IsContinuousIntegrationConfigured = Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(CIUser.UserName, id);
                }
            }

            return(View(mdl));
        }
Beispiel #6
0
        public JsonResult GenerateNewTokenForApp(int id)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
            {
                throw new HttpException(403, "You are not a team member of this app.");
            }
            String token = string.Empty;

            try
            {
                using (var context = new Repository.BetaDepotContext())
                {
                    Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                    int currentTimestamp       = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    token        = Common.Functions.GenerateMD5Hash(string.Format("apptoken|{0}|{1}", app.ApplicationIdentifier.ToLower(), currentTimestamp));
                    app.AppToken = token;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                return(Json(new { Msg = Common.Constants.APPLICATION_JSON_RESULT_ERROR }));
            }


            return(Json(new
            {
                Msg = Common.Constants.APPLICATION_JSON_RESULT_SUCCESS,
                AppToken = token
            }
                        ));
        }
Beispiel #7
0
        public static List <ApplicationBuild> GetLastestBuildsByApplicationAndEnvironment(int appId, string environmentName)
        {
            List <ApplicationBuild> retval = new List <ApplicationBuild>();

            using (var context = new Repository.BetaDepotContext())
            {
                BuildEnvironment e = context.Environments.Where(w => w.EnvironmentName == environmentName).FirstOrDefault();
                int environmentId  = e == null ? -1 : e.Id;

                var latestBuilds = (from b in context.Builds
                                    where (b.Application == context.Applications.Where(w => w.Id == appId).FirstOrDefault()) &&
                                    (b.Environment == context.Environments.Where(w => w.Id == environmentId).FirstOrDefault())
                                    group b by b.Id into g
                                    select new { buildId = g.Key, Date = g.Max(t => t.AddedDtm) }).ToList();

                var join = from l in latestBuilds
                           join b in context.Builds
                           on l.buildId equals b.Id
                           select b;

                retval = join.ToList();
            }

            return(retval);
        }
Beispiel #8
0
        public static void NotifyTeamOfNewBuild(int BuildId)
        {
            Dictionary <string, string> NotificationData = new Dictionary <string, string>();
            List <String> TeamMemberEmails = new List <string>();

            using (var context = new Repository.BetaDepotContext())
            {
                var build = context.Builds.Where(w => w.Id == BuildId).FirstOrDefault();
                NotificationData.Add(TEMPLATE_KEY_UPLOADED_BY, string.Format("{0} {1}", build.AddedBy.FirstName, build.AddedBy.LastName));
                NotificationData.Add(TEMPLATE_KEY_APP_NAME, build.Application.Name);
                NotificationData.Add(TEMPLATE_KEY_APP_IDENTIFIER, build.Application.ApplicationIdentifier);
                NotificationData.Add(TEMPLATE_KEY_VERSION, build.versionNumber);
                NotificationData.Add(TEMPLATE_KEY_TARGET_ENVIRONMENT, build.Environment.EnvironmentName);
                NotificationData.Add(TEMPLATE_KEY_NOTES, build.Notes);
                NotificationData.Add(TEMPLATE_KEY_DATE_UPLOADED, String.Format("{0:g}", build.AddedDtm));
                NotificationData.Add(TEMPLATE_KEY_BETA_DEPOT_HOME_URL, Iteedee.BetaDepot.Common.Functions.GetBaseUrl());
                NotificationData.Add(TEMPLATE_KEY_BETA_DEPOT_APP_DOWNLOAD_URL, Platforms.Common.GeneratePackageInstallUrl("App", "Download", build.Platform, build.UniqueIdentifier.ToString()));
                TeamMemberEmails = context.ApplicationTeamMembers.Where(w => w.ApplicationId == build.Application.Id)
                                   .Select(s => s.TeamMember.EmailAddress)
                                   .ToList();
            }

            string template  = GetEmbeddedResource(EMBEDDED_RESOURCE_BUILDNOTIFICATION_HTML);
            string emailBody = Iteedee.TextTemplater.Templify.PopulateTemplate(template, NotificationData);

            TeamMemberEmails.ForEach(f => {
                SendEmail(f, "Beta Depot - Build Notification", emailBody);
            });
        }
Beispiel #9
0
        public JsonResult UpdateUserManagement(Models.PlatformManageAppSettings n)
        {
            try
            {
                string currentUser = User.Identity.GetUserName().ToLower();
                using (var context = new Repository.BetaDepotContext())
                {
                    var membership = context.ApplicationTeamMembers.Where(w => w.TeamMember.UserName.ToUpper() == currentUser.ToUpper() &&
                                                                          w.ApplicationId == n.AppId)
                                     .FirstOrDefault();
                    membership.ReceiveBuildNotifications = n.IsReceivingBuildNotifications;
                    context.SaveChanges();
                }
            }
            catch
            {
                return(Json(new
                {
                    Msg = Common.Constants.APPLICATION_JSON_RESULT_ERROR
                }));
            }

            return(Json(new
            {
                Msg = Common.Constants.APPLICATION_JSON_RESULT_SUCCESS
            }));
        }
Beispiel #10
0
        private static void CreateAndGetApplicationIfNoExists(string Name, string AppIdentifier, string Platform, string CurrentUserName)
        {
            Application app;

            using (var context = new Repository.BetaDepotContext())
            {
                app = context.Applications.Where(w => w.ApplicationIdentifier == AppIdentifier).FirstOrDefault();

                if (app == null)
                {
                    TeamMember member = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault();
                    app = new Application()
                    {
                        ApplicationIdentifier = AppIdentifier,
                        AssignedMembers       = new List <ApplicationTeamMember>()
                        {
                            new ApplicationTeamMember()
                            {
                                TeamMember = member,
                                MemberRole = Common.Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR
                            }
                        },
                        Name     = Name,
                        Platform = Platform
                    };
                    context.Applications.Add(app);
                    context.SaveChanges();
                }
            }
        }
Beispiel #11
0
        public JsonResult UpdateUserRole(int appId, int memberId, string roleToUpdate)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), appId, Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR))
            {
                return(Json(new {
                    Status = "Error",
                    Msg = "You are not a administrator of this app"
                }));
            }

            using (var context = new Repository.BetaDepotContext())
            {
                ApplicationTeamMember membership = context.ApplicationTeamMembers
                                                   .Where(w => w.TeamMemberId == memberId &&
                                                          w.ApplicationId == appId)
                                                   .FirstOrDefault();

                if (membership != null)
                {
                    membership.MemberRole = roleToUpdate.ToUpper();
                }

                context.SaveChanges();
            }
            return(Json(new
            {
                Status = "OK",
                Msg = ""
            }));
        }
 public static void Init()
 {
     Database.SetInitializer(new MigrateDatabaseToLatestVersion <Repository.BetaDepotContext, Repository.Migrations.Configuration>());
     using (var context = new Repository.BetaDepotContext())
     {
         context.Database.Initialize(true);
     }
 }
Beispiel #13
0
        public ActionResult TeamMembers(string platform, int id)
        {
            Models.PlatformViewTeamMembers mdl = new Models.PlatformViewTeamMembers();



            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMemberInRole(User.Identity.GetUserName(), id, Common.Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR))
            {
                throw new HttpException(403, "You are not allowed to have access to this app.");
            }

            string currentUser = User.Identity.GetUserName().ToLower();

            using (var context = new Repository.BetaDepotContext())
            {
                mdl.CurrentUsersMembershipRole = context.ApplicationTeamMembers
                                                 .Where(w => w.TeamMember.UserName.ToLower() == currentUser &&
                                                        w.ApplicationId == id).FirstOrDefault().MemberRole;
                Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                if (app != null)
                {
                    mdl.AppId      = app.Id;
                    mdl.AppName    = app.Name;
                    mdl.AppIconUrl = Platforms.Common.GenerateAppIconUrl(app.ApplicationIdentifier);
                }
                else
                {
                    return(View(mdl));
                }

                var q = (from tm in context.TeamMembers
                         join atm in context.ApplicationTeamMembers on tm.Id equals atm.TeamMemberId
                         where atm.ApplicationId == id
                         select new {
                    TeamMemberId = tm.Id,
                    EmailAddress = tm.EmailAddress,
                    FirstName = tm.FirstName,
                    LastName = tm.LastName,
                    UserName = tm.UserName,
                    AssignAppCount = tm.UserMemberships.Count(),
                    TeamMembershipRole = atm.MemberRole
                });

                q.ToList().ForEach(f => {
                    mdl.MemberList.Add(new Models.PlatformViewTeamMembers.Members()
                    {
                        UserName       = f.UserName,
                        Id             = f.TeamMemberId,
                        EmailAddress   = f.EmailAddress,
                        GravitarUrl    = string.Format("http://www.gravatar.com/avatar/{0}?s=36", Common.Functions.GenerateMD5Hash(f.EmailAddress.ToLower())),
                        Name           = Common.Functions.FormatFullName(f.FirstName, f.LastName),
                        MembershipRole = f.TeamMembershipRole,
                        AssignAppCount = f.AssignAppCount,
                    });
                });
            }
            return(View(mdl));
        }
        public static ApplicationBuild SaveBuild(string BuildNotes, string FilePath, string CurrentUserName, int environmentId)
        {
            ApplicationBuild retval = null;
            string BuildType = Platforms.Common.GetFilesBuildPlatform(Path.GetFileName(FilePath));
            Guid uniqueBuildId = new Guid(System.IO.Path.GetFileNameWithoutExtension(FilePath));
            if (BuildType.ToUpper() == Constants.BUILD_PLATFORM_ANDROID)
            {
                Platforms.Android.AndroidManifestData data = Platforms.Android.AndroidPackage.GetManifestData(FilePath);
                CreateAndGetApplicationIfNoExists(data.ApplicationName, data.PackageName, Constants.BUILD_PLATFORM_ANDROID, CurrentUserName);

                using (var context = new Repository.BetaDepotContext())
                {
                    Repository.ApplicationBuild buildToSave = new Repository.ApplicationBuild()
                    {
                        AddedDtm = DateTime.UtcNow,
                        Application = context.Applications.Where(w => w.ApplicationIdentifier == data.PackageName).FirstOrDefault(),
                        UniqueIdentifier = uniqueBuildId,
                        Notes = BuildNotes,
                        versionNumber = data.VersionName,
                        versionCode = data.VersionCode,
                        Platform = Constants.BUILD_PLATFORM_ANDROID,
                        AddedBy = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault(),
                        Environment = context.Environments.Where(w => w.Id == environmentId).FirstOrDefault()
                    };
                    context.Builds.Add(buildToSave);
                    context.SaveChanges();
                    retval = buildToSave;
                }


            }
            else if (BuildType.ToUpper() == Constants.BUILD_PLATFORM_IOS)
            {
                Platforms.iOS.iOSBundleData data = Platforms.iOS.iOSBundle.GetIPABundleData(FilePath);
                CreateAndGetApplicationIfNoExists(data.BundleAppName, data.BundleIdentifier, Constants.BUILD_PLATFORM_IOS, CurrentUserName);

                using (var context = new Repository.BetaDepotContext())
                {
                    Repository.ApplicationBuild buildToSave = new Repository.ApplicationBuild()
                    {
                        AddedDtm = DateTime.UtcNow,
                        Application = context.Applications.Where(w => w.ApplicationIdentifier == data.BundleIdentifier).FirstOrDefault(),
                        UniqueIdentifier = Guid.NewGuid(),
                        Notes = BuildNotes,
                        versionNumber = data.BundleVersion,
                        Platform = Constants.BUILD_PLATFORM_IOS,
                        AddedBy = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault(),
                        Environment = context.Environments.Where(w => w.Id == environmentId).FirstOrDefault()
                    };

                    context.Builds.Add(buildToSave);
                    context.SaveChanges();
                    retval = buildToSave;
                }
            }

            return retval;
        }
 public static TeamMember GetSystemCIUser()
 {
     TeamMember retval;
     using (var context = new Repository.BetaDepotContext())
     {
         retval = context.TeamMembers.Where(w => w.UserName == Common.Constants.APPLICATION_TEAM_MEMBER_CI_USER_NAME).FirstOrDefault();
     }
     return retval;
 }
Beispiel #16
0
        public static ApplicationBuild SaveBuild(string BuildNotes, string FilePath, string CurrentUserName, int environmentId)
        {
            ApplicationBuild retval        = null;
            string           BuildType     = Platforms.Common.GetFilesBuildPlatform(Path.GetFileName(FilePath));
            Guid             uniqueBuildId = new Guid(System.IO.Path.GetFileNameWithoutExtension(FilePath));

            if (BuildType.ToUpper() == Constants.BUILD_PLATFORM_ANDROID)
            {
                Platforms.Android.AndroidManifestData data = Platforms.Android.AndroidPackage.GetManifestData(FilePath);
                CreateAndGetApplicationIfNoExists(data.ApplicationName, data.PackageName, Constants.BUILD_PLATFORM_ANDROID, CurrentUserName);

                using (var context = new Repository.BetaDepotContext())
                {
                    Repository.ApplicationBuild buildToSave = new Repository.ApplicationBuild()
                    {
                        AddedDtm         = DateTime.UtcNow,
                        Application      = context.Applications.Where(w => w.ApplicationIdentifier == data.PackageName).FirstOrDefault(),
                        UniqueIdentifier = uniqueBuildId,
                        Notes            = BuildNotes,
                        versionNumber    = data.VersionName,
                        versionCode      = data.VersionCode,
                        Platform         = Constants.BUILD_PLATFORM_ANDROID,
                        AddedBy          = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault(),
                        Environment      = context.Environments.Where(w => w.Id == environmentId).FirstOrDefault()
                    };
                    context.Builds.Add(buildToSave);
                    context.SaveChanges();
                    retval = buildToSave;
                }
            }
            else if (BuildType.ToUpper() == Constants.BUILD_PLATFORM_IOS)
            {
                Platforms.iOS.iOSBundleData data = Platforms.iOS.iOSBundle.GetIPABundleData(FilePath);
                CreateAndGetApplicationIfNoExists(data.BundleAppName, data.BundleIdentifier, Constants.BUILD_PLATFORM_IOS, CurrentUserName);

                using (var context = new Repository.BetaDepotContext())
                {
                    Repository.ApplicationBuild buildToSave = new Repository.ApplicationBuild()
                    {
                        AddedDtm         = DateTime.UtcNow,
                        Application      = context.Applications.Where(w => w.ApplicationIdentifier == data.BundleIdentifier).FirstOrDefault(),
                        UniqueIdentifier = Guid.NewGuid(),
                        Notes            = BuildNotes,
                        versionNumber    = data.BundleVersion,
                        Platform         = Constants.BUILD_PLATFORM_IOS,
                        AddedBy          = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault(),
                        Environment      = context.Environments.Where(w => w.Id == environmentId).FirstOrDefault()
                    };

                    context.Builds.Add(buildToSave);
                    context.SaveChanges();
                    retval = buildToSave;
                }
            }

            return(retval);
        }
Beispiel #17
0
        public JsonResult ConfigureAppForCI(int id, bool shouldConfigure)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
            {
                throw new HttpException(403, "You are not a team member of this app.");
            }

            Repository.TeamMember CIUser = Repository.Managers.ApplicationMgr.GetSystemCIUser();
            try
            {
                if (shouldConfigure)
                {
                    //Check to make sure the CI user is not already a member of the APP
                    if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(CIUser.UserName, id))
                    {
                        using (var context = new Repository.BetaDepotContext())
                        {
                            Repository.Application           app        = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                            Repository.ApplicationTeamMember membership = new Repository.ApplicationTeamMember()
                            {
                                TeamMember = CIUser,
                                MemberRole = Common.Constants.APPLICATION_MEMBER_ROLE_CONTINUOUS_INTEGRATION
                            };

                            app.AssignedMembers.Add(membership);
                            context.SaveChanges();
                        }
                    }
                }
                else
                {
                    //Check to make sure the CI user is not already a member of the APP
                    if (Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
                    {
                        using (var context = new Repository.BetaDepotContext())
                        {
                            Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                            app.AppToken = null;
                            Repository.ApplicationTeamMember membership = context.ApplicationTeamMembers
                                                                          .Where(w => w.TeamMember.UserName.ToLower() == CIUser.UserName)
                                                                          .FirstOrDefault();

                            app.AssignedMembers.Remove(membership);
                            context.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(Json(new { Msg = Common.Constants.APPLICATION_JSON_RESULT_ERROR }));
            }


            return(Json(new { Msg = Common.Constants.APPLICATION_JSON_RESULT_SUCCESS }));
        }
        public static TeamMember GetSystemCIUser()
        {
            TeamMember retval;

            using (var context = new Repository.BetaDepotContext())
            {
                retval = context.TeamMembers.Where(w => w.UserName == Common.Constants.APPLICATION_TEAM_MEMBER_CI_USER_NAME).FirstOrDefault();
            }
            return(retval);
        }
        //
        // GET: /Platform/
        public ActionResult Index(string id)
        {
            string platform = id;
            Models.PlatformViewModel mdl = new Models.PlatformViewModel();
            mdl.CurrentPlatform = platform;
            using (var context = new Repository.BetaDepotContext())
            {

                if (platform != null)
                {
                    string userName = User.Identity.GetUserName();
                    List<Repository.ApplicationTeamMember> membershipList = context.ApplicationTeamMembers
                                                                .Where(wt => wt.TeamMember.UserName == userName).ToList();

                    var apps = (from a in context.Applications
                               join tm in context.ApplicationTeamMembers on a.Id equals tm.ApplicationId
                               where tm.TeamMember.UserName == userName
                               select a).ToList();

                    //List<Repository.Application> apps = context.Applications.Where(w =>
                    //            w.AssignedMembers.Contains(
                    //                            context.ApplicationTeamMembers.Where(wt => wt.TeamMember.UserName.ToLower() == userName.ToLower()).FirstOrDefault())
                    //                            && w.Platform.ToLower() == platform.ToLower()
                    //                            ).ToList();
                    foreach(Repository.Application a in apps)
                    {
                        List<Repository.ApplicationBuild> latestBuilds = Repository.Managers.ApplicationBuildMgr.GetLastestBuildsByApplicationAndPlatform(a.Id, platform);
                         foreach(Repository.ApplicationBuild b in latestBuilds)
                         {
                             mdl.Applications.Add(new Models.PlatformViewModel.PlatformBuildDetail()
                             {
                                 AppId = a.Id,
                                 AppName = a.Name,
                                 Environment = b.Environment.EnvironmentName,
                                 AppIconUrl = Platforms.Common.GenerateAppIconUrl(a.ApplicationIdentifier),
                                 InstallUrl = Platforms.Common.GeneratePackageInstallUrl("App", "Download", a.Platform, b.UniqueIdentifier.ToString()),
                                 Platform = platform,
                                 UploadedByName = String.Format("{0} {1}", b.AddedBy.FirstName, b.AddedBy.LastName),
                                 UploadedDtm = Common.Functions.GetPrettyDate(b.AddedDtm.ToLocalTime(), "MM/dd/yy"),
                                 BuildNotes = b.Notes,
                                 BuildId = b.Id,
                                 VersionNumber = b.versionNumber
                             });     
                         }
  
                    }


                }
            }

            return View(mdl);
        }
Beispiel #20
0
        public ActionResult AcceptInvite(string uHash, string rHash, int appId, string userName)
        {
            string platform = string.Empty;

            if (uHash != null &&
                rHash != null &&
                appId > 0 &&
                userName != null)
            {
                using (var context = new Repository.BetaDepotContext())
                {
                    Application app = context.Applications.Where(w => w.Id == appId).FirstOrDefault();
                    platform = app.Platform;
                    TeamMember member = context.TeamMembers.Where(w => w.UserName == userName).FirstOrDefault();
                    if (app != null && member != null)
                    {
                        if (isUserInviteTokenValid(app.ApplicationIdentifier, userName, uHash))
                        {
                            if (Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(userName, appId))
                            {
                                throw new HttpException(400, "Your invite is invalid.");
                            }

                            string role = getRoleFromRoleInviteToken(app.ApplicationIdentifier, rHash);
                            if (role != null)
                            {
                                ApplicationTeamMember membership = new ApplicationTeamMember()
                                {
                                    TeamMember = member,
                                    MemberRole = role
                                };

                                app.AssignedMembers.Add(membership);
                                context.SaveChanges();
                            }
                            else
                            {
                                throw new HttpException(400, "Your invite is invalid.");
                            }
                        }
                    }
                    else
                    {
                        throw new HttpException(400, "Your invite is invalid.");
                    }
                }
            }


            return(RedirectToAction("Index", "Platform", new { id = platform }));
        }
Beispiel #21
0
        public static bool IsUserAnAppTeamMember(string UserName, int AppId, string role)
        {
            bool retval = false;

            using (var context = new Repository.BetaDepotContext())
            {
                retval = context.Applications
                         .Where(w => w.Id == AppId)
                         .FirstOrDefault().AssignedMembers
                         .Where(w => w.TeamMember.UserName == UserName && w.MemberRole == role)
                         .Count() > 0;
            }
            return(retval);
        }
Beispiel #22
0
        //
        // GET: /Platform/
        public ActionResult Index(string id)
        {
            string platform = id;

            Models.PlatformViewModel mdl = new Models.PlatformViewModel();
            mdl.CurrentPlatform = platform;
            using (var context = new Repository.BetaDepotContext())
            {
                if (platform != null)
                {
                    string userName = User.Identity.GetUserName();
                    List <Repository.ApplicationTeamMember> membershipList = context.ApplicationTeamMembers
                                                                             .Where(wt => wt.TeamMember.UserName == userName).ToList();

                    var apps = (from a in context.Applications
                                join tm in context.ApplicationTeamMembers on a.Id equals tm.ApplicationId
                                where tm.TeamMember.UserName == userName
                                select a).ToList();

                    //List<Repository.Application> apps = context.Applications.Where(w =>
                    //            w.AssignedMembers.Contains(
                    //                            context.ApplicationTeamMembers.Where(wt => wt.TeamMember.UserName.ToLower() == userName.ToLower()).FirstOrDefault())
                    //                            && w.Platform.ToLower() == platform.ToLower()
                    //                            ).ToList();
                    foreach (Repository.Application a in apps)
                    {
                        List <Repository.ApplicationBuild> latestBuilds = Repository.Managers.ApplicationBuildMgr.GetLastestBuildsByApplicationAndPlatform(a.Id, platform);
                        foreach (Repository.ApplicationBuild b in latestBuilds)
                        {
                            mdl.Applications.Add(new Models.PlatformViewModel.PlatformBuildDetail()
                            {
                                AppId          = a.Id,
                                AppName        = a.Name,
                                Environment    = b.Environment.EnvironmentName,
                                AppIconUrl     = Platforms.Common.GenerateAppIconUrl(a.ApplicationIdentifier),
                                InstallUrl     = Platforms.Common.GeneratePackageInstallUrl("App", "Download", a.Platform, b.UniqueIdentifier.ToString()),
                                Platform       = platform,
                                UploadedByName = String.Format("{0} {1}", b.AddedBy.FirstName, b.AddedBy.LastName),
                                UploadedDtm    = Common.Functions.GetPrettyDate(b.AddedDtm.ToLocalTime(), "MM/dd/yy"),
                                BuildNotes     = b.Notes,
                                BuildId        = b.Id,
                                VersionNumber  = b.versionNumber
                            });
                        }
                    }
                }
            }

            return(View(mdl));
        }
Beispiel #23
0
        public ActionResult Platform(string platform)
        {
            HomeSummary summary = new HomeSummary();

            using (var context = new Repository.BetaDepotContext())
            {
                context.Environments.ToList().ForEach(f =>
                {
                    summary.UploadForm.Environments.Add(new Environments()
                    {
                        EnvironmentId   = f.Id,
                        EnvironmentName = f.EnvironmentName
                    });
                });

                if (platform != null)
                {
                    string userName = User.Identity.GetUserName();
                    var    apps     = context.Applications.Where(w =>
                                                                 w.AssignedMembers.Contains(
                                                                     context.ApplicationTeamMembers.Where(wt => wt.TeamMember.UserName == userName).FirstOrDefault())
                                                                 ).ToList();

                    apps.ForEach(a =>
                    {
                        List <Repository.ApplicationBuild> builds = Repository.Managers.ApplicationBuildMgr
                                                                    .GetLastestBuildsByApplicationAndPlatform(a.Id, platform);

                        if (builds != null)
                        {
                            foreach (Repository.ApplicationBuild b in builds)
                            {
                                summary.ApplicationBuilds.Add(new ApplicationBuildSummaryModel()
                                {
                                    AppId          = a.Id,
                                    AppName        = a.Name,
                                    Environment    = b.Environment.EnvironmentName,
                                    InstallUrl     = Platforms.Common.GeneratePackageInstallUrl("App", "Download", a.Platform, b.UniqueIdentifier.ToString()),
                                    Platform       = platform,
                                    UploadedByName = String.Format("{0} {1}", b.AddedBy.FirstName, b.AddedBy.LastName),
                                    UploadedDtm    = Common.Functions.GetPrettyDate(b.AddedDtm.ToLocalTime(), "MM/dd/yy"),
                                    BuildNotes     = b.Notes
                                });
                            }
                        }
                    });
                }
            }
            return(View(summary));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser()
                {
                    UserName = model.UserName
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent : false);

                    var roleresult = UserManager.AddToRole(user.Id, Common.Constants.SYSTEM_ROLE_USER);

                    //Create user as a team member
                    using (var context = new Repository.BetaDepotContext())
                    {
                        var tm = context.TeamMembers.Where(w => w.UserName == model.UserName).FirstOrDefault();
                        if (tm == null)
                        {
                            context.TeamMembers.Add(new Repository.TeamMember()
                            {
                                EmailAddress = model.UserName,
                                UserName     = model.UserName,
                                FirstName    = model.FirstName,
                                LastName     = model.LastName
                            });
                        }
                        else
                        {
                            tm.FirstName    = model.FirstName;
                            tm.LastName     = model.LastName;
                            tm.EmailAddress = model.UserName;
                        }
                        context.SaveChanges();
                    }

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public ActionResult Platform(string platform)
        {
            HomeSummary summary = new HomeSummary();
            using (var context = new Repository.BetaDepotContext())
            {
                context.Environments.ToList().ForEach(f =>
                {
                    summary.UploadForm.Environments.Add(new Environments()
                    {
                        EnvironmentId = f.Id,
                        EnvironmentName = f.EnvironmentName
                    });
                });

                if (platform != null)
                {
                    string userName = User.Identity.GetUserName();
                    var apps = context.Applications.Where(w =>
                                w.AssignedMembers.Contains(
                                                context.ApplicationTeamMembers.Where(wt => wt.TeamMember.UserName == userName).FirstOrDefault())
                                                ).ToList();

                    apps.ForEach(a =>
                    {
                        List<Repository.ApplicationBuild> builds = Repository.Managers.ApplicationBuildMgr
                                                                        .GetLastestBuildsByApplicationAndPlatform(a.Id, platform);

                        if (builds != null)
                            foreach (Repository.ApplicationBuild b in builds)
                            {
                                summary.ApplicationBuilds.Add(new ApplicationBuildSummaryModel()
                                {
                                    AppId = a.Id,
                                    AppName = a.Name,
                                    Environment = b.Environment.EnvironmentName,
                                    InstallUrl = Platforms.Common.GeneratePackageInstallUrl("App", "Download", a.Platform, b.UniqueIdentifier.ToString()),
                                    Platform = platform,
                                    UploadedByName = String.Format("{0} {1}", b.AddedBy.FirstName, b.AddedBy.LastName),
                                    UploadedDtm = Common.Functions.GetPrettyDate(b.AddedDtm.ToLocalTime(), "MM/dd/yy"),
                                    BuildNotes = b.Notes

                                });
                            }
                    });
                }

            }
            return View(summary);
        }
Beispiel #26
0
        public JsonResult GenerateInviteUrl(string email, string assignedRole, int appId)
        {
            string url = "";
            string msg = "OK";
            bool   isAlreadyTeamMember = Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(email, appId);

            if (!isAlreadyTeamMember)
            {
                int TeamMemberId = -1;
                using (var context = new Repository.BetaDepotContext())
                {
                    Application app = context.Applications.Where(w => w.Id == appId).FirstOrDefault();
                    TeamMember  tm  = context.TeamMembers.Where(w => w.UserName == email).FirstOrDefault();
                    if (tm == null)
                    {
                        tm = new TeamMember()
                        {
                            EmailAddress = email,
                            UserName     = email
                        };
                        context.TeamMembers.Add(tm);
                    }
                    context.SaveChanges();
                    TeamMemberId = tm.Id;
                    int    timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    string uHash     = Common.Functions.GenerateMD5Hash(string.Format("{0}|{1}|{2}", app.ApplicationIdentifier.ToLower(), email.ToLower(), timestamp));
                    string rHash     = Common.Functions.GenerateMD5Hash(string.Format("{0}|{1}|{2}", app.ApplicationIdentifier.ToLower(), assignedRole.ToLower(), timestamp));

                    string baseUrl = Iteedee.BetaDepot.Common.Functions.GetBaseUrl();
                    if (baseUrl == null)
                    {
                        baseUrl = "http://localhost/";
                    }
                    baseUrl = String.Format("{0}{1}", baseUrl, Url.Content("~"));
                    url     = string.Format("{0}Account/InviteRedirect/?uHash={1}&rHash={2}&appId={3}&userName={4}", baseUrl, uHash, rHash, app.Id, Url.Encode(email.ToLower()));
                }
            }
            else
            {
                msg = "Error";
            }

            return(Json(new {
                Msg = msg,
                Url = url
            }));
        }
Beispiel #27
0
        public static bool IsUserAnAppTeamMember(string UserName, int AppId)
        {
            bool retval = false;

            using (var context = new Repository.BetaDepotContext())
            {
                var apps = (from a in context.Applications
                            join tm in context.ApplicationTeamMembers on a.Id equals tm.ApplicationId
                            where tm.TeamMember.UserName == UserName &&
                            a.Id == AppId
                            select a).ToList();
                if (apps != null)
                {
                    retval = apps.Count() > 0;
                }
            }
            return(retval);
        }
Beispiel #28
0
        public JsonResult DeleteBuild(int id)
        {
            using (var context = new Repository.BetaDepotContext())
            {
                //Repository.ApplicationBuild build = context.Builds.Where(w => w.Id == id).FirstOrDefault();
                //context.Builds.Remove(build);
                //System.IO.File.Delete(Platforms.Common.GetLocalBuildFileLocation(Server.MapPath("~"),
                //                                                build.UniqueIdentifier.ToString(),
                //                                                build.Platform)
                //                        );
                //context.SaveChanges();
            }

            return(Json(new
            {
                Status = "OK",
                Msg = ""
            }));
        }
        public JsonResult DeleteBuild(int id)
        {
            using (var context = new Repository.BetaDepotContext())
            {
                //Repository.ApplicationBuild build = context.Builds.Where(w => w.Id == id).FirstOrDefault();
                //context.Builds.Remove(build);
                //System.IO.File.Delete(Platforms.Common.GetLocalBuildFileLocation(Server.MapPath("~"),
                //                                                build.UniqueIdentifier.ToString(), 
                //                                                build.Platform)
                //                        );
                //context.SaveChanges();
            }

            return Json(new
            {
                Status = "OK",
                Msg = ""
            });
        }
Beispiel #30
0
        //UNTESTED
        public static List <ApplicationBuild> GetAllBuildsAssignedToMember(string CurrentUserName)
        {
            using (var context = new Repository.BetaDepotContext())
            {
                //TeamMember currentMember = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault();
                //List<Application> apps = new List<Application>();
                //context.Applications

                var q = (from b in context.Builds.Include("Environment")
                         .Include("Application")
                         .Include("AddedBy")
                         join a in context.Applications on b.Application.Id equals a.Id
                         where a.AssignedMembers.Any(any => any.TeamMember.UserName == CurrentUserName)
                         select b).Include("Environment")
                        .Include("Application")
                        .Include("AddedBy");


                return(q.ToList());
            }
        }
Beispiel #31
0
        public ActionResult Users()
        {
            Administration.UsersViewModel mdl = new Administration.UsersViewModel();

            List <IdentityUser>          userLogins;
            List <Repository.TeamMember> memberships;

            using (var usrContext = new IdentityDbContext())
            {
                userLogins = usrContext.Users.Include("Roles.Role").ToList();
            }

            using (var context = new Repository.BetaDepotContext())
            {
                memberships = context.TeamMembers.Include("UserMemberships").Where(w => w.IsSystemUser == false).ToList();
            }


            var rm = new RoleManager <IdentityRole>(
                new RoleStore <IdentityRole>(new ApplicationDbContext()));

            foreach (var u in userLogins)
            {
                Repository.TeamMember member = memberships.Where(w => w.UserName == u.UserName).FirstOrDefault();
                if (member != null)
                {
                    mdl.AppUsers.Add(new Administration.UsersViewModel.Users()
                    {
                        AppMemberCount = member.UserMemberships.Count(),
                        EmailAddress   = member.EmailAddress,
                        UserName       = member.UserName,
                        SystemRole     = u.Roles.Select(s => s.Role.Name).Contains(Common.Constants.SYSTEM_ROLE_ADMINISTRATOR) ? Common.Constants.SYSTEM_ROLE_ADMINISTRATOR : Common.Constants.SYSTEM_ROLE_USER,
                        Name           = string.Format("{0} {1}", member.FirstName, member.LastName),
                        GravitarUrl    = string.Format("http://www.gravatar.com/avatar/{0}?s=36", Common.Functions.GenerateMD5Hash(member.EmailAddress.ToLower()))
                    });
                }
            }

            return(View(mdl));
        }
        public ActionResult Users()
        {
            Administration.UsersViewModel mdl = new Administration.UsersViewModel();

            List<IdentityUser> userLogins;
            List<Repository.TeamMember> memberships;
            using(var usrContext = new IdentityDbContext())
            {
                userLogins = usrContext.Users.Include("Roles.Role").ToList();
                
            }

            using(var context = new Repository.BetaDepotContext())
            {
                memberships = context.TeamMembers.Include("UserMemberships").Where(w => w.IsSystemUser == false).ToList();
            }


            var rm = new RoleManager<IdentityRole>(
               new RoleStore<IdentityRole>(new ApplicationDbContext()));
            foreach (var u in userLogins)
            {
                Repository.TeamMember member = memberships.Where(w => w.UserName == u.UserName).FirstOrDefault();
                if(member != null)
                {
                    mdl.AppUsers.Add(new Administration.UsersViewModel.Users()
                    {
                        AppMemberCount = member.UserMemberships.Count(),
                        EmailAddress = member.EmailAddress,
                        UserName = member.UserName,
                        SystemRole = u.Roles.Select(s => s.Role.Name).Contains(Common.Constants.SYSTEM_ROLE_ADMINISTRATOR) ? Common.Constants.SYSTEM_ROLE_ADMINISTRATOR : Common.Constants.SYSTEM_ROLE_USER,
                        Name = string.Format("{0} {1}", member.FirstName, member.LastName),
                        GravitarUrl = string.Format("http://www.gravatar.com/avatar/{0}?s=36", Common.Functions.GenerateMD5Hash(member.EmailAddress.ToLower()))
                    }); 
                }
            }

            return View(mdl);
        }
Beispiel #33
0
        public ViewResult ManageAppSettings(string platform, int id)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
            {
                throw new HttpException(403, "You are not a team member of this app.");
            }

            string currentUser = User.Identity.GetUserName().ToLower();

            Models.PlatformManageAppSettings mdl = new Models.PlatformManageAppSettings();
            using (var context = new Repository.BetaDepotContext())
            {
                var membership = context.ApplicationTeamMembers.Where(w => w.TeamMember.UserName.ToUpper() == currentUser.ToUpper() &&
                                                                      w.ApplicationId == id)
                                 .FirstOrDefault();
                if (membership != null)
                {
                    mdl.AppId = id;
                    mdl.IsReceivingBuildNotifications = membership.ReceiveBuildNotifications;
                }
            }
            return(View(mdl));
        }
        public static List<ApplicationBuild> GetLastestBuildsByApplicationAndEnvironment(int appId, string environmentName)
        {
            List<ApplicationBuild> retval = new List<ApplicationBuild>();
            using (var context = new Repository.BetaDepotContext())
            {
                BuildEnvironment e = context.Environments.Where(w => w.EnvironmentName == environmentName).FirstOrDefault();
                int environmentId = e == null ? -1 : e.Id;

                var latestBuilds = (from b in context.Builds
                                where (b.Application == context.Applications.Where(w => w.Id == appId).FirstOrDefault())
                                        && (b.Environment == context.Environments.Where(w => w.Id == environmentId).FirstOrDefault())
                                 group b by b.Id into g
                                select new { buildId = g.Key, Date = g.Max(t=>t.AddedDtm)}).ToList();

                var join = from l in latestBuilds
                           join b in context.Builds
                                on l.buildId equals b.Id
                           select b;

                retval = join.ToList();
            }

            return retval;
        }
        private static void CreateAndGetApplicationIfNoExists(string Name, string AppIdentifier, string Platform, string CurrentUserName)
        {
            Application app;
            using(var context = new Repository.BetaDepotContext())
            {
                app = context.Applications.Where(w => w.ApplicationIdentifier == AppIdentifier).FirstOrDefault();

                if (app == null)
                {
                    TeamMember member = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault();
                    app = new Application()
                    {
                        ApplicationIdentifier = AppIdentifier,
                        AssignedMembers = new List<ApplicationTeamMember>(){ 
                           new ApplicationTeamMember()
                           {
                               TeamMember = member,
                               MemberRole = Common.Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR
                           }
                        },
                        Name = Name,
                        Platform = Platform
                        
                    };
                    context.Applications.Add(app);
                    context.SaveChanges();
                }

            }
        }
 public static bool IsUserAnAppTeamMember(string UserName, int AppId, string role)
 {
     bool retval = false;
     using (var context = new Repository.BetaDepotContext())
     {
         retval = context.Applications
                 .Where(w => w.Id == AppId)
                     .FirstOrDefault().AssignedMembers
                     .Where(w => w.TeamMember.UserName == UserName && w.MemberRole == role)
                     .Count() > 0;
     }
     return retval;
 }
 //public static bool IsUserAnAppTeamMemberAndInMembershipRole(string UserName, int AppId, string role)
 //{
 //    bool retval = false;
 //    using (var context = new Repository.BetaDepotContext())
 //    {
 //        var apps = (from a in context.Applications
 //                    join tm in context.ApplicationTeamMembers on a.Id equals tm.ApplicationId
 //                    where tm.TeamMember.UserName == UserName
 //                        && a.Id == AppId
 //                        && tm.MemberRole.ToUpper() == role.ToUpper()
 //                    select a).ToList();
 //        if (apps != null)
 //            retval = apps.Count() > 0;
 //    }
 //    return retval;
 //}
 public static bool IsUserAnAppTeamMemberInRole(string UserName, int AppId, string Role)
 {
     bool retval = false;
     using (var context = new Repository.BetaDepotContext())
     {
         var apps = (from a in context.Applications
                     join tm in context.ApplicationTeamMembers on a.Id equals tm.ApplicationId
                     where tm.TeamMember.UserName.ToLower() == UserName.ToLower()
                         && a.Id == AppId
                         && tm.MemberRole.ToUpper() == Role.ToUpper()
                     select a).ToList();
         if (apps != null)
             retval = apps.Count() > 0;
     }
     return retval;
 }
        //UNTESTED
        public static List<ApplicationBuild> GetAllBuildsAssignedToMember(string CurrentUserName)
        {
            using (var context = new Repository.BetaDepotContext())
            {
                //TeamMember currentMember = context.TeamMembers.Where(w => w.UserName == CurrentUserName).FirstOrDefault();
                //List<Application> apps = new List<Application>();
                //context.Applications
                
                var q = (from b in context.Builds.Include("Environment")
                                    .Include("Application")
                                    .Include("AddedBy")
                          join a in context.Applications on b.Application.Id equals a.Id
                          where a.AssignedMembers.Any(any => any.TeamMember.UserName == CurrentUserName)
                          select b).Include("Environment")
                                    .Include("Application")
                                    .Include("AddedBy");


                return q.ToList();

            }
            
        }
        public JsonResult UpdateUserRole(int appId, int memberId, string roleToUpdate)
        {
            if(!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), appId,Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR))
            {
                return Json(new {
                    Status = "Error",
                    Msg = "You are not a administrator of this app"
                });
            }

            using(var context = new Repository.BetaDepotContext())
            {

                ApplicationTeamMember membership = context.ApplicationTeamMembers
                                            .Where(w => w.TeamMemberId == memberId
                                                        && w.ApplicationId == appId)
                                            .FirstOrDefault();

                if (membership != null)
                    membership.MemberRole = roleToUpdate.ToUpper();

                context.SaveChanges();
            }
            return Json(new
            {
                Status = "OK",
                Msg = ""
            });

        }
        public ActionResult ContinuousIntegration(int id, string platform)
        {
            Models.PlatformContinuousIntegration mdl = new Models.PlatformContinuousIntegration();

            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMemberInRole(User.Identity.GetUserName(), id, Common.Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR))
                throw new HttpException(403, "You are not allowed to have access to this app.");

            string currentUser = User.Identity.GetUserName().ToLower();

            using (var context = new Repository.BetaDepotContext())
            {
                Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                if (app != null)
                {
                    mdl.AppId = app.Id;
                    mdl.AppName = app.Name;
                    mdl.AppIconUrl = Platforms.Common.GenerateAppIconUrl(app.ApplicationIdentifier);
                    mdl.AppToken = app.AppToken;
                    Repository.TeamMember CIUser = Repository.Managers.ApplicationMgr.GetSystemCIUser();
                    mdl.IsContinuousIntegrationConfigured = Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(CIUser.UserName, id);
                }
            }
            
            return View(mdl);
        }
        public ActionResult TeamMembers(string platform, int id)
        {
            Models.PlatformViewTeamMembers mdl = new Models.PlatformViewTeamMembers();



            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMemberInRole(User.Identity.GetUserName(), id, Common.Constants.APPLICATION_MEMBER_ROLE_ADMINISTRATOR))
                throw new HttpException(403, "You are not allowed to have access to this app.");

            string currentUser = User.Identity.GetUserName().ToLower();
            
            using(var context = new Repository.BetaDepotContext())
            {
                mdl.CurrentUsersMembershipRole = context.ApplicationTeamMembers
                                                .Where(w => w.TeamMember.UserName.ToLower() == currentUser
                                                            && w.ApplicationId == id).FirstOrDefault().MemberRole;
                Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                if (app != null)
                {
                    mdl.AppId = app.Id;
                    mdl.AppName = app.Name;
                    mdl.AppIconUrl = Platforms.Common.GenerateAppIconUrl(app.ApplicationIdentifier);
                }
                else
                    return View(mdl);

                var q = (from tm in context.TeamMembers
                         join atm in context.ApplicationTeamMembers on tm.Id equals atm.TeamMemberId
                         where atm.ApplicationId == id
                         select new {
                             TeamMemberId = tm.Id,
                             EmailAddress = tm.EmailAddress,
                             FirstName = tm.FirstName,
                             LastName = tm.LastName,
                             UserName = tm.UserName,
                             AssignAppCount = tm.UserMemberships.Count(),
                             TeamMembershipRole = atm.MemberRole
                         });

                q.ToList().ForEach(f => {
                    mdl.MemberList.Add(new Models.PlatformViewTeamMembers.Members()
                        {
                            UserName = f.UserName,
                            Id = f.TeamMemberId,
                            EmailAddress = f.EmailAddress,
                            GravitarUrl = string.Format("http://www.gravatar.com/avatar/{0}?s=36", Common.Functions.GenerateMD5Hash(f.EmailAddress.ToLower())),
                            Name = Common.Functions.FormatFullName(f.FirstName, f.LastName),
                            MembershipRole = f.TeamMembershipRole,
                            AssignAppCount = f.AssignAppCount,
                            
                        });
                });

            }
            return View(mdl);
        }
        public ViewResult ManageAppSettings(string platform, int id)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
                throw new HttpException(403, "You are not a team member of this app.");

            string currentUser = User.Identity.GetUserName().ToLower();
            Models.PlatformManageAppSettings mdl = new Models.PlatformManageAppSettings();
            using (var context = new Repository.BetaDepotContext())
            {
                var membership = context.ApplicationTeamMembers.Where(w => w.TeamMember.UserName.ToUpper() == currentUser.ToUpper() 
                                                                                && w.ApplicationId == id)
                                                                .FirstOrDefault();
                if(membership != null)
                {
                    mdl.AppId = id;
                    mdl.IsReceivingBuildNotifications = membership.ReceiveBuildNotifications;
                }
            }
            return View(mdl);
        }
        public static List<ApplicationBuild> GetLastestBuildsByApplicationAndPlatform(int appId, string platform)
        {
            List<ApplicationBuild> retval = new List<ApplicationBuild>();
            using (var context = new Repository.BetaDepotContext())
            {
                var latestBuilds = (from b in context.Builds
                                 where (b.Application == context.Applications.Where(w => w.Id == appId).FirstOrDefault())
                                         && (b.Platform == platform)
                                    group b by new { b.Application.Id, b.Environment } into g
                                 select new { AppId = g.Key.Id, Date = g.Max(t => t.AddedDtm) }).ToList();

                Console.Write(latestBuilds.Count());

                var join = from l in latestBuilds
                           join b in context.Builds.Include("Environment")
                                                    .Include("Application")
                                                    .Include("AddedBy")
                                on l.AppId equals b.Application.Id
                                where l.Date == b.AddedDtm
                           select b;

                retval = join.ToList();
            }

            return retval;
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser() { UserName = model.UserName };
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    var roleresult = UserManager.AddToRole(user.Id, Common.Constants.SYSTEM_ROLE_USER);

                    //Create user as a team member
                    using (var context = new Repository.BetaDepotContext())
                    {
                        var tm = context.TeamMembers.Where(w => w.UserName == model.UserName).FirstOrDefault();
                        if (tm == null)
                        {
                            context.TeamMembers.Add(new Repository.TeamMember()
                            {
                                EmailAddress = model.UserName,
                                UserName = model.UserName,
                                FirstName = model.FirstName,
                                LastName = model.LastName
                            });
                           
                        }
                        else
                        {
                            tm.FirstName = model.FirstName;
                            tm.LastName = model.LastName;
                            tm.EmailAddress = model.UserName;
                        }
                        context.SaveChanges();
                    }

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        public JsonResult UpdateUserManagement(Models.PlatformManageAppSettings n)
        {
            try
            {
                string currentUser = User.Identity.GetUserName().ToLower();
                using (var context = new Repository.BetaDepotContext())
                {
                    var membership = context.ApplicationTeamMembers.Where(w => w.TeamMember.UserName.ToUpper() == currentUser.ToUpper()
                                                                                    && w.ApplicationId == n.AppId)
                                                                    .FirstOrDefault();
                    membership.ReceiveBuildNotifications = n.IsReceivingBuildNotifications;
                    context.SaveChanges();
                }
                     
            }  
            catch
            {
                return Json(new
                {
                    Msg = Common.Constants.APPLICATION_JSON_RESULT_ERROR
                });
            }

            return Json(new 
            {
                Msg = Common.Constants.APPLICATION_JSON_RESULT_SUCCESS
            });
        }
        public JsonResult GenerateInviteUrl(string email, string assignedRole, int appId)
        {
            string url = "";
            string msg = "OK";
            bool isAlreadyTeamMember = Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(email, appId);
            if(!isAlreadyTeamMember)
            {
                int TeamMemberId = -1;
                using(var context = new Repository.BetaDepotContext())
                {
                    Application app = context.Applications.Where(w => w.Id == appId).FirstOrDefault();
                    TeamMember tm = context.TeamMembers.Where(w => w.UserName == email).FirstOrDefault();
                    if(tm == null)
                    {
                        tm = new TeamMember()
                        {
                            EmailAddress = email,
                            UserName = email
                        };
                        context.TeamMembers.Add(tm);
                    }
                    context.SaveChanges();
                    TeamMemberId = tm.Id;
                    int timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    string uHash = Common.Functions.GenerateMD5Hash(string.Format("{0}|{1}|{2}", app.ApplicationIdentifier.ToLower(), email.ToLower(), timestamp));
                    string rHash = Common.Functions.GenerateMD5Hash(string.Format("{0}|{1}|{2}", app.ApplicationIdentifier.ToLower(), assignedRole.ToLower(), timestamp));

                    string baseUrl = Iteedee.BetaDepot.Common.Functions.GetBaseUrl();
                    if (baseUrl == null)
                        baseUrl = "http://localhost/";
                    baseUrl = String.Format("{0}{1}", baseUrl, Url.Content("~"));
                    url = string.Format("{0}Account/InviteRedirect/?uHash={1}&rHash={2}&appId={3}&userName={4}", baseUrl, uHash, rHash, app.Id, Url.Encode(email.ToLower()));
                }
            }
            else
                msg = "Error";

            return Json(new {
                Msg = msg,
                Url = url
            });
        }
        public JsonResult GenerateNewTokenForApp(int id)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
                throw new HttpException(403, "You are not a team member of this app.");
            String token = string.Empty;
            try
            {
                using (var context = new Repository.BetaDepotContext())
                {
                    Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                    int currentTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    token = Common.Functions.GenerateMD5Hash(string.Format("apptoken|{0}|{1}", app.ApplicationIdentifier.ToLower(), currentTimestamp));
                    app.AppToken = token;
                    context.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                return Json(new { Msg = Common.Constants.APPLICATION_JSON_RESULT_ERROR });
            }


            return Json(new 
                {
                    Msg = Common.Constants.APPLICATION_JSON_RESULT_SUCCESS,
                    AppToken = token
                }
            );
        }
        public ActionResult AcceptInvite(string uHash, string rHash, int appId, string userName)
        {
            string platform = string.Empty;
            if(uHash != null
                && rHash != null
                && appId > 0
                && userName != null)
            {
                using(var context = new Repository.BetaDepotContext())
                {
                    Application app = context.Applications.Where(w => w.Id == appId).FirstOrDefault();
                    platform = app.Platform;
                    TeamMember member = context.TeamMembers.Where(w => w.UserName == userName).FirstOrDefault();
                    if (app != null && member != null)
                    {
                        if(isUserInviteTokenValid(app.ApplicationIdentifier, userName, uHash))
                        {
                            if(Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(userName, appId))
                                throw new HttpException(400, "Your invite is invalid.");

                            string role = getRoleFromRoleInviteToken(app.ApplicationIdentifier, rHash);
                            if(role != null)
                            {
                                

                                ApplicationTeamMember membership =  new ApplicationTeamMember()
                                        {
                                            TeamMember = member,
                                            MemberRole = role
                                        };

                                app.AssignedMembers.Add(membership);
                                context.SaveChanges();
                            }
                            else
                                throw new HttpException(400, "Your invite is invalid.");
                        }
                    }
                    else
                        throw new HttpException(400, "Your invite is invalid.");

                }
            }
            

            return RedirectToAction("Index", "Platform", new { id = platform });

        }
        public JsonResult ConfigureAppForCI(int id, bool shouldConfigure)
        {
            if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
                throw new HttpException(403, "You are not a team member of this app.");

            Repository.TeamMember CIUser = Repository.Managers.ApplicationMgr.GetSystemCIUser();
            try
            {
                if (shouldConfigure)
                {
                    //Check to make sure the CI user is not already a member of the APP
                    if (!Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(CIUser.UserName, id))
                    {
                        using (var context = new Repository.BetaDepotContext())
                        {
                            Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                            Repository.ApplicationTeamMember membership = new Repository.ApplicationTeamMember()
                            {
                                TeamMember = CIUser,
                                MemberRole = Common.Constants.APPLICATION_MEMBER_ROLE_CONTINUOUS_INTEGRATION
                            };

                            app.AssignedMembers.Add(membership);
                            context.SaveChanges();
                        }
                    }
                }
                else
                {
                    //Check to make sure the CI user is not already a member of the APP
                    if (Repository.Managers.ApplicationBuildMgr.IsUserAnAppTeamMember(User.Identity.GetUserName(), id))
                    {
                        using (var context = new Repository.BetaDepotContext())
                        {
                            Repository.Application app = context.Applications.Where(w => w.Id == id).FirstOrDefault();
                            app.AppToken = null;
                            Repository.ApplicationTeamMember membership = context.ApplicationTeamMembers
                                                                                .Where(w => w.TeamMember.UserName.ToLower() == CIUser.UserName)
                                                                                .FirstOrDefault();

                            app.AssignedMembers.Remove(membership);
                            context.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(new { Msg = Common.Constants.APPLICATION_JSON_RESULT_ERROR });
            }


            return Json(new { Msg = Common.Constants.APPLICATION_JSON_RESULT_SUCCESS });
        }