Ejemplo n.º 1
0
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here

            ClaimsPrincipal claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;

            //TODO: look-up the roles from the DB!
            string userId = userIdentity.Claims.Single(x => x.Type == ClaimTypes.NameIdentifier).Value;

            ApplicationDbContext context = new ApplicationDbContext();
            Identity identity = context.Identities.Single(x => x.NameIdentifier == userId);

            userIdentity.AddClaim(new Claim(SpecialClaimTypes.UserId, identity.IdentityId.ToString(), ClaimValueTypes.Integer));

            if (identity.SubscriptionIdentityRoles.Any())
            {

                //get first found subscription
                //TODO: update the databasee to be in line with the entity model code first
                foreach (int subscriptionId in identity.SubscriptionIdentityRoles.Select(x=>x.SubscriptionId).Distinct())
                {
                    userIdentity.AddClaim(new Claim(SpecialClaimTypes.Subscription, subscriptionId.ToString()));
                }
            }
            
            return userIdentity;
        }
Ejemplo n.º 2
0
 private void AssigUserSubscriptionRoles()
 {
     using (var context = new ApplicationDbContext())
     {
         var roles = context.SubscriptionIdentityRoles.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId && x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).Select(y => y.Role).ToList();
         var email = context.Identities.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId).Select(x => x.Email).First();
         Session[String.Format("Roles{0}", email)] = roles;
     }
 }
Ejemplo n.º 3
0
 // GET: Training
 public ActionResult Index()
 {
     using (var context = new ApplicationDbContext())
     {
         var email = context.Identities.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId).Select(x => x.Email).First();
         var roles = Session[String.Format("Roles{0}", email)];
         if (roles != null)
         {
             ViewBag.IsOwnerOrTrainer = ((List<string>)roles).Contains(RoleTypes.Owner) || ((List<string>)roles).Contains(RoleTypes.Trainer);
         }
     }
     return View();
 }
Ejemplo n.º 4
0
        public AzureTestController(ILogger logger, AzureFacadeFactory azureFacadeFactory)
        {
            _logger = logger;

            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Subscription subscription = context.Subscriptions
                    .Single(x => x.SubscriptionId == 1);

                _vmManagement = azureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                    subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                    subscription.BlobStorageKey);
            }
        }
Ejemplo n.º 5
0
        public void End(EndSessionRequest request)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                string version = request.Version.ToString();
                //Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);
                Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);

                //check if the request is no longer valid
                if (session.Version != request.Version.ToString())
                {
                    _logger.InfoFormat("EndSessionRequest for Sessionid: {0} was ignored because Removed: {1} and Version: {2}",
                        request.SessionId, session.Removed, request.Version);
                    return;
                }

                _logger.InfoFormat("Deleting VMs for SessionId: {0} ({1} - {2})",
                        session.SessionId, session.StartDate, session.EndDate);

                Subscription subscription = context.Subscriptions
                    .Single(x => x.SubscriptionId == session.SubscriptionId);

                IVMManagement vmManagement = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                    subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                    subscription.BlobStorageKey);

                //TODO: need to keep service name in the session
                string vmNameBase = "tn" + session.SessionId + "vm";
                vmManagement.DeleteService(vmNameBase);

                foreach (VirtualMachine vm in session.VirtualMachines.Where(x => !x.Deleted))
                {
                    vm.Deleted = true;
                }

                context.SaveChanges();

                _logger.InfoFormat("Deleted VMs for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);
            }
        }
Ejemplo n.º 6
0
        public ActionResult Index(SubscriptionCreateModel model)
        {
            Subscription subscription = new Subscription
            {
                BlobStorageKey = model.BlobStorageKey,
                BlobStorageName = model.BlobStorageName,
                CertificateKey = model.CertificateKey,
                AzureSubscriptionId = model.AzureSubscriptionId
            };

            BinaryReader r = new BinaryReader(Request.Files[0].InputStream);
            subscription.Certificate = r.ReadBytes(Request.Files[0].ContentLength);

            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                context.Subscriptions.Add(subscription);
                context.SaveChanges();
            }

            return View();
        }
