protected void Page_Load(object sender, EventArgs e)
        {
            if (IsEditing())
            {
                ReportEditing();
                return;
            }
            if (NeedsConfig())
            {
                ReportNeedsConfiguration();
                return;
            }

            if ((!ParentWebPart.AllowAnonymousLaunch) && (!Request.IsAuthenticated))
            {
                throw new HttpException(403, "You must be signed in to continue.");
            }

            var actingUserName = Request.IsAuthenticated ?
                                 IdentityHelpers.GetUsedEmail(Page.User as IClaimsPrincipal) :
                                 "(anonymous)";

            SessionManager.SaveIntegrationSession(Session,
                                                  ParentWebPart.EndpointUri, ParentWebPart.ApiKey,
                                                  string.Empty, actingUserName);

            try {
                var client = new LabOnDemandApiClient(ParentWebPart.EndpointUri, ParentWebPart.ApiKey);

                var labProfileIds = ParentWebPart.LabProfileIds.Split(',');

                var labTable = new Table {
                    CssClass = "labTable"
                };
                AddHeader(labTable);
                var count = 0;
                foreach (var labProfileIdString in labProfileIds)
                {
                    AddComment(labProfileIdString);
                    int labProfileId;
                    if (!int.TryParse(labProfileIdString, out labProfileId))
                    {
                        AddComment("(skipped)");
                        continue;
                    }
                    count++;
                    var alternate  = (count % 2) == 0;
                    var labProfile = client.LabProfile(labProfileId);
                    labTable.Rows.Add(GetFirstRow(labProfile, alternate));
                    labTable.Rows.Add(GetSecondRow(labProfile, alternate));
                }
                Controls.Add(labTable);

                SessionManager.SessionAllowsAnonymous(Session, ParentWebPart.AllowAnonymousLaunch);
            }
            catch (Exception ex) {
                AddComment(ex.ToString());
                AddLiteral("An error occurred retrieving the requested lab information.");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsEditing()) {
                ReportEditing();
                return;
            }
            if (NeedsConfig()) {
                ReportNeedsConfiguration();
                return;
            }

            if ((!ParentWebPart.AllowAnonymousLaunch) && (!Request.IsAuthenticated)) {
                throw new HttpException(403, "You must be signed in to continue.");
            }

            var actingUserName = Request.IsAuthenticated ?
                IdentityHelpers.GetUsedEmail(Page.User as IClaimsPrincipal) :
                "(anonymous)";
            SessionManager.SaveIntegrationSession(Session,
                ParentWebPart.EndpointUri, ParentWebPart.ApiKey,
                string.Empty, actingUserName);

            try {
                var client = new LabOnDemandApiClient(ParentWebPart.EndpointUri, ParentWebPart.ApiKey);

                var labProfileIds = ParentWebPart.LabProfileIds.Split(',');

                var labTable = new Table {
                    CssClass = "labTable"
                };
                AddHeader(labTable);
                var count = 0;
                foreach (var labProfileIdString in labProfileIds) {
                    AddComment(labProfileIdString);
                    int labProfileId;
                    if (!int.TryParse(labProfileIdString, out labProfileId)) {
                        AddComment("(skipped)");
                        continue;
                    }
                    count++;
                    var alternate = (count % 2) == 0;
                    var labProfile = client.LabProfile(labProfileId);
                    labTable.Rows.Add(GetFirstRow(labProfile, alternate));
                    labTable.Rows.Add(GetSecondRow(labProfile, alternate));
                }
                Controls.Add(labTable);

                SessionManager.SessionAllowsAnonymous(Session, ParentWebPart.AllowAnonymousLaunch);
            }
            catch (Exception ex) {
                AddComment(ex.ToString());
                AddLiteral("An error occurred retrieving the requested lab information.");
            }
        }
        public IActionResult RegisterLabAction(string labAction, int labProfileId, long labInstanceId, string globalLabInstanceId,
                                               string userId, string firstName, string lastName, string email)
        {
            var apiUrl = _Settings.APIURL;
            var apiKey = _Settings.APIKey;
            var client = new LabOnDemandApiClient(apiUrl, apiKey);

            // check whitelist!
            if (!_Settings.IPWhitelist.Contains(Request.HttpContext.Connection.RemoteIpAddress.ToString()))
            {
                return(NotFound());
            }

            // verify that LOD knows about this launch!
            var details = client.Details(labInstanceId);

            if (!(details.UserId == userId ||
                  (details.UserFirstName == firstName && details.UserLastName == lastName)) ||
                details.LabProfileId != labProfileId)
            {
                return(NotFound());
            }

            // if we get here, everything checks out, so add our record!
            var launch = new LabAction
            {
                FirstName            = details.UserFirstName,
                LastName             = details.UserLastName,
                State                = details.State,
                Status               = details.Status.ToString(),
                LabInstanceId        = labInstanceId,
                LabProfileId         = details.LabProfileId,
                LabProfileName       = details.LabProfileName,
                LabActionDescription = labAction
            };

            _context.Add(launch);
            _context.SaveChanges();

            return(Json(new { success = true }));
        }
        public IActionResult CancelLab(long labRecordId)
        {
            var launchRecord = _context.LabLaunch.FirstOrDefault(rec => rec.Id == labRecordId);

            if (launchRecord == null)
            {
                return(NotFound());
            }

            var apiUrl = _Settings.APIURL;
            var apiKey = _Settings.APIKey;
            var client = new LabOnDemandApiClient(apiUrl, apiKey);

            var labInstance = client.Details(launchRecord.LabInstanceId);

            if (labInstance.State != "Running")
            {
                return(BadRequest());
            }

            var response = client.Cancel(launchRecord.LabInstanceId, "Canceled from remote test site");

            if (response.Result == CancelResult.Success)
            {
                var launch = new LabAction
                {
                    FirstName            = labInstance.UserFirstName,
                    LastName             = labInstance.UserLastName,
                    State                = labInstance.State,
                    Status               = labInstance.Status.ToString(),
                    LabInstanceId        = labInstance.Id,
                    LabProfileId         = labInstance.LabProfileId,
                    LabProfileName       = labInstance.LabProfileName,
                    LabActionDescription = "Lab canceled from Demo Site"
                };
                _context.Add(launch);
                _context.SaveChanges();
            }

            return(RedirectToAction(nameof(Index)));
        }
        /// <summary>
        /// Used to launch a lab in LOD. The API is used here to call Launch, which returns a URL that will connect the
        /// user to the lab instance. It is possible to automatically open the window for the user, but be weary of popup blockers
        /// because any window open call on the browser without the direct action of a user (clicking a link) will be blocked by popup
        /// blockers
        /// </summary>
        /// <param name="model">Launches a lab in LOD</param>
        /// <returns>Returns a model contianing the link to the lab instance</returns>
        public IActionResult Launch(LaunchModel model)
        {
            if (!ModelState.IsValid)
            {
                var modelToRebind = model;
                ModelState.Clear();
                return(View("Launch", modelToRebind));
            }

            var apiUrl   = _Settings.APIURL;
            var apiKey   = _Settings.APIKey;
            var client   = new LabOnDemandApiClient(apiUrl, apiKey);
            var response = client.Launch(LAB_PROFILE_TO_LAUNCH, $"{model.FirstName}{model.LastName}", model.FirstName, model.LastName, model.Email);

            model.LabLaunchURL = response.Url;
            if (string.IsNullOrEmpty(model.LabLaunchURL))
            {
                return(View(nameof(StartLaunch), model));
            }
            return(View("LaunchPad", model));
        }