Ejemplo n.º 7
0
        public ActionResult Index()
        {
            ViewBag.IsSignedUser = false;
            ViewBag.IsMember = false;
            if (HttpContext.User.Identity.IsAuthenticated)
            {
                AssigUserSubscriptionRoles();

                using (var context = new ApplicationDbContext())
                {
                    var email = context.Identities.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId).Select(x => x.Email).First();
                    var roles = Session[String.Format("Roles{0}", email)];
                    if (roles != null)
                    {
                        ViewBag.IsSignedUser = true;
                        ViewBag.IsMember = ((List<string>)roles).Contains(RoleTypes.Member);
                    }
                }
            }
            return View();
        }
Ejemplo n.º 8
0
        public void AssignCertificate(int subscriptionId, int identityId)
        {
            //create subscription if doesn't exist, otherwise update with new certificate
            CertificateSet certificateSet = CreateCertificate();

            //save the cer and pfx to local folder for debugging (si it me, or does that sound like a bad idea?)
            SaveCertificatesLocally(subscriptionId.ToString(), certificateSet);

            //TODO: finish implementation - send email

            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Subscription subscription = context.Subscriptions.Single(x => x.SubscriptionId == subscriptionId);
                subscription.CertificateKey = certificateSet.Password;
                subscription.Certificate = certificateSet.PfxRawData;
                context.SaveChanges();

                Identity identity = context.Identities.Single(x => x.IdentityId == identityId);

                Email.BuildAssignCertificateEmail(identity, subscription, certificateSet.CerRawData).Send();
            }
        }
Ejemplo n.º 9
0
        public bool AddUserSubscriptionRole(string role, string identityId)
        {
            var success = false;
            try
            {
                if (string.IsNullOrWhiteSpace(role) || string.IsNullOrWhiteSpace(identityId))
                    return false;

                if (role == RoleTypes.Trainer || role == RoleTypes.Owner)
                {
                    using (var context = new ApplicationDbContext())
                    {
                        var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();
                        var identity = context.Identities.Where(x => x.IdentityId.ToString() == identityId).FirstOrDefault();

                        if (subscription != null && identity != null && !context.SubscriptionIdentityRoles.Any(x => x.Role == role &&
                                x.IdentityId == identity.IdentityId && x.SubscriptionId == subscription.SubscriptionId))
                        {
                            context.SubscriptionIdentityRoles.Add(new SubscriptionIdentityRole()
                            {
                                SubscriptionId = subscription.SubscriptionId,
                                IdentityId = identity.IdentityId,
                                Role = role
                            });

                            context.SaveChanges();
                            success = true;
                        }
                    }
                }
                return success;
            }
            catch (Exception)
            {
                return false;
            }
        }
Ejemplo n.º 10
0
		public async Task<string> ReadyForCapture(string templateVmKey)
		{
			_logger.Info("Entering AzureManagement.ReadyForCapture");

			string result = "OK";

			try
			{
				using (ApplicationDbContext repository = new ApplicationDbContext())
				{
					Guid key = new Guid(templateVmKey);
					TemplateVM templateVM = repository.TemplateVMs.Single(x => x.Key == key);
					templateVM.State = (int)TemplateVMStatusEnum.ReadyToCapture;
					templateVM.StateChangedTimestamp = DateTimeOffset.Now;
					repository.SaveChanges();

					//schedule the check and capture in 5 minutes
					await Messaging.SendAsync(new VMReadyForCaptureRequest 
						{ TemplateVMId = templateVM.TemplateVMId },
						DateTime.UtcNow.AddMinutes(5));
				}
			}
			catch (Exception ex)
			{
				_logger.Fatal("Exception when marking VM for capture.", ex);
				result = "Error";
			}

			_logger.Info("Exiting AzureManagement.ReadyForCapture");

			return result;
		}
Ejemplo n.º 11
0
 public PoRepository()
 {
     _context = new ApplicationDbContext();
 }
Ejemplo n.º 12
0
        private void SaveInvites(IList<string> emailList)
        {
            using (var context = new ApplicationDbContext())
            {
                var identity = context.Identities.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId).FirstOrDefault();
                var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();

                if (identity != null && subscription != null)
                {
                    foreach (var email in emailList)
                    {
                        if (!context.Invitations.Where(x => x.Identity.IdentityId == identity.IdentityId &&
                             x.Subscription.SubscriptionId == subscription.SubscriptionId && x.Email == email).Any())
                        {
                            context.Invitations.Add(new Invitation()
                            {
                                Email = email,
                                Identity = identity,
                                Subscription = subscription,
                                IdentityId = identity.IdentityId,
                                SubscriptionId = subscription.SubscriptionId,
                                Processed = false
                            });
                            context.SaveChanges();
                        }
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public IEnumerable<VirtualMachineImageModel> AvailableTemplateImages()
        {
            Subscription subscription;
            List<string> preferredVmFamilies;
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                subscription = context.Subscriptions.Single(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId);

                preferredVmFamilies = context.RecommendedVMImages.Select(x => x.ImageFamily).ToList();
            }

            IVMManagement management = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                subscription.BlobStorageKey);

            List<VirtualMachineImageModel> vmImageList = management.GetAvailableTemplateImages(VmImageSourceEnum.All, preferredVmFamilies);

            // Filter the image list:
            // User images must check if are for the current subscription
            // also enrich the user images with a friendly description
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                int subscriptionId = UnitOfWork.ActiveSubscriptionId;
                List<TemplateVM> subscriptionTemplates = context.TemplateVMs
                    .Where(x=>x.SubscriptionId == subscriptionId).ToList();

                List<string> subscriptionImageNames = subscriptionTemplates.Select(x=>x.ImageName).ToList();

                vmImageList = vmImageList.Where(x => !x.IsUserImage || subscriptionImageNames.Contains(x.Name))
                    .ToList();

                foreach(VirtualMachineImageModel image in vmImageList.Where(x=>x.IsUserImage))
                {
                    image.Description = subscriptionTemplates.Single(x => x.ImageName == image.Name).Description;
                }
            }

            return vmImageList;
        }
Ejemplo n.º 14
0
        public IEnumerable<object> AvailableSubscriptions()
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                int activeSubscriptionId = UnitOfWork.CurrentIdentity.ActiveSubscriptionId;

                var availableSubscriptions = context.Subscriptions.Where(x => x.SubscriptionIdentityRoles.Any(y => y.SubscriptionId == activeSubscriptionId)).Distinct().ToList()
                    .Select(x=> new
                    {
                        SubscriptionId = x.SubscriptionId,
                        SubscriptionName = x.Name,
                        Active = x.SubscriptionId == UnitOfWork.ActiveSubscriptionId
                    });

                return availableSubscriptions;
            }
        }
Ejemplo n.º 15
0
        public void Start(StartSessionRequest request)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);
                //Session session = context.Sessions.Single(x => x.Version == version);

                //check if the session is canceled or the request is no longer valid
                if (session.Removed ||
                    (session.Version != request.Version.ToString()))
                {
                    _logger.InfoFormat("StartSessionRequest for Sessionid: {0} was ignored because Removed: {1} and Version: {2}",
                        request.SessionId, session.Removed, request.Version);
                    return;
                }

                _logger.InfoFormat("Spawning VMs for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);

                Subscription subscription = context.Subscriptions
                    .Single(x => x.SubscriptionId == session.SubscriptionId);

                IVMManagement vmManagement = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                    subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                    subscription.BlobStorageKey);

                //TODO: remove the hardcoding at some point in time
                string NorthEurope = "North Europe";

                VMConfigModel vmConfig = new VMConfigModel(session.Lab.ImageName, NorthEurope)
                {
                    VmSize = (VmSizeEnum)Enum.Parse(typeof(VmSizeEnum), session.VmSize)
                };

                var sessionUsers = session.SessionUsers.ToList();

                var vmUsers = new List<VMUserModel>();
                sessionUsers.ForEach(x =>
                {
                    //TODO: wrong logic.. not all sessions are based on templates
                    var templateVM = context.TemplateVMs.Where(y => y.IdentityId == x.IdentityId && y.SubscriptionId == subscription.SubscriptionId).FirstOrDefault();
                    if (templateVM != null)
                    {
                        vmUsers.Add(new VMUserModel
                        {
                            IdentityId = x.IdentityId,
                            Username = templateVM.VMAdminUser,
                            Password = templateVM.VMAdminPass
                        });
                    }
                });

                //figure out a URL friendly name for the vm names
                string vmNameBase = "tn" + session.SessionId + "vm";

                var assignedVMs = vmManagement.GenerateVMsForUsers(vmNameBase, vmConfig, vmUsers);

                foreach (var assignedVM in assignedVMs)
                {
                    VirtualMachine virtualMachine = new VirtualMachine
                    {
                        IdentityId = assignedVM.UserId,
                        VmAdminPass = assignedVM.Password,
                        VmAdminUser = assignedVM.UserName,
                        VmName = assignedVM.VmName,
                        VmRdpPort = assignedVM.VmRdpPort
                    };

                    session.VirtualMachines.Add(virtualMachine);
                    context.SaveChanges();
                }

                _logger.InfoFormat("Spawned VMs for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);

                _logger.InfoFormat("Sending emails for SessionId: {0} ({1} - {2})",
                    session.SessionId, session.StartDate, session.EndDate);
                //well.. this is a hack
                //TODO: send the correct service name, that should be returned from the Azure Facade
                Email.BuildSessionEmails(session, vmNameBase).Send();
            }
        }
Ejemplo n.º 16
0
        public bool RemoveUserFromSubscription(string identityId)
        {
            var success = false;
            try
            {
                if (string.IsNullOrWhiteSpace(identityId))
                    return false;

                using (var context = new ApplicationDbContext())
                {
                    var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();
                    var identity = context.Identities.Where(x => x.IdentityId.ToString() == identityId).FirstOrDefault();

                    if (subscription == null || identity == null)
                        return false;

                    var subscriptionRoles = context.SubscriptionIdentityRoles.Where(x => x.IdentityId == identity.IdentityId &&
                        x.SubscriptionId == subscription.SubscriptionId);

                    foreach (var subscriptionRole in subscriptionRoles.ToList())
                    {
                        context.SubscriptionIdentityRoles.Remove(context.SubscriptionIdentityRoles.Where(x =>
                            x.SubscriptionIdentityRoleId == subscriptionRole.SubscriptionIdentityRoleId).FirstOrDefault());
                        context.SaveChanges();
                        success = true;
                    }
                }
                return success;
            }
            catch (Exception)
            {
                return false;
            }
        }
Ejemplo n.º 17
0
 public List<string> GetLoggedInUserSubscriptionRoles()
 {
     var loggedInUserRoles = new List<string>();
     using (var context = new ApplicationDbContext())
     {
         var identity = context.Identities.Where(x => x.IdentityId == UnitOfWork.CurrentIdentity.IdentityId).FirstOrDefault();
         var subscription = context.Subscriptions.Where(x => x.SubscriptionId == UnitOfWork.ActiveSubscriptionId).FirstOrDefault();
         if (identity != null && subscription != null)
         {
             var roles = context.SubscriptionIdentityRoles.Where(x =>
                 x.IdentityId == identity.IdentityId && x.SubscriptionId == subscription.SubscriptionId);
             if (roles.Any())
                 roles.ToList().ForEach(x => loggedInUserRoles.Add(x.Role));
         }
     }
     return loggedInUserRoles;
 }
Ejemplo n.º 18
0
 private void CreateSubscriptionIdentityMap(Subscription subscription, int identityId)
 {
     using (ApplicationDbContext context = new ApplicationDbContext())
     {
         CreateSubscriptionIdentityMap(subscription, context, RoleTypes.Member);
         CreateSubscriptionIdentityMap(subscription, context, RoleTypes.Owner);
         CreateSubscriptionIdentityMap(subscription, context, RoleTypes.Trainer);
         context.SaveChanges();
     }
 }
Ejemplo n.º 19
0
 private int GetIdentityIdByUserId(string userId)
 {
     try
     {
         var identityId = 0;
         using (var context = new ApplicationDbContext())
         {
             identityId = context.Identities.Single(x => x.NameIdentifier == userId).IdentityId;
         }
         return identityId;
     }
     catch(Exception)
     {
         return 0;
     }
 }
Ejemplo n.º 20
0
        private bool CheckAndHandleUserInvites(int identityId, string email)
        {
            try
            {
                using (var context = new ApplicationDbContext())
                {
                    var invitations = context.Invitations.Where(x => x.Email == email && x.Processed == false);
                    var identity = context.Identities.Where(x => x.IdentityId == identityId).FirstOrDefault();

                    if (!invitations.Any() || identity == null)
                        return false;

                    foreach (var invitation in invitations.ToList())
                    {
                        var subscription = context.Subscriptions.Where(x => x.SubscriptionId == invitation.SubscriptionId).FirstOrDefault();
                        if (subscription != null)
                        {
                            if (!context.SubscriptionIdentityRoles.Any(x => x.IdentityId == identityId &&
                                x.Subscription.SubscriptionId == invitation.SubscriptionId && x.Role == RoleTypes.Member))
                            {
                                context.SubscriptionIdentityRoles.Add(new SubscriptionIdentityRole()
                                {
                                    Subscription = subscription,
                                    IdentityId = identity.IdentityId,
                                    Role = RoleTypes.Member
                                });
                            }

                            invitation.Processed = true;
                            context.Entry(invitation).State = EntityState.Modified;
                            context.SaveChanges();
                        }
                    }
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
Ejemplo n.º 21
0
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            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");
                }

                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        ApplicationDbContext context = new ApplicationDbContext();
                        Core.Repository.Identity identity = new Identity
                        {
                            IdentityProvider = "",
                            NameIdentifier = user.Id,
                            Email = model.Email,
                            DisplayName = "",
                            FirstName = model.FirstName,
                            LastName = model.LastName
                        };
                        context.Identities.Add(identity);
                        context.SaveChanges();

                        Email.BuildSignUpEmail(identity).Send();

                        CheckAndHandleUserInvites(identity.IdentityId, model.Email);

                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
Ejemplo n.º 22
0
        public void Start(StartSessionRequest request)
        {
            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                Session session = context.Sessions.Single(x => x.SessionId == request.SessionId);
                //Session session = context.Sessions.Single(x => x.Version == version);

                Identity trainer = session.TrainerId != 0 ?
                    context.Identities.Where(x => x.IdentityId == session.TrainerId).FirstOrDefault() :
                    context.Identities.Where(x => x.IdentityId ==
                        (context.SubscriptionIdentityRoles.Where(y => y.SubscriptionId == session.SubscriptionId && y.Role == "Owner").FirstOrDefault()).IdentityId).FirstOrDefault();

                //figure out a URL friendly name for the vm names
                string vmNameBase = "tn" + session.SessionId + "vm";

                try
                {
                    //check if the session is canceled or the request is no longer valid
                    if (session.Removed ||
                        (session.Version != request.Version.ToString()))
                    {
                        _logger.InfoFormat("StartSessionRequest for Sessionid: {0} was ignored because Removed: {1} and Version: {2}",
                            request.SessionId, session.Removed, request.Version);
                        return;
                    }

                    _logger.InfoFormat("Spawning VMs for SessionId: {0} ({1} - {2})", session.SessionId, session.StartDate, session.EndDate);

                    Subscription subscription = context.Subscriptions.Single(x => x.SubscriptionId == session.SubscriptionId);

                    IVMManagement vmManagement = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                        subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                        subscription.BlobStorageKey);

                    //TODO: remove the hardcoding at some point in time
                    string NorthEurope = "North Europe";

                    VMConfigModel vmConfig = new VMConfigModel(session.Lab.ImageName, NorthEurope)
                    {
                        VmSize = (VmSizeEnum)Enum.Parse(typeof(VmSizeEnum), session.VmSize)
                    };

                    var sessionUsers = session.SessionUsers.ToList();
                    var vmUsers = new List<VMUserModel>();
                    RandomProvider randomProvider = new RandomProvider();

                    sessionUsers.ForEach(x =>
                    {
                        vmUsers.Add(new VMUserModel
                        {
                            IdentityId = x.IdentityId,
                            Username = x.Identity != null ? string.Format("{0}.{1}", x.Identity.FirstName, x.Identity.LastName) : string.Empty,
                            Password = randomProvider.SecurePassword(8)
                        });
                    });

                    Email.BuildSessionStartVmsEmails(trainer.FirstName, trainer.Email, session, vmNameBase, vmUsers.Count).Send();

                    var assignedVMs = vmManagement.GenerateVMsForUsers(vmNameBase, vmConfig, vmUsers);

                    foreach (var assignedVM in assignedVMs)
                    {
                        VirtualMachine virtualMachine = new VirtualMachine
                        {
                            IdentityId = assignedVM.UserId,
                            VmAdminPass = assignedVM.Password,
                            VmAdminUser = assignedVM.UserName,
                            VmName = assignedVM.VmName,
                            VmRdpPort = assignedVM.VmRdpPort
                        };

                        session.VirtualMachines.Add(virtualMachine);
                        context.SaveChanges();
                    }

                    _logger.InfoFormat("Spawned VMs for SessionId: {0} ({1} - {2})", session.SessionId, session.StartDate, session.EndDate);

                    _logger.InfoFormat("Sending emails for SessionId: {0} ({1} - {2})", session.SessionId, session.StartDate, session.EndDate);
                    //well.. this is a hack
                    //TODO: send the correct service name, that should be returned from the Azure Facade

                    Email.BuildSessionEndVmsEmails(trainer.FirstName, trainer.Email, session.SessionName, vmNameBase, vmUsers.Count, assignedVMs.Count).Send();
                    Email.BuildSessionEmails(session, vmNameBase).Send();
                }
                catch(Exception ex)
                {
                    Email.BuildProblemStartingVmsEmails(trainer.FirstName, trainer.Email, session.SessionName, vmNameBase, ex.InnerException != null ? ex.InnerException.Message : "Error in starting the virtual machine(s).").Send();
                    throw ex;
                }
            }
        }
Ejemplo n.º 23
0
        private void CreateSubscriptionIdentityMap(Subscription subscription, ApplicationDbContext context, string role)
        {
            SubscriptionIdentityRole subscriptionIdentity = new SubscriptionIdentityRole
            {
                Subscription = subscription,
                IdentityId = UnitOfWork.CurrentIdentity.IdentityId,
                Role = role
            };

            context.SubscriptionIdentityRoles.Add(subscriptionIdentity);
        }
Ejemplo n.º 24
0
		public string BaseVmProvisionedWithExtensions(string templateVmKey)
		{
			_logger.Info("Entering AzureManagement.BaseVmProvisionedWithExtensions");

			string result = "OK";

			try
			{
				using (ApplicationDbContext repository = new ApplicationDbContext())
				{
					Guid key = new Guid(templateVmKey);
					TemplateVM templateVm = repository.TemplateVMs.Single(x => x.Key == key);

					Email.BuildTemplateVMReady(templateVm).Send();
				}
			}
			catch (Exception ex)
			{
				_logger.Fatal("Exception when marking VM provisioned.", ex);
				result = "Error";
			}

			_logger.Info("Exiting AzureManagement.BaseVmProvisionedWithExtensions");

			return result;
		}
Ejemplo n.º 25
-1
        public int CheckForAvailableResources(int subscriptionId, DateTimeOffset sessionStart, DateTimeOffset sessionEnd)
        {
            int availableCPUs;

            using (ApplicationDbContext context = new ApplicationDbContext())
            {
                //TODO: move warmUP and coolDown into the config
                TimeSpan warmUp = new TimeSpan(0, 20, 0);
                //there is an extra +5 as this is a safe assumption as how long will it take for azure to
                //delete the VMs
                TimeSpan coolDown = new TimeSpan(0, 30 + 5, 0);

                DateTimeOffset start = sessionStart.Subtract(warmUp);
                DateTimeOffset end = sessionEnd.Add(coolDown);

                var sameWindowSessions = context.Sessions.Where(x => x.SubscriptionId == subscriptionId &&
                    x.StartDate <= end && x.EndDate >= start && !x.Removed).ToList();

                //int projectedCPUs = sameWindowSessions.Sum(x => Sessions.CalculateSessionCPUs(x));
                int projectedCPUs = MaxOverlappingCPUs(sameWindowSessions);

                //now check how many VMs programmed are running at the moment
                List<VmSizeEnum> runningVMs = context.VirtualMachines
                    .Where(x => !x.Deleted && !x.Stopped && x.Session.SubscriptionId == subscriptionId)
                    .Select(x => x.Session.VmSize).ToList()
                    .Select(x => (VmSizeEnum)Enum.Parse(typeof(VmSizeEnum), x)).ToList();

                int currentPlannedCPUs = runningVMs.Sum(x => (int)x);

                Subscription subscription = context.Subscriptions
                        .Single(x => x.SubscriptionId == subscriptionId);

                IVMManagement management = AzureFacadeFactory.VMManagement(subscription.AzureSubscriptionId,
                    subscription.Certificate, subscription.CertificateKey, subscription.BlobStorageName,
                    subscription.BlobStorageKey);
                SubscriptionDetails subscriptionDetails = management.GetSubscriptionDetails();
                int unknownCPUs = subscriptionDetails.MaxCoreCount - subscriptionDetails.AvailableCoreCount -
                    currentPlannedCPUs;

                unknownCPUs = Math.Max(unknownCPUs, 0);

                availableCPUs = subscriptionDetails.MaxCoreCount - unknownCPUs - projectedCPUs;
            }

            return availableCPUs;
        }