Exemple #1
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            //Use Session payload vs. URL params to validate
            // if credentials pass / Get Cookie
            //HttpCookie cookie = (HttpCookie) Request.Cookies.Get("viData");
            // if credentials pass / Get Cookie
            int tz = 0;
            if(Session["userTZ"] != null)
                tz = Convert.ToInt32(Session["userTZ"]);
            String returnURL = (string)Session["returnURL"];
            if ((returnURL != null) && (returnURL.Length > 0))
            {
                lnkBackSB.NavigateUrl = returnURL;
                lnkBackSB.Visible = true;
            }
            else{
                lnkBackSB.Visible = false;
            }

            string payload = (string) Session["payload"];
            XmlQueryDoc xDoc = new XmlQueryDoc(payload);
            String viidStr= xDoc.Query("payload/appId");
            String viname = xDoc.Query("payload/application");
            String revision = xDoc.Query("payload/revision");
            String appUrl = xDoc.Query("payload/appUrl");
            String widthStr = xDoc.Query("payload/width");
            String heightStr= xDoc.Query("payload/height");
            String startStr = xDoc.Query("payload/startTime");
            String durationStr= xDoc.Query("payload/duration");
            int width = Convert.ToInt32(widthStr);
            int height = Convert.ToInt32(heightStr);
            long duration = -1;
            if((durationStr != null) && (durationStr.Length > 0))
                duration = Convert.ToInt64(durationStr);
            if ((appUrl != null) && (appUrl.Length > 0))
            {
                thePanel.serverURL = appUrl;
            }
            else
            {
                thePanel.serverURL = @"http://" + this.ApplicationInstance.Server.MachineName + @":81";
            }

            thePanel.viName = viname;
            thePanel.version = revision;
            thePanel.width = width;
            thePanel.height= height;
            if(duration > 0){
                RegisterStartupScript("timer", LabUtils.TimerScript(startStr, duration, tz,
                    DateUtil.ParseCulture(Request.Headers["Accept-Language"]),returnURL,1000));
            }

            /* Use Session payload vs. URL params to validate
            }
            else
            {
                Response.Redirect("AccessDenied.aspx", true);
            }
            */
        }
 public static SystemSupport Parse(XmlQueryDoc xdoc)
 {
     SystemSupport ss = new SystemSupport();
     try
     {
         ss.agentGuid = xdoc.Query("/systemSupport/agentGuid");
         ss.bugEmail = xdoc.Query("/systemSupport/bugEmail");
         ss.contactEmail = xdoc.Query("/systemSupport/contactEmail");
         ss.infoUrl = xdoc.Query("/systemSupport/infoUrl");
         ss.description = xdoc.Query("/systemSupport/description");
         ss.location = xdoc.Query("/systemSupport/location");
         return ss;
     }
     catch (Exception e)
     {
         ;
     }
     return null;
 }
Exemple #3
0
        public override LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {

            long experimentID = -1;
            LabTask task = null;

            //Parse experiment payload 	
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);

            string experimentStr = expDoc.Query("ExecuteExperimentPayload/experimentID");
            if ((experimentStr != null) && (experimentStr.Length > 0))
            {
                experimentID = Convert.ToInt64(experimentStr);
            }
            string sbStr = expDoc.Query("ExecuteExperimentPayload/sbGuid");



            // Check to see if an experiment with this ID is already running
            LabDB dbManager = new LabDB();
            LabTask.eStatus status = dbManager.ExperimentStatus(experimentID, sbStr);
            if (status == LabTask.eStatus.NotFound)
            {
                // Check for an existing experiment using the same resources, if found Close it

                //Create the new Task
                if(appInfo.rev.Contains("8.2")){
                   task = iLabs.LabView.LV82.LabViewTask.CreateLabTask(appInfo,expCoupon,expTicket);
                }
                else{
                     task = iLabs.LabView.LV86.LabViewTask.CreateLabTask(appInfo,expCoupon,expTicket);
                }
            }

            else
            {
                task =  TaskProcessor.Instance.GetTask(experimentID);

            }
            return task;
        }
        public int LoadLabClient(XmlQueryDoc xdoc, ref StringBuilder message)
        {
            string guid = xdoc.Query("/clientDescriptor/clientGuid");
            string type = xdoc.Query("/clientDescriptor/clientType");
            string name = xdoc.Query("/clientDescriptor/clientName");
            string version = xdoc.Query("/clientDescriptor/version");
            string shortDescription = xdoc.Query("/clientDescriptor/clientShortDescription");
            string longDescription = xdoc.Query("/clientDescriptor/clientLongDescription");
            string contactEmail = HttpUtility.HtmlDecode(xdoc.Query("/clientDescriptor/contactEmail"));
            string contactFirstName = xdoc.Query("/clientDescriptor/contactFirstName");
            string contactLastName = xdoc.Query("/clientDescriptor/contactLastName");
            string loaderScript = xdoc.Query("/clientDescriptor/loaderScript");
            string documentationURL = xdoc.Query("/clientDescriptor/documentationUrl");
            string tmp = xdoc.Query("/clientDescriptor/needsScheduling");
            bool needsScheduling = Convert.ToBoolean(tmp);
            tmp = xdoc.Query("/clientDescriptor/needsESS");
            bool needsESS = Convert.ToBoolean(tmp);
            tmp = xdoc.Query("/clientDescriptor/isReentrant");
            bool isReentrant = Convert.ToBoolean(tmp);
            string notes = xdoc.Query("/clientDescriptor/notes");

            // Insert the Client, Qualifier is created internally
            int newClientId = AdministrativeAPI.AddLabClient(guid, name, version, shortDescription,
                longDescription, type, loaderScript, documentationURL,
                contactEmail, contactFirstName, contactLastName,notes, needsESS, needsScheduling, isReentrant);

            // parse the LabServer list
            XPathNodeIterator iter = xdoc.Select("/clientDescriptor/labServers/*");
            if (iter != null && iter.Count > 0)
            {
                int order = 0;
                while (iter.MoveNext())
                {
                    string lsGuid = iter.Current.GetAttribute("guid", ns);
                    int serverID = brokerDb.GetProcessAgentID(lsGuid);
                    if (serverID > 0)
                    {
                        AdministrativeAPI.LabServerClient_Insert(serverID, newClientId, order);
                        order++;
                    }
                }
            }

            // deal with resources
            iter = xdoc.Select("/clientDescriptor/clientInfos/*");
            if (iter != null && iter.Count > 0)
            {
                while (iter.MoveNext())
                {
                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo.infoURL = iter.Current.GetAttribute("infoUrl", ns);
                    clientInfo.infoURLName = iter.Current.GetAttribute("infoUrlName", ns);
                    clientInfo.description = iter.Current.GetAttribute("description", ns);
                    clientInfo.displayOrder = Int32.Parse(iter.Current.GetAttribute("displayOrder", ns));
                    AdministrativeAPI.InsertLabClientInfo(newClientId, clientInfo.infoURL, clientInfo.infoURLName,
                        clientInfo.description, clientInfo.displayOrder);
                }
            }

            message.Append(" Registered a new LabClient. ");
            message.AppendLine(" GUID: " + guid + " -> " + name);
            return newClientId;
        }
        public LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {
            // set defaults
            DateTime startTime = DateTime.UtcNow;
            long duration = -1L;
            long experimentID = 0;
            int status = -1;

            string statusViName = null;
            string statusTemplate = null;
            string templatePath = null;
            LabDB dbManager = new LabDB();
            string qualName = null;
            string fullName = null;  // set defaults
            string viName = null;

            //CHeck that a labVIEW interface revision is set
            //if (appInfo.rev == null || appInfo.rev.Length < 2)
            //{
            //    appInfo.rev = ConfigurationManager.AppSettings["LabViewVersion"];
            //}

            ////Parse experiment payload, only get what is needed
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);
            string essService = expDoc.Query("ExecuteExperimentPayload/essWebAddress");
            string startStr = expDoc.Query("ExecuteExperimentPayload/startExecution");
            string durationStr = expDoc.Query("ExecuteExperimentPayload/duration");
            string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
            string userName = expDoc.Query("ExecuteExperimentPayload/userName");
            string expIDstr = expDoc.Query("ExecuteExperimentPayload/experimentID");

            if ((startStr != null) && (startStr.Length > 0))
            {
                startTime = DateUtil.ParseUtc(startStr);
            }
            if ((durationStr != null) && (durationStr.Length > 0) && !(durationStr.CompareTo("-1") == 0))
            {
                duration = Convert.ToInt64(durationStr);
            }
            if ((expIDstr != null) && (expIDstr.Length > 0))
            {
                experimentID = Convert.ToInt64(expIDstr);
            }

            if (appInfo.extraInfo != null && appInfo.extraInfo.Length > 0)
            {
                // Note should have either statusVI or template pair
                // Add Option for VNCserver access
                try
                {
                    XmlQueryDoc viDoc = new XmlQueryDoc(appInfo.extraInfo);
                    statusViName = viDoc.Query("extra/status");
                    statusTemplate = viDoc.Query("extra/statusTemplate");
                    templatePath = viDoc.Query("extra/templatePath");
                }
                catch (Exception e)
                {
                    string err = e.Message;
                }
            }

            // log the experiment for debugging

            Logger.WriteLine("Experiment: " + experimentID + " Start: " + DateUtil.ToUtcString(startTime) + " \tduration: " + duration);
            long statusSpan = DateUtil.SecondsRemaining(startTime, duration);

            if (!IsLoaded(appInfo.application))
            {
                viName = LoadVI(appInfo.path, appInfo.application);
                if (false) // Check for controls first
                {
                    string[] names = new string[4];
                    object[] values = new object[4];
                    names[0] = "CouponId";
                    values[0] = expCoupon.couponId;
                    names[1] = "Passcode";
                    values[1] = expCoupon.passkey;
                    names[2] = "IssuerGuid";
                    values[2] = expCoupon.issuerGuid;
                    names[3] = "ExperimentId";
                    values[3] = experimentID;
                    SetControlValues(viName, names, values);
                }
                OpenFrontPanel(viName, true, LabViewTypes.eFPState.eVisible);
            }
            else
            {
                viName = LoadVI(appInfo.path, appInfo.application);
            }
            if (viName == null)
            {
                status = -1;
                string err = "Unable to Find: " + appInfo.path + @"\" + appInfo.application;
                Logger.WriteLine(err);
                throw new Exception(err);
            }
            // Get qualifiedName
            qualName = qualifiedName(viName);
            fullName = appInfo.path + @"\" + appInfo.application;

            status = GetVIStatus(viName);

            Logger.WriteLine("CreateLabTask - " + qualName + ": VIstatus: " + status);
            switch (status)
            {
                case -10:
                    throw new Exception("Error GetVIStatus: " + status);
                    break;
                case -1:
                    // VI not in memory
                    throw new Exception("Error GetVIStatus: " + status);

                    break;
                case 0: // eBad == 0
                    break;
                case 1: // eIdle == 1 vi in memory but not running
                    //LabViewTypes.eFPState fpState = GetFPStatus(viName);
                   //if (fpState != LabViewTypes.eFPState.eVisible)
                    //{
                        OpenFrontPanel(viName, true, LabViewTypes.eFPState.eVisible);
                    //}
                    ResetVI(viName);
                    break;
                case 2: // eRunTopLevel: this should be the LabVIEW application
                    break;
                case 3: // eRunning
                    //Unless the Experiment is reentrant it should be stopped and be reset.
                    if (!appInfo.reentrant)
                    {
                        int stopStatus = StopVI(viName);
                        if (stopStatus != 0)
                        {
                            AbortVI(viName);
                        }
                        ResetVI(viName);
                    }
                    break;
                default:
                    throw new Exception("Error GetVIStatus: unknown status: " + status);
                    break;
            }
            try
            {
                SetBounds(viName, 0, 0, appInfo.width, appInfo.height);
                Logger.WriteLine("SetBounds: " + appInfo.application);
            }
            catch (Exception sbe)
            {
                Logger.WriteLine("SetBounds exception: " + Utilities.DumpException(sbe));
            }
            SubmitAction("unlockvi", qualifiedName(viName));
            Logger.WriteLine("unlockvi Called: ");

            // Create the labTask & store in database;
            LabViewTask task = new LabViewTask();
            task.labAppID = appInfo.appID;
            task.experimentID = experimentID;
            task.groupName = groupName;
            task.startTime = startTime;
            if (duration > 0)
                task.endTime = startTime.AddTicks(duration * TimeSpan.TicksPerSecond);
            else
                task.endTime = DateTime.MinValue;
            task.Status = LabTask.eStatus.Scheduled;
            task.couponID = expTicket.couponId;
            task.storage = essService;
            task.data = task.constructTaskXml(appInfo.appID, fullName, appInfo.rev, statusViName, essService);
            long taskID = dbManager.InsertTaskLong(task);
            task.taskID = taskID;

            if ((statusTemplate != null) && (statusTemplate.Length > 0))
            {
                statusViName = CreateFromTemplate(templatePath, statusTemplate, task.taskID.ToString());
            }

            if (((essService != null) && (essService.Length > 0)))
            {
                // Create DataSourceManager to manage dataSocket connections
                DataSourceManager dsManager = new DataSourceManager();

                // set up an experiment storage handler
                ExperimentStorageProxy ess = new ExperimentStorageProxy();
                ess.OperationAuthHeaderValue = new OperationAuthHeader();
                ess.OperationAuthHeaderValue.coupon = expCoupon;
                ess.Url = essService;
                dsManager.essProxy = ess;
                dsManager.ExperimentID = experimentID;
                dsManager.AppKey = qualName;
                // Note these dataSources are written to by the application and sent to the ESS
                if ((appInfo.dataSources != null) && (appInfo.dataSources.Length > 0))
                {
                    string[] sockets = appInfo.dataSources.Split(',');
                    // Use the experimentID as the storage parameter
                    foreach (string s in sockets)
                    {
                        LVDataSocket reader = new LVDataSocket();
                        dsManager.AddDataSource(reader);
                        if (s.Contains("="))
                        {
                            string[] nv = s.Split('=');
                            reader.Type = nv[1];
                            reader.Connect(nv[0], LabDataSource.READ_AUTOUPDATE);

                        }
                        else
                        {
                            reader.Connect(s, LabDataSource.READ_AUTOUPDATE);
                        }
                    }
                }
                TaskProcessor.Instance.AddDataManager(task.taskID, dsManager);
            }

            TaskProcessor.Instance.Add(task);
            return task;
        }
 //public bool AuthenticateProcessAgent(Coupon agentCoupon, string agentGuid)
 //{
 //    // check that the agent record exists
 //    int id = GetProcessAgentID(agentGuid);
 //    if (id == 0)
 //        return false;
 //    // check that the agentCoupon parameter corresponds to the In coupon of the process agent
 //    if (AuthenticateCoupon(agentCoupon) && GetProcessAgentInfo(id).identIn.couponId == agentCoupon.couponId)
 //        return true;
 //    return false;
 //}
 /// <summary>
 /// Uses the reference ticketCollection to find a REDEEM_SESSION ticket and parse it
 /// </summary>
 /// <param name="sessionCoupon"></param>
 /// <param name="userId"></param>
 /// <param name="groupId"></param>
 /// <param name="clientId"></param>
 /// <returns>True if ticket found</returns>
 public bool RedeemSessionInfo(Coupon sessionCoupon, out int userId, out int groupId, out int clientId)
 {
     bool status = false;
     userId = -1;
     groupId = -1;
     clientId = -1;
     if (sessionCoupon != null)
     {
         if (sessionCoupon.issuerGuid.CompareTo(GetIssuerGuid()) == 0)
         {
             status = AuthenticateIssuedCoupon(sessionCoupon);
             if (status)
             {
                 XmlQueryDoc xDoc = null;
                 Ticket sessionTicket = RetrieveIssuedTicket(sessionCoupon, TicketTypes.REDEEM_SESSION, GetIssuerGuid());
                 if (sessionTicket != null)
                 {
                     if (!sessionTicket.isCancelled && !sessionTicket.IsExpired())
                     {
                         xDoc = new XmlQueryDoc(sessionTicket.payload);
                         string user = xDoc.Query("RedeemSessionPayload/userID");
                         string group = xDoc.Query("RedeemSessionPayload/groupID");
                         string client = xDoc.Query("RedeemSessionPayload/clientID");
                         if (user != null && user.Length > 0)
                             userId = Convert.ToInt32(user);
                         if (group != null && group.Length > 0)
                             groupId = Convert.ToInt32(group);
                         if (client != null && client.Length > 0)
                             clientId = Convert.ToInt32(client);
                     }
                 }
             }
         }
     }
     return status;
 }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            int groupID = 0;
            int authID = -1;
            Coupon opCoupon = null;
            string groupName = null;
            lblResponse.Visible = false;

            userTZ = Convert.ToInt32(Session["UserTZ"]);
            culture = DateUtil.ParseCulture(Request.Headers["Accept-Language"]);
            lc = null;
            if (!IsPostBack)
            {
                // retrieve parameters from URL
                couponId = Request.QueryString["coupon_id"];
                passkey = Request.QueryString["passkey"];
                issuerGuid = Request.QueryString["issuer_guid"];
                if (couponId != null && passkey != null && issuerGuid != null)
                {
                    opCoupon = new Coupon(issuerGuid, Int64.Parse(couponId), passkey);
                    Ticket authExperimentTicket = issuer.RetrieveTicket(opCoupon,
                        TicketTypes.CREATE_EXPERIMENT, ProcessAgentDB.ServiceGuid);
                    if (authExperimentTicket != null)
                    {
                        XmlQueryDoc authDoc = new XmlQueryDoc(authExperimentTicket.payload);
                        string auth = authDoc.Query("CreateExperimentPayload/authID");
                        if (auth != null && auth.Length > 0)
                        {
                            authID = Int32.Parse(auth);

                        }
                        string grpName = authDoc.Query("CreateExperimentPayload/groupName");
                        if (grpName != null && groupName.Length > 0)
                        {
                            Session["GroupName"] = grpName;
                            int grpID = AdministrativeAPI.GetGroupID(grpName);
                            if (grpID > 0)
                                Session["GroupID"] = groupID;
                        }
                        string userName = authDoc.Query("CreateExperimentPayload/userName");
                        if (userName != null && userName.Length > 0)
                        {
                            Session["UserName"] = userName;
                            int userID = AdministrativeAPI.GetUserID(userName,authID);
                            if (userID > 0)
                                Session["UserID"] = userID;
                        }
                        string clientGuid = authDoc.Query("CreateExperimentPayload/clientGuid");
                        if (clientGuid != null && clientGuid.Length > 0)
                        {
                            Session["ClientGuid"] = clientGuid;
                            int clientID = AdministrativeAPI.GetLabClientID(clientGuid);
                            if (clientID > 0)
                                Session["ClientID"] = clientID;
                        }
                    }
                }
                pReenter.Visible = false;
                btnReenter.Visible = false;
                auto = Request.QueryString["auto"];
                if (auto != null && auto.Length > 0)
                {
                    if (auto.ToLower().Contains("t"))
                    {
                        autoLaunch = true;
                    }
                }
            }
            if (Session["ClientID"] != null && Session["ClientID"].ToString().Length > 0)
            {
                lc = wrapper.GetLabClientsWrapper(new int[] { Convert.ToInt32(Session["ClientID"]) })[0];
            }
            if (Session["GroupID"] != null && Session["GroupID"].ToString().Length > 0)
            {
                groupID = Convert.ToInt32(Session["GroupID"]);
            }
            if (groupID > 0 && lc != null)
            {
                setEffectiveGroup(groupID, lc.clientID);
            }
            if (Session["GroupName"] != null && Session["GroupName"].ToString().Length > 0)
            {
                groupName = Session["GroupName"].ToString();
                lblGroupNameTitle.Text = groupName;
            }

            if (lc != null)
            {
                labServer = getLabServer(lc.clientID, effectiveGroupID);
                clientInfos = AdministrativeAPI.ListClientInfos(lc.clientID);
                if (lc.clientType == LabClient.INTERACTIVE_APPLET || lc.clientType == LabClient.INTERACTIVE_HTML_REDIRECT)
                {
                    if (lc.needsScheduling)
                    {
                        Ticket allowExperimentExecutionTicket = null;
                        if (opCoupon != null)
                        {
                            // First check for an Allow Execution Ticket
                            allowExperimentExecutionTicket = issuer.RetrieveTicket(
                                opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION);
                        }
                        if (allowExperimentExecutionTicket == null)
                        {
                            // Try for a reservation
                            int ussId = issuer.FindProcessAgentIdForClient(lc.clientID, ProcessAgentType.SCHEDULING_SERVER);
                            if (ussId > 0)
                            {
                                ProcessAgent uss = issuer.GetProcessAgent(ussId);
                                // check for current reservation

                                //create a collection & redeemTicket
                                string redeemPayload = TicketLoadFactory.Instance().createRedeemReservationPayload(DateTime.UtcNow,
                                    DateTime.UtcNow, Session["UserName"].ToString(), Convert.ToInt32(Session["UserID"]),
                                    groupName, lc.clientGuid);
                                if (opCoupon == null)
                                    opCoupon = issuer.CreateCoupon();

                                issuer.AddTicket(opCoupon, TicketTypes.REDEEM_RESERVATION, uss.agentGuid,
                                    ProcessAgentDB.ServiceGuid, 600, redeemPayload);

                                UserSchedulingProxy ussProxy = new UserSchedulingProxy();
                                OperationAuthHeader op = new OperationAuthHeader();
                                op.coupon = opCoupon;
                                ussProxy.Url = uss.webServiceUrl;
                                ussProxy.OperationAuthHeaderValue = op;
                                Reservation reservation = ussProxy.RedeemReservation(ProcessAgentDB.ServiceGuid,
                                    Session["UserName"].ToString(), labServer.agentGuid, lc.clientGuid);
                                if (reservation != null)
                                {
                                    // Find efective group
                                    setEffectiveGroup(groupID, lc.clientID);

                                    // create the allowExecution Ticket
                                    DateTime start = reservation.Start;
                                    long duration = reservation.Duration;
                                    string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload(
                                        start, duration, effectiveGroupName,lc.clientGuid);
                                    DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond);
                                    DateTime utcNow = DateTime.UtcNow;
                                    long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond;
                                    allowExperimentExecutionTicket = issuer.AddTicket(opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION,
                                            ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, ticketDuration, payload);
                                }
                            }
                        }
                        if (allowExperimentExecutionTicket != null)
                        {
                            XmlDocument payload = new XmlDocument();
                            payload.LoadXml(allowExperimentExecutionTicket.payload);
                            startExecution = DateUtil.ParseUtc(payload.GetElementsByTagName("startExecution")[0].InnerText);
                            duration = Int64.Parse(payload.GetElementsByTagName("duration")[0].InnerText);

                            Session["StartExecution"] = DateUtil.ToUtcString(startExecution);
                            Session["Duration"] = duration;

                            // Display reenter button if experiment is reentrant & a current experiment exists
                            if (lc.IsReentrant)
                            {

                                long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(Convert.ToInt32(Session["UserID"]),
                                    effectiveGroupID, labServer.agentId, lc.clientID);
                                if (ids.Length > 0)
                                {
                                    btnLaunchLab.Text = "Launch New Experiment";
                                   btnLaunchLab.OnClientClick = "javascript:return confirm('Are you sure you want to start a new experiment?\\n If you proceed the currently running experimnent will be closed.');";
                                    btnLaunchLab.Visible = true;
                                    pLaunch.Visible = true;
                                    pReenter.Visible = true;
                                    btnReenter.Visible = true;
                                    btnReenter.CommandArgument = ids[0].ToString();
                                }
                                else
                                {

                                    //pReenter.Visible = false;
                                    //btnReenter.Visible = false;
                                    btnLaunchLab.Text = "Launch Lab";
                                    btnLaunchLab.OnClientClick="";
                                    if (autoLaunch)
                                    {
                                        launchLabClient(lc.clientID);
                                    }
                                    else
                                    {
                                        pLaunch.Visible = true;
                                        btnLaunchLab.Visible = true;
                                    }
                                }
                            }
                            else
                            {
                                pLaunch.Visible = true;
                                btnLaunchLab.Visible = true;
                                btnLaunchLab.OnClientClick = "";
                                if (autoLaunch)
                                {
                                    launchLabClient(lc.clientID);
                                }
                            }
                        }
                        else
                        {
                            pLaunch.Visible = false;
                            btnLaunchLab.Visible = false;
                        }
                    }
                    else
                    {
                        pLaunch.Visible = true;
                        btnLaunchLab.Visible = true;
                        if (autoLaunch)
                        {
                            launchLabClient(lc.clientID);
                        }
                    }
                }
                else if (lc.clientType == LabClient.BATCH_APPLET || lc.clientType == LabClient.BATCH_HTML_REDIRECT)
                {
                    pLaunch.Visible = true;
                    btnLaunchLab.Visible = true;
                    if (autoLaunch)
                    {
                        launchLabClient(lc.clientID);
                    }

                }
                btnSchedule.Visible = lc.needsScheduling;
                lblClientName.Text = lc.clientName;
                lblVersion.Text = lc.version;
                lblLongDescription.Text = lc.clientLongDescription;
                if (lc.notes != null && lc.notes.Length > 0)
                {
                    pNotes.Visible = true;
                    lblNotes.Text = lc.notes;
                }
                else
                {
                    pNotes.Visible = false;
                    lblNotes.Text = null;
                }
                if (lc.contactEmail != null && lc.contactEmail.Length > 0)
                {
                    pEmail.Visible = true;
                    string emailCmd = "mailto:" + lc.contactEmail;
                    lblEmail.Text = "<a href=" + emailCmd + ">" + lc.contactEmail + "</a>";
                }
                else
                {
                    pEmail.Visible = false;
                    lblEmail.Text = null;
                }
                if (lc.documentationURL != null && lc.documentationURL.Length > 0)
                {
                    pDocURL.Visible = true;
                    lblDocURL.Text = "<a href=" + lc.documentationURL + ">" + lc.documentationURL + "</a>";
                }
                else
                {
                    pDocURL.Visible = false;
                    lblDocURL.Text = null;
                }

                btnLaunchLab.Command += new CommandEventHandler(this.btnLaunchLab_Click);
                btnLaunchLab.CommandArgument = lc.clientID.ToString();

                int count = 0;

                if (clientInfos != null && clientInfos.Length > 0)
                {
                    //repClientInfos.DataSource = clientInfos;
                    //repClientInfos.DataBind();
                    foreach (ClientInfo ci in clientInfos)
                    {
                        System.Web.UI.WebControls.Button b = new System.Web.UI.WebControls.Button();
                        b.Visible = true;
                        b.CssClass = "button";
                        b.Text = ci.infoURLName;
                        b.CommandArgument = ci.infoURL;
                        b.CommandName = ci.infoURLName;
                        b.ToolTip = ci.description;
                        b.Command += new CommandEventHandler(this.HelpButton_Click);
                        repClientInfos.Controls.Add(b);
                        repClientInfos.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
                    }
                }
            }
            else
            {
                // No LabClient
                btnSchedule.Visible = false;
                pLaunch.Visible = false;
                btnLaunchLab.Visible = false;
                string msg = "There are no labs assigned to group: " + Session["GroupName"].ToString() + "!";
                lblResponse.Text = Utilities.FormatErrorMessage(msg);
                lblResponse.Visible = true;
            }
            // System_Messages block

            SystemMessage[] groupMessages = null;
            SystemMessage[] serverMessages = null;
            groupMessages = AdministrativeAPI.SelectSystemMessagesForGroup(Convert.ToInt32(Session["GroupID"]));
            if (lc != null && labServer != null && labServer.agentId > 0)
            {
                serverMessages = wrapper.GetSystemMessagesWrapper(SystemMessage.LAB, 0, 0, labServer.agentId);
            }
            if ((groupMessages == null || groupMessages.Length == 0) && (serverMessages == null || serverMessages.Length == 0))
            {

                lblGroupNameSystemMessage.Text = "No Messages at this time!";
                lblGroupNameSystemMessage.Visible = true;
                lblServerSystemMessage.Visible = false;
            }
            else
            {
                if (groupMessages != null && groupMessages.Length > 0)
                {
                    lblGroupNameSystemMessage.Text = "Group Messages:";
                    lblGroupNameSystemMessage.Visible = true;
                    repGroupMessage.DataSource = groupMessages;
                    repGroupMessage.DataBind();
                }
                else
                {
                    lblGroupNameSystemMessage.Visible = false;
                }

                if (serverMessages != null && serverMessages.Length > 0)
                {
                    lblServerSystemMessage.Text = "Client/Server Messages:";
                    lblServerSystemMessage.Visible = true;
                    repServerMessage.DataSource = serverMessages;
                    repServerMessage.DataBind();
                }
                else
                {
                    lblServerSystemMessage.Visible = false;
                }
            }
        }
        public int LoadLabClient(XmlQueryDoc xdoc, ref StringBuilder message)
        {
            string guid = xdoc.Query("/clientDescriptor/clientGuid");
            string type = xdoc.Query("/clientDescriptor/clientType");
            string name = xdoc.Query("/clientDescriptor/clientName");
            string version = xdoc.Query("/clientDescriptor/version");
            string shortDescription = xdoc.Query("/clientDescriptor/clientShortDescription");
            string longDescription = xdoc.Query("/clientDescriptor/clientLongDescription");
            string contactEmail = HttpUtility.HtmlDecode(xdoc.Query("/clientDescriptor/contactEmail"));
            string contactFirstName = xdoc.Query("/clientDescriptor/contactFirstName");
            string contactLastName = xdoc.Query("/clientDescriptor/contactLastName");
            string loaderScript = xdoc.Query("/clientDescriptor/loaderScript");
            string tmp = xdoc.Query("/clientDescriptor/needsScheduling");
            bool needsScheduling = Convert.ToBoolean(tmp);
            tmp = xdoc.Query("/clientDescriptor/needsESS");
            bool needsESS = Convert.ToBoolean(tmp);
            tmp = xdoc.Query("/clientDescriptor/isReentrant");
            bool isReentrant = Convert.ToBoolean(tmp);
            string notes = xdoc.Query("/clientDescriptor/notes");

            // Insert the Client, Qualifier is created internally
            int newClientId = AdministrativeAPI.AddLabClient(guid, name, version, shortDescription,
                longDescription, notes, loaderScript, type, null, contactEmail, contactFirstName, contactLastName, needsScheduling, needsESS, isReentrant, null);
            // parse the LabServer list
            ArrayList labServers = new ArrayList();
            XPathNodeIterator iter = xdoc.Select("/clientDescriptor/labServers/*");
            if (iter != null && iter.Count > 0)
            {
                while (iter.MoveNext())
                {
                    string lsGuid = iter.Current.GetAttribute("guid", ns);
                    int serverID = brokerDb.GetProcessAgentID(lsGuid);
                    if (serverID > 0)
                    {
                        labServers.Add(serverID);
                    }

                }
            }

            // deal with resources
            iter = xdoc.Select("/clientDescriptor/clientInfos/*");
            ArrayList clientItems = new ArrayList();
            if (iter != null && iter.Count > 0)
            {
                while (iter.MoveNext())
                {
                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo.infoURL = iter.Current.GetAttribute("infoUrl", ns);
                    clientInfo.infoURLName = iter.Current.GetAttribute("infoUrlName", ns);
                    clientInfo.description = iter.Current.GetAttribute("description", ns);
                    clientInfo.displayOrder = Int32.Parse(iter.Current.GetAttribute("displayOrder", ns));
                    clientItems.Add(clientInfo);
                }
            }

            message.Append(" Registered a new LabClient. ");
            message.AppendLine(" GUID: " + guid + " -> " + name);

            if (labServers.Count > 0 || clientItems.Count > 0)
            {
                int[] servers = new int[labServers.Count];
                for (int j = 0; j < labServers.Count; j++)
                {
                    servers[j] = (int)labServers[j];
                }
                ClientInfo[] infos = new ClientInfo[clientItems.Count];
                for (int k = 0; k < clientItems.Count; k++)
                {
                    infos[k] = (ClientInfo)clientItems[k];
                }

                AdministrativeAPI.ModifyLabClient(newClientId, name, version, shortDescription,
                longDescription, notes, loaderScript, type, servers, contactEmail, contactFirstName,
                contactLastName, needsScheduling, needsESS, isReentrant, infos);
            }

            return newClientId;
        }
 public GroupCredential ParseCredential(XmlQueryDoc xdoc, ref StringBuilder message)
 {
     GroupCredential credential = new GroupCredential();
     credential.domainGuid = xdoc.Query("/credentialDescriptor/domainGuid");
     credential.domainServerName = xdoc.Query("/credentialDescriptor/serviceBrokerName");
     credential.groupName = xdoc.Query("/credentialDescriptor/groupName");
     credential.ussGuid = xdoc.Query("/credentialDescriptor/ussGuid");
     credential.lssGuid = xdoc.Query("/credentialDescriptor/lssGuid");
     return credential;
 }
 public static SessionInfo ParseRedeemSessionPayload(string payload)
 {
     SessionInfo sessionInfo = null;
     if(payload != null && payload.Length >0){
     // Get Session info
         XmlQueryDoc expDoc = new XmlQueryDoc(payload);
         sessionInfo = new SessionInfo();
         string STR_RedeemSessionPayload = "RedeemSessionPayload/";
         string userID = expDoc.Query(STR_RedeemSessionPayload + "userID");
         sessionInfo.userID = Convert.ToInt32(userID);
         string groupID = expDoc.Query(STR_RedeemSessionPayload + "groupID");
         sessionInfo.groupID = Convert.ToInt32(groupID);
         string clientID = expDoc.Query(STR_RedeemSessionPayload + "clientID");
         sessionInfo.clientID = Convert.ToInt32(clientID);
         sessionInfo.userName = expDoc.Query(STR_RedeemSessionPayload + "userName");
         sessionInfo.groupName = expDoc.Query(STR_RedeemSessionPayload + "groupName");
     }
     return sessionInfo;
 }
 public static SystemSupport Parse(string xml)
 {
     XmlQueryDoc xdoc = new XmlQueryDoc(xml);
     return Parse(xdoc);
 }
        public override eStatus Close(eStatus reason)
        {
            LabDB dbService = new LabDB();
            LabViewInterface lvi = null;
            try
            {
                if (data != null)
                {
                    XmlQueryDoc taskDoc = new XmlQueryDoc(data);
                    string viName = taskDoc.Query("task/application");
                    string statusVI = taskDoc.Query("task/status");
                    string server = taskDoc.Query("task/server");
                    string portStr = taskDoc.Query("task/serverPort");
#if LabVIEW_WS
                     lvi = new LabViewInterface();
#else
                    if ((portStr != null) && (portStr.Length > 0) && (portStr.CompareTo("0") != 0) )
                    {
                        lvi = new LabViewRemote(server, Convert.ToInt32(portStr));
                    }
                    else
                    {
                        lvi = new LabViewInterface();
                    }
#endif

                    // Status VI not used 
                    if ((statusVI != null) && statusVI.Length != 0)
                    {
                        try
                        {
                            if(reason == eStatus.Expired)
                                lvi.DisplayStatus(statusVI, "You are out of time!", "0:00");
                            else
                                lvi.DisplayStatus(statusVI, "Your experiment has been cancelled", "0:00");
                        }
                        catch (Exception ce)
                        {
                           Logger.WriteLine("Trying StatusVI: " + ce.Message);
                        }
                    }


                    //Get the VI and send version specfic call to get control of the VI
                   //VirtualInstrument vi = lvi.GetVI(viName);
                    // LV 8.2.1
                    //Server takes control of RemotePanel, connection not brokenS
                    lvi.ReleaseVI(viName);
                }
               Logger.WriteLine("TaskID = " + taskID + " has expired");
                dbService.SetTaskStatus(taskID, (int)reason);
                status = eStatus.Closed;
               
                    DataSourceManager dsManager = TaskProcessor.Instance.GetDataManager(taskID);
                    if (dsManager != null)
                    {
                        dsManager.CloseDataSources();
                        TaskProcessor.Instance.RemoveDataManager(taskID);
                    }
                
                dbService.SetTaskStatus(taskID, (int)status);
                if (couponID > 0)
                { // this task was created with a valid ticket, i.e. not a test.
                    Coupon expCoupon = dbService.GetCoupon(couponID, issuerGUID);

                    // Only use the domain ServiceBroker, do we need a test
                    // Should only be one
                    ProcessAgentInfo[] sbs = dbService.GetProcessAgentInfos(ProcessAgentType.SERVICE_BROKER);

                    if ((sbs == null) || (sbs.Length < 1))
                    {
                       Logger.WriteLine("Can not retrieve ServiceBroker!");
                        throw new Exception("Can not retrieve ServiceBroker!");
                    }
                    ProcessAgentInfo domainSB = null;
                    foreach (ProcessAgentInfo dsb in sbs)
                    {
                        if (!dsb.retired)
                        {
                            domainSB = dsb;
                            break;
                        }
                    }
                    if (domainSB == null)
                    {
                       Logger.WriteLine("Can not retrieve ServiceBroker!");
                        throw new Exception("Can not retrieve ServiceBroker!");
                    }
                    InteractiveSBProxy iuProxy = new InteractiveSBProxy();
                    iuProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                    iuProxy.AgentAuthHeaderValue.coupon = sbs[0].identOut;
                    iuProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    iuProxy.Url = sbs[0].webServiceUrl;
                    StorageStatus storageStatus = iuProxy.AgentCloseExperiment(expCoupon, experimentID);
                   Logger.WriteLine("AgentCloseExperiment status: " + storageStatus.status + " records: " + storageStatus.recordCount);


                    // currently RequestTicketCancellation always returns false
                    // Create ticketing service interface connection to TicketService
                    TicketIssuerProxy ticketingInterface = new TicketIssuerProxy();
                    ticketingInterface.AgentAuthHeaderValue = new AgentAuthHeader();
                    ticketingInterface.Url = sbs[0].webServiceUrl;
                    ticketingInterface.AgentAuthHeaderValue.coupon = sbs[0].identOut;
                    ticketingInterface.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    if (ticketingInterface.RequestTicketCancellation(expCoupon, TicketTypes.EXECUTE_EXPERIMENT, ProcessAgentDB.ServiceGuid))
                    {
                        dbService.CancelTicket(expCoupon, TicketTypes.EXECUTE_EXPERIMENT, ProcessAgentDB.ServiceGuid);
                       Logger.WriteLine("Canceled ticket: " + expCoupon.couponId);
                    }
                    else
                    {
                       Logger.WriteLine("Unable to cancel ticket: " + expCoupon.couponId);
                    }
                }
            }
            catch (Exception e1)
            {
               Logger.WriteLine("ProcessTasks Cancelled: exception:" + e1.Message + e1.StackTrace);
            }
            finally
            {
                lvi = null;
            }
            return base.Close();
        }
        public override eStatus HeartBeat()
        {

            try
            {
                if (status == eStatus.Running)
                {
                    if (data != null)
                    {
                        XmlQueryDoc taskDoc = new XmlQueryDoc(data);
                        string vi = taskDoc.Query("task/application");
                        string statusVI = taskDoc.Query("task/status");

                        if ((statusVI != null) && (statusVI.Length > 0))
                        {
                            I_LabViewInterface lvi = null;
                            try
                            {
                                string server = taskDoc.Query("task/server");
                                string portStr = taskDoc.Query("task/serverPort");
#if LabVIEW_WS
                                lvi = new LabViewInterface();
#else
                                if (((server != null) && (server.Length > 0)) && ((portStr != null) && (portStr.Length > 0)))
                                {
                                    lvi = new LabViewRemote(server, Convert.ToInt32(portStr));
                                }
                                else
                                {
                                    lvi = new LabViewInterface();
                                }
#endif
                                long ticks = endTime.Ticks - DateTime.UtcNow.Ticks;
                                TimeSpan val = new TimeSpan(ticks);
                                lvi.DisplayStatus(statusVI, "TaskID: " + taskID, val.Minutes + ":" + val.Seconds);
                            }
                            catch (Exception ce2)
                            {
                               Logger.WriteLine("Status: " + ce2.Message);
                                throw;
                            }
                            finally
                            {
                                lvi = null;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
               Logger.WriteLine("ProcessTasks Status: " + e.Message);
            }
            return status;
        }
        public int RevokeReservation(string serviceBrokerGuid, string groupName,
            string labServerGuid, string labClientGuid, DateTime startTime, DateTime endTime, string message)
        {
            bool status = false;
            bool fromISB = false;
            int count = 0;
            Coupon opCoupon = new Coupon();
            opCoupon.couponId = opHeader.coupon.couponId;
            opCoupon.passkey = opHeader.coupon.passkey;
            opCoupon.issuerGuid = opHeader.coupon.issuerGuid;
            UserSchedulingDB dbManager = new UserSchedulingDB();
            try
            {
                Ticket retrievedTicket = dbManager.RetrieveAndVerify(opCoupon, TicketTypes.REVOKE_RESERVATION);
                if (retrievedTicket.payload != null && retrievedTicket.payload.Length > 0)
                {
                    XmlQueryDoc revokeDoc = new XmlQueryDoc(retrievedTicket.payload);
                    string sourceStr = revokeDoc.Query("RevokeReservationPayload/source");
                    if (sourceStr != null && sourceStr.CompareTo("ISB") == 0)
                    {
                        fromISB = true;
                    }
                }
                DateTime targetStart = new DateTime(startTime.Year, startTime.Month, startTime.Day,
                    startTime.Hour, startTime.Minute, 0, startTime.Kind);
                if (targetStart.Kind != DateTimeKind.Utc)
                    targetStart = targetStart.ToUniversalTime();
                DateTime targetEnd = new DateTime(endTime.Year, endTime.Month, endTime.Day,
                    endTime.Hour, endTime.Minute, 0, endTime.Kind);
                if (targetEnd.Kind != DateTimeKind.Utc)
                    targetEnd = targetEnd.ToUniversalTime();
                if (fromISB)
                { // Need to forward to LSS
                    string lssUrl = dbManager.ListLssUrlByExperiment(labClientGuid, labServerGuid);
                    if (lssUrl != null && lssUrl.Length > 0)
                    {
                        LabSchedulingProxy lssProxy = new LabSchedulingProxy();
                        lssProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                        lssProxy.OperationAuthHeaderValue.coupon = opCoupon;
                        lssProxy.Url = lssUrl;
                        int rCount = lssProxy.RemoveReservation(serviceBrokerGuid, groupName, ProcessAgentDB.ServiceGuid,
                            labServerGuid, labClientGuid, targetStart, targetEnd);
                    }
                }

                ReservationData[] ris = dbManager.GetReservations(serviceBrokerGuid, null, groupName,
                    labServerGuid, labClientGuid, targetStart, targetEnd);

                if (ris != null && ris.Length > 0)
                {

                    InteractiveSBProxy sbProxy = new InteractiveSBProxy();
                    ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(ProcessAgentDB.ServiceAgent.domainGuid);
                    AgentAuthHeader header = new AgentAuthHeader();
                    header.coupon = sbInfo.identOut;
                    header.agentGuid = ProcessAgentDB.ServiceGuid;
                    sbProxy.AgentAuthHeaderValue = header;
                    sbProxy.Url = sbInfo.webServiceUrl;
                    foreach (ReservationData rd in ris)
                    {

                        status = dbManager.RevokeReservation(rd.sbGuid, rd.groupName, rd.lsGuid, rd.clientGuid,
                              rd.startTime, rd.endTime, message);
                        if (status)
                        {
                            count++;
                            status = sbProxy.RevokeReservation(rd.sbGuid, rd.userName, rd.groupName, rd.lsGuid, rd.clientGuid,
                              rd.startTime, rd.endTime, message);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("USS: RevokeReservation -> ",e);
            }
            return count;
        }
Exemple #15
0
        public static LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {
            // set defaults
            DateTime startTime = DateTime.UtcNow;
            long duration = -1L;
            long experimentID = 0;
            int status = -1;

            string statusViName = null;
            string statusTemplate = null;
            string templatePath = null;
            LabDB dbManager = new LabDB();
            string qualName = null;
            string fullName = null;  // set defaults
           
            LabTask labTask = null;
            LabViewTask task = null;
            VirtualInstrument vi = null;
            LabViewInterface lvi = null;
            

            ////Parse experiment payload, only get what is needed 	
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);
            string essService = expDoc.Query("ExecuteExperimentPayload/essWebAddress");
            string startStr = expDoc.Query("ExecuteExperimentPayload/startExecution");
            string durationStr = expDoc.Query("ExecuteExperimentPayload/duration");
            string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
            string userName = expDoc.Query("ExecuteExperimentPayload/userName");

            if ((startStr != null) && (startStr.Length > 0))
            {
                startTime = DateUtil.ParseUtc(startStr);
            }
            if ((durationStr != null) && (durationStr.Length > 0) && !(durationStr.CompareTo("-1") == 0))
            {
                duration = Convert.ToInt64(durationStr);
            }


            if (appInfo.extraInfo != null && appInfo.extraInfo.Length > 0)
            {
                // Note should have either statusVI or template pair
                // Add Option for VNCserver access
                try
                {
                    XmlQueryDoc viDoc = new XmlQueryDoc(appInfo.extraInfo);
                    statusViName = viDoc.Query("extra/status");
                    statusTemplate = viDoc.Query("extra/statusTemplate");
                    templatePath = viDoc.Query("extra/templatePath");
                }
                catch (Exception e)
                {
                    string err = e.Message;
                }
            }

            // log the experiment for debugging

            Utilities.WriteLog("Experiment: " + experimentID + " Start: " + DateUtil.ToUtcString(startTime) + " \tduration: " + duration);
            long statusSpan = DateUtil.SecondsRemaining(startTime, duration);



            if ((appInfo.server != null) && (appInfo.server.Length > 0) && (appInfo.port > 0))
            {
                lvi = new LabViewRemote(appInfo.server, appInfo.port);
            }
            else
            {
                lvi = new LabViewInterface();
            }
            if (!lvi.IsLoaded(appInfo.application))
            {
                vi = lvi.loadVI(appInfo.path, appInfo.application);
                vi.OpenFrontPanel(true, FPStateEnum.eVisible);
            }
            else
            {
                vi = lvi.GetVI(appInfo.path, appInfo.application);
            }
            if (vi == null)
            {
                status = -1;
                string err = "Unable to Find: " + appInfo.path + @"\" + appInfo.application;
                Utilities.WriteLog(err);
                throw new Exception(err);
            }
            // Get qualifiedName
            qualName = lvi.qualifiedName(vi);
            fullName = appInfo.path + @"\" + appInfo.application;


            status = lvi.GetVIStatus(vi);

            Utilities.WriteLog("CreateLabTask - " + qualName + ": VIstatus: " + status);
            switch (status)
            {
                case -10:
                    throw new Exception("Error GetVIStatus: " + status);
                    break;
                case -1:
                    // VI not in memory
                    throw new Exception("Error GetVIStatus: " + status);

                    break;
                case 0: // eBad == 0
                    break;
                case 1: // eIdle == 1 vi in memory but not running 
                    FPStateEnum fpState = vi.FPState;
                    if (fpState != FPStateEnum.eVisible)
                    {
                        vi.OpenFrontPanel(true, FPStateEnum.eVisible);
                    }
                    vi.ReinitializeAllToDefault();
                    break;
                case 2: // eRunTopLevel: this should be the LabVIEW application
                    break;
                case 3: // eRunning
                    //Unless the Experiment is reentrant it should be stopped and be reset.
                    if(!appInfo.reentrant){
                        int stopStatus = lvi.StopVI(vi);
                        if (stopStatus != 0)
                        {
                            lvi.AbortVI(vi);
                        }
                        vi.ReinitializeAllToDefault();
                    }
                    break;
                default:
                    throw new Exception("Error GetVIStatus: unknown status: " + status);
                    break;
            }
            try
            {
                lvi.SetBounds(vi, 0, 0, appInfo.width, appInfo.height);
                Utilities.WriteLog("SetBounds: " + appInfo.application);
            }
            catch (Exception sbe)
            {
                Utilities.WriteLog("SetBounds exception: " + Utilities.DumpException(sbe));
            }
            lvi.SubmitAction("unlockvi", lvi.qualifiedName(vi));
            Utilities.WriteLog("unlockvi Called: ");


            // Set up in-memory and database task control structures
            DataSourceManager dsManager = null;

            // Create the labTask & store in database;
            labTask = dbManager.InsertTask(appInfo.appID, experimentID,
           groupName, startTime, duration,
           LabTask.eStatus.Scheduled, expTicket.couponId, expTicket.issuerGuid, null);
            if (labTask != null)
            {
                //Convert the generic LabTask to a LabViewTask
                task = new LabViewTask(labTask);
            }
            if ((statusTemplate != null) && (statusTemplate.Length > 0))
            {
                statusViName = lvi.CreateFromTemplate(templatePath, statusTemplate, task.taskID.ToString());
            }


            if (((essService != null) && (essService.Length > 0)) && ((appInfo.dataSources != null) && (appInfo.dataSources.Length > 0)))
            {
                // Create DataSourceManager to manage dataSocket connections
                dsManager = new DataSourceManager();

                // set up an experiment storage handler
                ExperimentStorageProxy ess = new ExperimentStorageProxy();
                ess.OperationAuthHeaderValue = new OperationAuthHeader();
                ess.OperationAuthHeaderValue.coupon = expCoupon;
                ess.Url = essService;
                dsManager.essProxy = ess;
                dsManager.ExperimentID = experimentID;
                dsManager.AppKey = qualName;
                string[] sockets = appInfo.dataSources.Split(',');
                // Use the experimentID as the storage parameter
                foreach (string s in sockets)
                {
                    LVDataSocket reader = new LVDataSocket();
                    dsManager.AddDataSource(reader);
                    if (s.Contains("="))
                    {
                        string[] nv = s.Split('=');
                        reader.Type = nv[1];
                        reader.Connect(nv[0], LabDataSource.READ_AUTOUPDATE);

                    }
                    else
                    {
                        reader.Connect(s, LabDataSource.READ_AUTOUPDATE);
                    }

                }
                TaskProcessor.Instance.AddDataManager(task.taskID, dsManager);
            }
            string taskData = null;
            taskData = LabTask.constructTaskXml(appInfo.appID, fullName,appInfo.rev, statusViName, essService);
            dbManager.SetTaskData(task.taskID, taskData);
            task.data = taskData;
            TaskProcessor.Instance.Add(task);
            return task;
        }
Exemple #16
0
        public override eStatus HeartBeat()
        {
            try
            {
                switch(status){
                    case eStatus.Running:
                    if (data != null)
                    {
                        XmlQueryDoc taskDoc = new XmlQueryDoc(data);
                        string app = taskDoc.Query("task/application");
                        string statusName = taskDoc.Query("task/status");

                    }
                    break;
                    case eStatus.Scheduled:
                        break;
                    default:
                        break;

                }
            }
            catch (Exception e)
            {
                Logger.WriteLine("HeartBeat: " + e.Message);
            }
            return status;
        }
Exemple #17
0
        public int RemoveTickets(List<Ticket> ticketList, BrokerDB brokerDb)
        {
            ArrayList coupons = new ArrayList();
            Coupon coupon = null;
            int ticketCount = 0;
            int couponCount = 0;
            if (ticketList.Count > 0)
            {
                Utilities.WriteLog("RemoveTickets: expired count = " + ticketList.Count);

                foreach (Ticket ticket in ticketList)
                {
                    if (!coupons.Contains(ticket.couponId))
                    {
                        coupons.Add(ticket.couponId);
                    }
                    if (coupon == null || coupon.couponId != ticket.couponId)
                    {
                        coupon = brokerDb.GetIssuedCoupon(ticket.couponId);
                    }
                    switch (ticket.type)
                    {
                        case TicketTypes.ADMINISTER_EXPERIMENT:

                            string payload = ticket.payload;
                            if (payload != null)
                            {
                                XmlQueryDoc xDoc = new XmlQueryDoc(payload);
                                string url = xDoc.Query("AdministerExperimentPayload/essURL");
                                string expStr = xDoc.Query("AdministerExperimentPayload/experimentID");
                                long expID = Convert.ToInt64(expStr);
                                ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
                                essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                                essProxy.OperationAuthHeaderValue.coupon = coupon;
                                essProxy.Url = url;
                                StorageStatus expStatus = essProxy.SetExperimentStatus(expID, (int)StorageStatus.CLOSED_TIMEOUT);
                                DataStorageAPI.UpdateExperimentStatus(expStatus);
                            }
                            break;
                        case TicketTypes.RETRIEVE_RECORDS:
                        case TicketTypes.STORE_RECORDS:
                            break;
                        case TicketTypes.EXECUTE_EXPERIMENT:
                        case TicketTypes.ALLOW_EXPERIMENT_EXECUTION:
                            break;
                        default: // Every other Ticket type
                            break;
                    }
                    bool statusR = false;

                    if (ticket.redeemerGuid != brokerDb.GetIssuerGuid())
                    {
                        ProcessAgentInfo redeemer = brokerDb.GetProcessAgentInfo(ticket.redeemerGuid);
                        if ((redeemer != null) && !redeemer.retired)
                        {
                            ProcessAgentProxy paProxy = new ProcessAgentProxy();
                            paProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                            paProxy.Url = redeemer.webServiceUrl;
                            paProxy.AgentAuthHeaderValue.coupon = redeemer.identOut;
                            paProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                            statusR = paProxy.CancelTicket(coupon, ticket.type, ticket.redeemerGuid);
                        }
                    }
                    if (ticket.issuerGuid == brokerDb.GetIssuerGuid())
                    {
                        brokerDb.DeleteIssuedTicket(ticket.ticketId);
                        ticketCount++;
                    }
                }
                foreach (long id in coupons)
                {
                    int count = brokerDb.GetIssuedCouponCollectionCount(id);
                    if (count == 0)
                    {
                        brokerDb.DeleteIssuedCoupon(id);
                        couponCount++;
                    }
                }
                Utilities.WriteLog("RemoveTickets: ticketCount=" + ticketCount + " \tcouponCount=" + couponCount);
            }
            return ticketCount;
        }
        public override LabTask CreateLabTask(LabAppInfo appInfo, Coupon expCoupon, Ticket expTicket)
        {
            long experimentID = -1;
            LabTask task = null;
            string revision = null;
            //Parse experiment payload
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);

            string experimentStr = expDoc.Query("ExecuteExperimentPayload/experimentID");
            if ((experimentStr != null) && (experimentStr.Length > 0))
            {
                experimentID = Convert.ToInt64(experimentStr);
            }
            string sbStr = expDoc.Query("ExecuteExperimentPayload/sbGuid");

            // Check to see if an experiment with this ID is already running
            LabDB dbManager = new LabDB();
            LabTask.eStatus status = dbManager.ExperimentStatus(experimentID, sbStr);
            if (status == LabTask.eStatus.NotFound)
            {
                // Check for an existing experiment using the same resources, if found Close it

                //Create the new Task
                if (appInfo.rev == null || appInfo.rev.Length < 2)
                {
                    revision = appInfo.rev;
                }
                else
                {
                    revision = ConfigurationManager.AppSettings["LabViewVersion"];
                }
                if (revision != null && revision.Length > 2)
                {
                    if (revision.Contains("8.2"))
                    {
                        task = new iLabs.LabView.LV82.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }
                    else if (revision.Contains("8.6"))
                    {
                        task = new iLabs.LabView.LV86.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }
                    else if (revision.Contains("2009"))
                    {
                        task = new iLabs.LabView.LV2009.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }

                    else if (revision.Contains("2010"))
                    {
                        task = new iLabs.LabView.LV2010.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }
                    else if (revision.Contains("2011"))
                    {
                        task = new iLabs.LabView.LV2011.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }
                    else if (revision.Contains("2012"))
                    {
                        task = new iLabs.LabView.LV2012.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }
                    else if (revision.Contains("WS"))
                    {
                        task = new iLabs.LabView.LVWS.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                    }
                }
                else // Default to LV 2009
                {
                    task = new iLabs.LabView.LV2009.LabViewInterface().CreateLabTask(appInfo, expCoupon, expTicket);
                }

            }
            else
            {
                task =  TaskProcessor.Instance.GetTask(experimentID,expCoupon.issuerGuid);
            }
            return task;
        }
        protected long[] getExperimentIDs(Coupon opCoupon, Criterion[] carray)
        {
            int userID = 0;
            int groupID = 0;
            long[] expIDs = null;
            Ticket expTicket = brokerDB.RetrieveTicket(opCoupon, TicketTypes.REDEEM_SESSION);
            if (expTicket != null && !expTicket.IsExpired())
            {
                //Parse payload, only get what is needed

                XmlQueryDoc expDoc = new XmlQueryDoc(expTicket.payload);
                long expID = -1;

                string userStr = expDoc.Query("RedeemSessionPayload/userID");
                if ((userStr != null) && (userStr.Length > 0))
                    userID = Convert.ToInt32(userStr);
                string groupStr = expDoc.Query("RedeemSessionPayload/groupID");
                if ((groupStr != null) && (groupStr.Length > 0))
                    groupID = Convert.ToInt32(groupStr);

                if (userID > 0)
                {

                    expIDs = DataStorageAPI.RetrieveAuthorizedExpIDs(userID, groupID, carray);
                }
            }
            return expIDs;
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            LabDB dbManager = new LabDB();
            int appID = 0;
            long expID = 0;
            LabTask task = null;
            string pageURL = null;
            // Query values from the request

            string appKey = Request.QueryString["app"];
            string coupon_Id = Request.QueryString["coupon_id"];
            string passkey = Request.QueryString["passkey"];
            string issuerGUID = Request.QueryString["issuer_guid"];
            string returnTarget = Request.QueryString["sb_url"];

            if ((returnTarget != null) && (returnTarget.Length > 0))
                Session["returnURL"] = returnTarget;

               Logger.WriteLine("BEElab: " + Request.Url.ToString());

            // this should be the Experiment Coupon data
            if (!(passkey != null && passkey != "" && coupon_Id != null && coupon_Id != "" && issuerGUID != null && issuerGUID != ""))
            {
                Logger.WriteLine("BEElab: " + "AccessDenied missing Experiment credentials");
                Response.Redirect("AccessDenied.aspx?text=missing+Experiment+credentials.", true);
            }

            long expCoupId = Convert.ToInt64(coupon_Id);
            Coupon expCoupon = new Coupon(issuerGUID, expCoupId, passkey);

            //Check the database for ticket and coupon, if not found Redeem Ticket from
            // issuer and store in database.
            //This ticket should include group, experiment id and be valid for this moment in time??
            Ticket expTicket = dbManager.RetrieveAndVerify(expCoupon, TicketTypes.EXECUTE_EXPERIMENT);

            if (expTicket != null)
            {
                if (expTicket.IsExpired())
                {
                    Response.Redirect("AccessDenied.aspx?text=The ExperimentExecution+ticket+has+expired.", true);

                }

                ////Parse experiment payload, only get what is needed
                string payload = expTicket.payload;
                XmlQueryDoc expDoc = new XmlQueryDoc(payload);
                string tzStr = expDoc.Query("ExecuteExperimentPayload/userTZ");
                if ((tzStr != null) && (tzStr.Length > 0))
                    Session["userTZ"] = tzStr;
                string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
                Session["groupName"] = groupName;
                string sbStr = expDoc.Query("ExecuteExperimentPayload/sbGuid");
                string essUrl = expDoc.Query("ExecuteExperimentPayload/essWebAddress");
                expID = Convert.ToInt64(expDoc.Query("ExecuteExperimentPayload/experimentID"));
                Session["brokerGUID"] = sbStr;

                //Get Lab specific info for this URL or group
                LabAppInfo appInfo = null;
                // Experiment is specified by 'app=appKey'
                if (appKey != null && appKey.Length > 0)
                {
                    appInfo = dbManager.GetLabApp(appKey);
                }
                else // Have to use groupName & Servicebroker THIS REQUIRES groups & permissions are set in database
                {    // This is no longer the case as the USS handles groups and permissions
                    appInfo = dbManager.GetLabAppForGroup(groupName, sbStr);
                }
                if (appInfo == null)
                {
                    Response.Redirect("AccessDenied.aspx?text=Unable+to+find+application+information,+please+notify+your+administrator.", true);
                }

                // Check to see if an experiment with this ID is already running
                // Check for an existing task for this experiment
                // If found redirect to the graph page, do not abort running controller program
                LabTask.eStatus status = dbManager.ExperimentStatus(expID, sbStr);
                if (status == LabTask.eStatus.NotFound)
                {
                    // Check for existing tasks that may be using resources
                    // For now only close other instances of the lab
                    List<LabTask> curTasks = TaskProcessor.Instance.GetTasks(appInfo.appID);
                    if (curTasks != null && curTasks.Count > 0)
                    {
                        foreach (LabTask t in curTasks)
                        {
                            DataSourceManager dsManager = TaskProcessor.Instance.GetDataManager(t.taskID);
                            if (dsManager != null)
                            {
                                // Need to close existing data Sources
                                TaskProcessor.Instance.Remove(t);
                                t.Close();
                            }
                        }
                    }

                    // Create a new Experiment task
                    // Use taskFactory to create a new task
                    LabTaskFactory factory = new LabTaskFactory();
                    task = factory.CreateLabTask(appInfo, expCoupon, expTicket);

                    if (task != null)
                    {
                        string filePath = "c:\\logs\\Campbell\\LoggerNet";
                        string fileName = "CECI-CR10X_final_storage_1.dat";
                        // Stop the controller and flush the data file

                        //Flush the File
                        FileInfo fInfo = new FileInfo(filePath +"\\" + fileName);
                        using (FileStream inFile = fInfo.Open(FileMode.Truncate)) { }

                        string pushChannel = ChecksumUtil.ToMD5Hash("BEElab" + expID);
                        //Add BEElab specific attributes
                        BeeEventHandler bEvt = new BeeEventHandler(expCoupon,expID,essUrl,
                            "data",ProcessAgentDB.ServiceGuid);
                        bEvt.PusherChannel = pushChannel;
                        DataSourceManager dsManager = TaskProcessor.Instance.GetDataManager(task.taskID);
                        FileWatcherDataSource fds = new FileWatcherDataSource();
                        fds.Path = filePath;
                        fds.Filter = fileName;
                        fds.AddFileSystemEventHandler(bEvt.OnChanged);
                        dsManager.AddDataSource(fds);
                        fds.Start();

                        //Useful for debugging overloads the use of a field in the banner
                        //Session["GroupName"] = "TaskID: " + task.taskID.ToString();

                        //Utilities.WriteLog("TaskXML: " + task.taskID + " \t" + task.data);

                        ////Construct the information to be passed to the target page
                        //TimeSpan taskDur = task.endTime - task.startTime;
                        //string vipayload = LabTask.constructSessionPayload(appInfo,
                        //    task.startTime, taskDur.Ticks / TimeSpan.TicksPerSecond, task.taskID,
                        //    returnTarget, null, null);

                        ////Utilities.WriteLog("sessionPayload: " + payload);
                        ////Store Session information
                        //Session["payload"] = vipayload;
                        //if (appInfo.rev != null && appInfo.rev.Length > 0)
                        //{
                        //    Session["lvversion"] = appInfo.rev;
                        //}
                        //else
                        //{
                        //    Session.Remove("lvversion");
                        //}

                        //set Presentation page tp appPage
                        pageURL = appInfo.page;

                    }
                    else
                    {
                        Response.Redirect("AccessDenied.aspx?text=Unable+to+launch++application,+please+notify+your+administrator.", true);
                    }
                }
                else
                { // An existing Experiment
                    task = TaskProcessor.Instance.GetTask(expID, sbStr);
                    if (task.data != null)
                    {
                        XmlQueryDoc taskDoc = new XmlQueryDoc(task.data);
                        pageURL = taskDoc.Query("task/application");
                    }
                    if (pageURL == null || pageURL.Length == 0)
                    {
                        pageURL = appInfo.page;
                    }
                }
            }
            if(pageURL != null && pageURL.Length >0){
                StringBuilder buf = new StringBuilder(pageURL + "?expid=" + expID);
                Session["opCouponID"] = coupon_Id;
                Session["opPasscode"] = passkey;
                Session["opIssuer"] = issuerGUID;
                buf.Append("&coupon_id=" + coupon_Id);
                buf.Append("&passkey=" + passkey);
                buf.Append("&issuer_guid=" + issuerGUID);
                buf.Append("&sb_url=" + returnTarget );
                Response.Redirect(buf.ToString(), true);
            }
            else{
                 Response.Redirect("AccessDenied.aspx?text=Unable+to+launch++application,+please+notify+your+administrator.", true);
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            LabDB dbManager = new LabDB();
            if (!IsPostBack)
            {
                // Query values from the request
                //clearSessionInfo();
                hdnExpId.Value = Request.QueryString["expid"];
                hdnCoupon.Value = Request.QueryString["coupon_id"];
                hdnPasscode.Value = Request.QueryString["passkey"];
                hdnIssuer.Value = Request.QueryString["issuer_guid"];
                hdnSbUrl.Value = Request.QueryString["sb_url"];
               string expLen  = Request.QueryString["explen"];
               string timeUnit = Request.QueryString["tu"];
               if (timeUnit != null && timeUnit.Length > 0)
                   hdnTimeUnit.Value = timeUnit;

                string userName = null;
                string userIdStr = null;

                int tz = 0;
                if (Session["userTZ"] != null)
                    tz = Convert.ToInt32(Session["userTZ"]);
                if (Session["sbUrl"] != null)
                {
                    String returnURL = (string)Session["sbUrl"];
                }

                //// this should be the RedeemSession & Experiment Coupon data
                if (!(Session["opPasscode"] != null && Session["opPasscode"] != ""
                    && Session["opCouponID"] != null && Session["opCouponID"] != ""
                    && Session["opIssuer"] != null && Session["opIssuer"] != ""))
                {
                    Logger.WriteLine("BEEstartAll: " + "AccessDenied missing credentials");
                    Response.Redirect("AccessDenied.aspx?text=missing+credentials.", true);
                }

                Coupon expCoupon = new Coupon(Session["opIssuer"].ToString(), Convert.ToInt64(Session["opCouponID"]), Session["opPasscode"].ToString());

                //Check the database for ticket and coupon, if not found Redeem Ticket from
                // issuer and store in database.
                //This ticket should include group, experiment id and be valid for this moment in time??
                Ticket expTicket = dbManager.RetrieveAndVerify(expCoupon, TicketTypes.EXECUTE_EXPERIMENT);

                if (expTicket != null)
                {
                    if (expTicket.IsExpired())
                    {
                        Response.Redirect("AccessDenied.aspx?text=The ExperimentExecution+ticket+has+expired.", true);

                    }
                    Session["exCoupon"] = expCoupon;

                    ////Parse experiment payload, only get what is needed
                    string payload = expTicket.payload;
                    XmlQueryDoc expDoc = new XmlQueryDoc(payload);
                    string expIdStr = expDoc.Query("ExecuteExperimentPayload/experimentID");
                    hdnExpId.Value = expIdStr;
                    string tzStr = expDoc.Query("ExecuteExperimentPayload/userTZ");
                    //string userIdStr = expDoc.Query("ExecuteExperimentPayload/userID");
                    string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
                    Session["groupName"] = groupName;
                    string sbStr = expDoc.Query("ExecuteExperimentPayload/sbGuid");
                    Session["brokerGUID"] = sbStr;
                    string startStr = expDoc.Query("ExecuteExperimentPayload/startExecution");
                    string durStr = expDoc.Query("ExecuteExperimentPayload/duration");
                    writeExpLength(startStr,durStr);
                    if ((tzStr != null) && (tzStr.Length > 0))
                    {
                        Session["userTZ"] = tzStr;
                    }

                }
            }
        }
        protected override void register(string registerGuid, ServiceDescription[] info)
        {
            StringBuilder message = new StringBuilder();
            message.AppendLine("Service " + ProcessAgentDB.ServiceAgent.codeBaseUrl + " recieved a 'Register' webService call.");

            if (info == null)
            {
                //message.AppendLine("Register called without any ServiceDescriptions");
                throw new ArgumentNullException("Register called without any ServiceDescriptions");
            }

            try
            {
                base.register(registerGuid, info);
            }
            catch (Exception e)
            {
                message.AppendLine("Error in base.register" + Utilities.DumpException(e));
                throw new Exception(message.ToString(), e);
            }
            bool hasProvider = false;
            bool hasConsumer = false;
            string ns = "";

            int lssID = 0;
            int lsID = 0;
            ProcessAgentInfo ls = null;
            ProcessAgentInfo lss = null;
            ProcessAgentInfo uss = null;
            LabClient labClient = null;
            GroupCredential credential = null;
            try
            {
                ResourceDescriptorFactory rFactory = ResourceDescriptorFactory.Instance();
                string jobGuid = registerGuid;
                message.AppendLine(" Register called at " + DateTime.UtcNow + " UTC \t registerGUID: " + registerGuid);
                ProcessAgent sourceAgent = brokerDB.GetProcessAgent(agentAuthHeader.agentGuid);
                message.AppendLine("Source Agent: " + sourceAgent.agentName);

                for (int i = 0; i < info.Length; i++)
                {

                    Coupon coupon = null;
                    if (info[i].coupon != null)
                    {
                        coupon = info[i].coupon;
                    }
                    if (info[i].serviceProviderInfo != null && info[i].serviceProviderInfo.Length > 0)
                    {
                        // ProviderInfo is simple add to database and create qualifier
                        if (!hasProvider)
                        {
                            message.AppendLine("Provider Info:");
                            hasProvider = true;
                        }
                        XmlQueryDoc xdoc = new XmlQueryDoc(info[i].serviceProviderInfo);
                        string descriptorType = xdoc.GetTopName();
                        if (descriptorType.Equals("processAgentDescriptor"))
                        {
                            string paGuid = xdoc.Query("/processAgentDescriptor/agentGuid");
                            string paType = xdoc.Query("/processAgentDescriptor/type");
                            if (paType.Equals(ProcessAgentType.LAB_SCHEDULING_SERVER))
                            {
                                lssID = brokerDB.GetProcessAgentID(paGuid);
                                if (lssID > 0)
                                {
                                    // Already in database
                                    //message.AppendLine("Reference to existing LSS: " + lssID + " GUID: " + paGuid);

                                }
                                else
                                {
                                    lss = rFactory.LoadProcessAgent(xdoc, ref message);
                                    lssID = lss.agentId;
                                }
                            }
                            else if (paType.Equals(ProcessAgentType.LAB_SERVER))
                            {
                                lsID = brokerDB.GetProcessAgentID(paGuid);
                                if (lsID > 0)
                                {
                                    // Already in database
                                    //message.AppendLine("Reference to existing LS: " + lsID + " GUID: " + paGuid);

                                }
                                else
                                {
                                    ls = rFactory.LoadProcessAgent(xdoc, ref message);
                                    lsID = ls.agentId;
                                }
                                int myLssID = brokerDB.FindProcessAgentIdForAgent(lsID, ProcessAgentType.LAB_SCHEDULING_SERVER);
                                if ((lssID > 0) && (myLssID <= 0) && (lssID != myLssID))
                                {
                                    brokerDB.AssociateLSS(lsID, lssID);
                                }
                            }
                        }
                        else if (descriptorType.Equals("clientDescriptor"))
                        {
                            int clientId = -1;
                            string clientGuid = xdoc.Query("/clientDescriptor/clientGuid");
                            clientId = AdministrativeAPI.GetLabClientID(clientGuid);
                            if (clientId > 0)
                            {
                                // Already in database
                                message.Append(" Attempt to Register a LabClient that is already in the database. ");
                                message.AppendLine(" GUID: " + clientGuid);
                            }
                            else
                            {
                                // LabServer should already be in the Database, once multiple LS supported may need work
                                // LS is specified in clientDescriptor
                                int clientID = rFactory.LoadLabClient(xdoc, ref message);
                                message.AppendLine("Adding LabClient: GUID " + clientGuid);
                            }
                        }
                        else if (descriptorType.Equals("systemSupport"))
                        {
                            // Already handled in base.register

                        }
                        // Add Relationships: LSS, LS Client
                    } // end of ServiceProvider
                    if (info[i].consumerInfo != null && info[i].consumerInfo.Length > 0)
                    {
                          // requestSystemSupport Handled by base register & there is no xml dcument
                        if (info[i].consumerInfo.CompareTo("requestSystemSupport") != 0)
                        {
                            message.AppendLine("Consumer Info: " + info[i].consumerInfo);
                            //if (!hasConsumer)
                            //    message.AppendLine("Consumer Info: " + info[i].consumerInfo);
                            hasConsumer = true;
                            XmlQueryDoc xdoc = new XmlQueryDoc(info[i].consumerInfo);
                            string descriptorType = xdoc.GetTopName();
                            if (descriptorType.Equals("processAgentDescriptor"))
                            {
                                string paGuid = xdoc.Query("/processAgentDescriptor/agentGuid");
                                ProcessAgentInfo paInfo = brokerDB.GetProcessAgentInfo(paGuid);
                                if (paInfo == null)
                                {
                                    // Not in database
                                    paInfo = rFactory.LoadProcessAgent(xdoc, ref message);
                                    message.Append("Loaded new ");
                                }
                                else
                                {
                                    message.Append("Reference to existing ");
                                    if (paInfo.retired)
                                    {
                                        throw new Exception("The ProcessAgent is retired");
                                    }
                                }

                                if (paInfo.agentType == ProcessAgentType.AgentType.LAB_SCHEDULING_SERVER)
                                {
                                    lss = paInfo;
                                    message.AppendLine("LSS: " + paGuid);
                                }
                                else if (paInfo.agentType == ProcessAgentType.AgentType.LAB_SERVER)
                                {
                                    ls = paInfo;
                                    message.AppendLine("LS: " + paGuid);
                                }
                                else if (paInfo.agentType == ProcessAgentType.AgentType.SCHEDULING_SERVER)
                                {
                                    uss = paInfo;
                                    message.AppendLine("USS: " + paGuid);
                                    if (lss != null)
                                    {
                                        if (lss.domainGuid.Equals(ProcessAgentDB.ServiceGuid))
                                        {
                                            message.AppendLine("Registering USSinfo on LSS: " + lss.agentName);
                                            LabSchedulingProxy lssProxy = new LabSchedulingProxy();
                                            lssProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                                            lssProxy.AgentAuthHeaderValue.coupon = lss.identOut;
                                            lssProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                                            lssProxy.Url = lss.webServiceUrl;
                                            lssProxy.AddUSSInfo(uss.agentGuid, uss.agentName, uss.webServiceUrl, coupon);
                                        }
                                        else
                                        {
                                            message.AppendLine("LSS is not from this domain");
                                        }
                                    }
                                }

                            }
                            else if (descriptorType.Equals("clientDescriptor"))
                            {
                                int newClientId = -1;
                                string clientGuid = xdoc.Query("/clientDescriptor/clientGuid");
                                int clientId = AdministrativeAPI.GetLabClientID(clientGuid);
                                if (clientId > 0)
                                {
                                    // Already in database
                                    message.Append(" Attempt to Register a LabClient that is already in the database. ");
                                    message.AppendLine(" GUID: " + clientGuid);
                                }
                                else
                                {
                                    clientId = rFactory.LoadLabClient(xdoc, ref message);
                                    message.AppendLine("Adding Lab Client GUID: " + clientGuid);
                                }
                            }
                            else if (descriptorType.Equals("credentialDescriptor"))
                            {
                                credential = rFactory.ParseCredential(xdoc, ref message);
                                if (lss != null)
                                {
                                    if (lss.domainGuid.Equals(ProcessAgentDB.ServiceGuid))
                                    {
                                        message.AppendLine("Registering Group Credentials on LSS: " + lss.agentName);
                                        message.AppendLine("Group:  " + credential.groupName + " DomainServer: " + credential.domainServerName);
                                        LabSchedulingProxy lssProxy = new LabSchedulingProxy();
                                        lssProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                                        lssProxy.AgentAuthHeaderValue.coupon = lss.identOut;
                                        lssProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                                        lssProxy.Url = lss.webServiceUrl;
                                        lssProxy.AddCredentialSet(credential.domainGuid, credential.domainServerName, credential.groupName, credential.ussGuid);
                                    }
                                    else
                                    {
                                        message.AppendLine("LSS is not from this domain");
                                    }
                                }
                            }
                        }
                    }
                } // End of info loop
            } // End of Try
            catch (Exception ex)
            {
                message.Append("Exception in Register: " + Utilities.DumpException(ex));

                throw new Exception(message.ToString(),ex);
            }
            finally
            {
                // Send a mail Message
                StringBuilder sb = new StringBuilder();

                MailMessage mail = new MailMessage();
                mail.To = ConfigurationManager.AppSettings["supportMailAddress"];
                //mail.To = "*****@*****.**";
                mail.From = ConfigurationManager.AppSettings["genericFromMailAddress"];
                mail.Subject = "Register called on " + ProcessAgentDB.ServiceAgent.agentName;
                mail.Body = message.ToString();
                SmtpMail.SmtpServer = "127.0.0.1";

                try
                {
                    SmtpMail.Send(mail);
                }
                catch (Exception ex)
                {
                    // Report detailed SMTP Errors
                    StringBuilder smtpErrorMsg = new StringBuilder();
                    smtpErrorMsg.Append("Exception: " + ex.Message);
                    //check the InnerException
                    if (ex.InnerException != null)
                        smtpErrorMsg.Append("<br>Inner Exceptions:");
                    while (ex.InnerException != null)
                    {
                        smtpErrorMsg.Append("<br>" + ex.InnerException.Message);
                        ex = ex.InnerException;
                    }
                    Logger.WriteLine(smtpErrorMsg.ToString());
                }
            }
        }
    /// <summary>
    /// Method that does the actual make reservation for the user. 
    /// makes the basis of the parameters from the message and the application database
    /// </summary>
    /// <param name="userName"> the user who is scheduling for the lab; must be registered with the service broker</param>
    /// <param name="groupName">the group name authorized to do a lab</param>
    /// <param name="labServerGuid">lab server which holds the lab that does the actual scheduling</param>
    /// <param name="clientGuid">Guid of the lab being registered for</param>
    /// <param name="start">Start time of a particular period scheduled for</param>
    /// <param name="end">End time of a particular period being scheduled for</param>
    /// <returns>returns a message string that the application bases on for to give the feedback to the user</returns>
    public static string MakeReservation(string userName, string groupName, string labServerGuid,
        string clientGuid, DateTime start, DateTime end)
    {
        string lsGuid = null;
            int status = -1;
            string message = null;
            if (ProcessAgentDB.ServiceAgent != null && ProcessAgentDB.ServiceAgent.domainGuid != null)
            {
                ProcessAgentDB paDb = new ProcessAgentDB();
                ProcessAgentInfo domainServer = paDb.GetProcessAgentInfo(ProcessAgentDB.ServiceAgent.domainGuid);

                InteractiveSBProxy isbProxy = new InteractiveSBProxy();
                isbProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                isbProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                isbProxy.AgentAuthHeaderValue.coupon = domainServer.identOut;
                isbProxy.Url = domainServer.ServiceUrl;

                string[] types = new string[] { TicketTypes.SCHEDULE_SESSION };

                Coupon opCoupon = isbProxy.RequestAuthorization(types, 600, 			userName, groupName,  labServerGuid, clientGuid);
                if (opCoupon != null)
                {
                    TicketIssuerProxy ticketProxy = new TicketIssuerProxy();
                    ticketProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                    ticketProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                    ticketProxy.AgentAuthHeaderValue.coupon = domainServer.identOut;
                    ticketProxy.Url = domainServer.ServiceUrl;
                    //the method call below is one which does not returns a null value
                    //in otherwards the ticket value is not created.
                    Ticket ticketSMS = ticketProxy.RedeemTicket(opCoupon, TicketTypes.SCHEDULE_SESSION, ProcessAgentDB.ServiceGuid);
                    if (ticketSMS != null)
                    {
                        if (ticketSMS.payload != null || ticketSMS.payload.Length > 0)
                        {
                            XmlQueryDoc xdoc = new XmlQueryDoc(ticketSMS.payload);
                            string ussURL = xdoc.Query("ScheduleSessionPayload/ussURL");
                            UserSchedulingProxy ussProxy = new UserSchedulingProxy();
                            ussProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                            ussProxy.OperationAuthHeaderValue.coupon = opCoupon;
                            ussProxy.Url = ussURL;

                            TimePeriod[] times = ussProxy.RetrieveAvailableTimePeriods(ProcessAgentDB.ServiceAgent.domainGuid, groupName, labServerGuid,
                                clientGuid, start, end);
                            // Logic to check for final time
                            DateTime resStart = start;
                            DateTime resEnd = end;

                            message = ussProxy.AddReservation(ProcessAgentDB.ServiceAgent.domainGuid, userName, groupName, labServerGuid, clientGuid, resStart, resEnd);
                        }
                    }
                }
                else
                {
                    message = "coupon is null";
                }
            }
            else
            {
                message = "This service is not part of a domain, please contact the administrator!";

            }
            return message;
    }
        public IntTag LaunchLabClient(string clientGuid, string groupName,
            string userName, string authorityKey, DateTime start, long duration)
        {
            IntTag result = new IntTag(-1, "");
            StringBuilder buf = new StringBuilder("LaunchClient Called: ");
            int userID = -1;
            int clientID = -1;
            int groupID = -1;
            Authority authority = null;
            try
            {
                Ticket clientAuthTicket = null;

                // Need to check opHeader
                if (opHeader != null && opHeader.coupon != null)
                {
                    buf.AppendLine("found opHeader");
                    authority = brokerDB.AuthorityRetrieve(authorityKey);
                    if (authority != null)
                        buf.AppendLine("authority: " + authority.authName);
                    // Coupon is from the client SCORM
                    clientAuthTicket = brokerDB.RetrieveIssuedTicket(opHeader.coupon,
                        TicketTypes.AUTHORIZE_CLIENT, ProcessAgentDB.ServiceGuid);
                    if (authority == null || clientAuthTicket == null)
                    {
                         result.tag = buf.ToString();
                        return result;
                    }
                    if (!clientAuthTicket.IsExpired() && !clientAuthTicket.isCancelled)
                    {
                        XmlQueryDoc xDoc = new XmlQueryDoc(clientAuthTicket.payload);
                        string cGuid = xDoc.Query("AuthorizeClientPayload/clientGuid");
                        string gName = xDoc.Query("AuthorizeClientPayload/groupName");
                        buf.AppendLine("AuthGroup: " + gName);
                        if ((cGuid.CompareTo(clientGuid) == 0) && (gName.CompareTo(groupName) == 0))
                        {
                            userID = AdministrativeAPI.GetUserID(userName, authority.authorityID);
                            if (userID <= 0)
                            { //User does not exist
                                buf.AppendLine("user: "******" doesnot exist");
                                //Check if Authority has a default group
                                if (authority.defaultGroupID > 0)
                                {
                                    //Should try & Query Authority for more information
                                    string firstName = null;
                                    string lastName = null;
                                    string email = null;
                                    string reason = null;
                                    userID = AdministrativeAPI.AddUser(userName, authority.authorityID, authority.authTypeID,
                                        firstName, lastName, email, authority.authName, reason, null, authority.defaultGroupID, false);
                                }
                            }
                            if (userID > 0)
                            {
                                buf.AppendLine("found userID: " + userID);
                                if (cGuid != null && clientGuid != null && cGuid.Length > 0 && (cGuid.CompareTo(clientGuid) == 0))
                                {
                                    clientID = AdministrativeAPI.GetLabClientID(clientGuid);
                                    buf.AppendLine("ClientID: " +clientID);
                                }
                                else
                                {
                                    result.tag = buf.ToString();
                                    return result;
                                }
                                if (gName != null && groupName != null && gName.Length > 0 && (gName.CompareTo(groupName) == 0))
                                {
                                    groupID = AdministrativeAPI.GetGroupID(groupName);
                                     buf.AppendLine("GroupID "+ groupID);
                                }
                                else
                                {
                                     result.tag = buf.ToString();
                                    return result;
                                }
                            }
                            else
                            { result.tag = buf.ToString();
                                return result;
                            }

                            if (userID > 0 && clientID > 0 && groupID > 0)
                            {

                                //Check for group access & User
                                //THis is the planned future need to deal with Session varables before it works
                                //result = brokerDB.ResolveAction(Context, clientID, userID, groupID, DateTime.UtcNow, duration, autoStart > 0);

                                Coupon coupon = brokerDB.CreateCoupon();
                                string ss = Utilities.RandomStr(10000);
                                TicketLoadFactory tlc = TicketLoadFactory.Instance();
                                string payload = tlc.createLaunchClientPayload(clientGuid, null, groupName, authority.authGuid, userID, userName, coupon.passkey, ss);
                                Ticket tt = brokerDB.AddTicket(coupon, TicketTypes.LAUNCH_CLIENT, ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, 600L, payload);
                                StringBuilder urlbuf = new StringBuilder();
                                urlbuf.Append(ProcessAgentDB.ServiceAgent.codeBaseUrl);
                                urlbuf.Append("/LaunchClient.aspx?cid=" + coupon.couponId);
                                urlbuf.Append("&ss=" + ss);
                                result.id = 1;
                                result.tag = urlbuf.ToString();

                             }
                        }
                    }
                }

            }
            catch (Exception e)
            {
                result.id = -1;
                result.tag = buf.ToString() + e.Message;
            }
            Context.Response.AddHeader("Access-Control-Allow-Origin", authority.Origin);
            return result;
        }
        /// <summary>
        /// Loads a new ProcessAgent into the database, without any Ident coupons, creates Qualifier.
        /// </summary>
        /// <param name="xdoc"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public ProcessAgentInfo LoadProcessAgent(XmlQueryDoc xdoc, ref StringBuilder message)
        {
            ProcessAgent pa = new ProcessAgent();
            pa.agentGuid = xdoc.Query("/processAgentDescriptor/agentGuid");
            pa.type = xdoc.Query("/processAgentDescriptor/type");
            pa.agentName = xdoc.Query("/processAgentDescriptor/agentName");
            pa.domainGuid = xdoc.Query("/processAgentDescriptor/domainGuid");
            pa.codeBaseUrl = xdoc.Query("/processAgentDescriptor/codeBaseUrl");
            pa.webServiceUrl = xdoc.Query("/processAgentDescriptor/webServiceUrl");
            int newID = brokerDb.InsertProcessAgent(pa, null, null);

            SystemSupport systemSupport = new SystemSupport();
            systemSupport.agentGuid = xdoc.Query("/processAgentDescriptor/systemSupport/agentGuid");
            systemSupport.bugEmail = xdoc.Query("/processAgentDescriptor/systemSupport/bugEmail");
            systemSupport.contactEmail = xdoc.Query("/processAgentDescriptor/systemSupport/contactEmail");
            systemSupport.infoUrl = xdoc.Query("/processAgentDescriptor/systemSupport/infoUrl");
            systemSupport.description = xdoc.Query("/processAgentDescriptor/systemSupport/desciption");
            systemSupport.location = xdoc.Query("/processAgentDescriptor/systemSupport/loction");
            if (systemSupport != null && systemSupport.agentGuid.CompareTo(pa.agentGuid) == 0)
            {
                brokerDb.SaveSystemSupport(systemSupport.agentGuid, systemSupport.contactEmail, systemSupport.bugEmail,
                    systemSupport.infoUrl, systemSupport.description, systemSupport.location);
            }

            // deal with resources later, need to decode resource Names
            XPathNodeIterator pathIter = xdoc.Select("/processAgentDescriptor/resources/*");
            if (pathIter != null && pathIter.Count > 0)
            {
                while (pathIter.MoveNext())
                {
                    string key = pathIter.Current.GetAttribute("key", ns);
                    string value = pathIter.Current.GetAttribute("value", ns);
                    // Create ResourceMapping
                    ResourceMappingKey mapKey = new ResourceMappingKey(ResourceMappingTypes.PROCESS_AGENT, newID);

                    // create values
                    ResourceMappingValue[] values = new ResourceMappingValue[2];
                    values[0] = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, key);
                    values[1] = new ResourceMappingValue(ResourceMappingTypes.STRING, value);
                    ResourceMapping newMapping = brokerDb.AddResourceMapping(mapKey, values);
                }
            }
            message.AppendLine("Registered a new " + pa.type + ": " + newID + ": "
                    + pa.agentName + " -> " + pa.codeBaseUrl);
            //Add Qualifiers
            if (pa.type.Equals(ProcessAgentType.LAB_SCHEDULING_SERVER))
            {
                int lssQualID = AuthorizationAPI.AddQualifier(newID, Qualifier.labSchedulingQualifierTypeID,
                    pa.agentName, Qualifier.ROOT);

            }
            else if (pa.type.Equals(ProcessAgentType.LAB_SERVER))
            {
                int lsQualID = AuthorizationAPI.AddQualifier(newID, Qualifier.labServerQualifierTypeID, pa.agentName, Qualifier.ROOT);
                string lssGuid = xdoc.Query("/processAgentDescriptor/lssGuid");
                if (lssGuid != null && lssGuid.Length > 0)
                {
                    int lssForLsId = brokerDb.GetProcessAgentID(lssGuid);
                    if (lssForLsId > 0)
                    {
                        brokerDb.AssociateLSS(newID, lssForLsId);
                    }
                }
            }
            return brokerDb.GetProcessAgentInfo(pa.agentGuid);
        }
        /// <summary>
        /// Parses the appInfo and experiment ticket, inserts the task into the database, 
        /// but does not create the DataManager.
        /// </summary>
        /// <param name="appInfo"></param>
        /// <param name="expTicket"></param>
        /// <returns></returns>
        public virtual LabTask CreateLabTask(LabAppInfo appInfo, Ticket expTicket)
        {
            // set defaults
            DateTime startTime = DateTime.UtcNow;
            long experimentID = 0;

            string statusName = null;
            string statusTemplate = null;
            string templatePath = null;

            string qualName = null;
            string fullName = null;  // set defaults
            long duration = -1L;

            LabTask labTask = null;

            LabDB dbManager = new LabDB();

            ////Parse experiment payload, only get what is needed
            string payload = expTicket.payload;
            XmlQueryDoc expDoc = new XmlQueryDoc(payload);
            string essService = expDoc.Query("ExecuteExperimentPayload/essWebAddress");
            string startStr = expDoc.Query("ExecuteExperimentPayload/startExecution");
            string durationStr = expDoc.Query("ExecuteExperimentPayload/duration");
            string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
            string userName = expDoc.Query("ExecuteExperimentPayload/userName");
            string expIDstr = expDoc.Query("ExecuteExperimentPayload/experimentID");

            if ((startStr != null) && (startStr.Length > 0))
            {
                startTime = DateUtil.ParseUtc(startStr);
            }
            if ((durationStr != null) && (durationStr.Length > 0) && !(durationStr.CompareTo("-1") == 0))
            {
                duration = Convert.ToInt64(durationStr);
            }
            if ((expIDstr != null) && (expIDstr.Length > 0))
            {
                experimentID = Convert.ToInt64(expIDstr);
            }

            if (appInfo.extraInfo != null && appInfo.extraInfo.Length > 0)
            {
                // Note should have either statusVI or template pair
                // Add Option for VNCserver access
                try
                {
                    XmlQueryDoc viDoc = new XmlQueryDoc(appInfo.extraInfo);
                    statusName = viDoc.Query("extra/status");
                    statusTemplate = viDoc.Query("extra/statusTemplate");
                    templatePath = viDoc.Query("extra/templatePath");
                }
                catch (Exception e)
                {
                    string err = e.Message;
                }
            }

            // log the experiment for debugging

            Logger.WriteLine("Experiment: " + experimentID + " Start: " + DateUtil.ToUtcString(startTime) + " \tduration: " + duration);
            long statusSpan = DateUtil.SecondsRemaining(startTime, duration);
            //launchClient(experimentID, essService, appInfo);

            //factory constructs the correct LabTask object Type
            labTask = CreateLabTask();

            labTask.labAppID = appInfo.appID;
            labTask.experimentID = experimentID;
            labTask.groupName = groupName;
            labTask.startTime = startTime;
            if (duration > 0)
                labTask.endTime =  startTime.AddTicks(duration * TimeSpan.TicksPerSecond);
            else
                labTask.endTime = DateTime.MinValue;
            labTask.couponID = expTicket.couponId;
            labTask.issuerGUID = expTicket.issuerGuid;
            labTask.storage = essService;
            labTask.data = labTask.constructTaskXml(appInfo.appID, fullName, appInfo.rev, statusName, essService);
            // Create  & store the labTask in database and return an LabTask object;
            long taskID = dbManager.InsertTaskLong(labTask);
            labTask.taskID = taskID;
            return labTask;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            StringBuilder buf;
            long couponID = -1L;
            int userID = -1;
            int groupID = -1;
            int clientID = -1;
            int labServerID = -1;
            int userTZ = 0;

            string clientGuid = null;
            string serverGuid = null;
            string groupName = null;
            string userName = null;
            string authKey = null;
            string startStr = null;
            string durStr = null;
            Coupon initCoupon = null;
            LabClient client = null;

            BrokerDB brokerDB = new BrokerDB();
            buf = new StringBuilder();

            string cidStr = Request.QueryString["cid"];
            string authStr = Request.QueryString["ss"];

            if (!String.IsNullOrEmpty(cidStr))
            {
                string test =hdnUserTZ.Value;
                couponID = Int64.Parse(cidStr);
                initCoupon = brokerDB.GetIssuedCoupon(couponID);
                if (initCoupon != null)
                {
                    Ticket launchTicket = brokerDB.RetrieveIssuedTicket(initCoupon, TicketTypes.LAUNCH_CLIENT, ProcessAgentDB.ServiceGuid);
                    if (launchTicket != null && !launchTicket.isCancelled && !launchTicket.IsExpired())
                    {
                        XmlQueryDoc xDoc = new XmlQueryDoc(launchTicket.payload);

                        //Check that the coupon matches the passcode in the ticket payload
                        string passChk = xDoc.Query("LaunchClient/passcode");
                        string ssChk = xDoc.Query("LaunchClient/ss");
                        if (String.IsNullOrEmpty(passChk) || passChk.CompareTo(initCoupon.passkey) != 0)
                        {
                            buf.AppendLine("Passkey Error");
                            processError(buf);
                        }
                        if (String.IsNullOrEmpty(ssChk) || passChk.CompareTo(authStr) != 0)
                        {
                            buf.AppendLine("ss_key Error");
                            processError(buf);
                        }
                        clientGuid = xDoc.Query("LaunchClient/clientGuid");
                        serverGuid = xDoc.Query("LaunchClient/serverGuid");
                        groupName = xDoc.Query("LaunchClient/groupName");
                        authKey = xDoc.Query("LaunchClient/authorityKey");
                        string userIdStr = xDoc.Query("LaunchClient/userId");
                        userName = xDoc.Query("LaunchClient/userName");
                        if (String.IsNullOrEmpty(authKey))
                        {
                            buf.AppendLine("authority Error");
                            processError(buf);
                        }
                        if (!String.IsNullOrEmpty(userIdStr))
                        {
                            userID = Int32.Parse(userIdStr);
                            if (userID <= 0)
                            {
                                buf.AppendLine("userID invalid value");
                                processError(buf);
                            }
                        }
                        else
                        {
                            buf.AppendLine("userID not specified");
                            processError(buf);
                        }
                        if (!String.IsNullOrEmpty(groupName))
                        {
                            groupID = AdministrativeAPI.GetGroupID(groupName);
                            if (groupID <= 0)
                            {
                                buf.AppendLine("groupName invalid value");
                                processError(buf);
                            }
                        }
                        else
                        {
                            buf.AppendLine("groupName not specified");
                            processError(buf);
                        }
                        startStr = xDoc.Query("LaunchClient/start");
                        durStr = xDoc.Query("LaunchClient/duration");

                        if (!String.IsNullOrEmpty(clientGuid))
                        {
                            clientID = AdministrativeAPI.GetLabClientID(clientGuid);
                            if (clientID > 0)
                            {
                                // do the real work
                                IntTag results = brokerDB.ProcessLaunchClientRequest(initCoupon, clientID, labServerID, groupID, userID, userTZ);

                                // Checks for different status values
                                //TODO Check for Scheduling redirect -- May be checked before we get here
                                if (results.id > -1)
                                {
                                   long sessionID = AdministrativeAPI.InsertUserSession(userID, groupID, clientID, userTZ, Session.SessionID);
                                    //add Session cookie
                                    HttpCookie cookie = new HttpCookie(ConfigurationManager.AppSettings["isbAuthCookieName"], sessionID.ToString());
                                    Response.AppendCookie(cookie);
                                    Response.AddHeader("Access-Control-Allow-Origin", "*");
                                    if ((results.id & LabClient.APPLET_BIT) == LabClient.APPLET_BIT)
                                    {
                                        Session["LoaderScript"] = results.tag;
                                        Response.Redirect("applet2.aspx", true);
                                    }
                                    else if ((results.id & LabClient.REDIRECT_BIT) == LabClient.REDIRECT_BIT)
                                    {
                                        string url = results.tag;
                                        Response.Redirect(url, true);
                                    }
                                    else
                                    {
                                        buf.AppendLine("Client type not supported");
                                    }
                                }
                                else
                                {
                                    buf.AppendLine("Client not found");
                                }
                            }
                            else
                            {
                                buf.AppendLine("client not specified");
                                processError(buf);
                            }

                        }
                    }
                    else
                    {
                        buf.AppendLine("Ticket Error");
                    }
                }
            }
            else
            {
                buf.AppendLine("Missing cid");
            }
            // If the code above does not complete fall through to processError()
            processError(buf);
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            LabDB dbManager = new LabDB();
            int appID = 0;
            long expID = 0;
            LabTask task = null;

            // Query values from the request

            string appKey = Request.QueryString["app"];
            string coupon_Id = Request.QueryString["coupon_id"];
            string passkey = Request.QueryString["passkey"];
            string issuerGUID = Request.QueryString["issuer_guid"];
            string returnTarget = Request.QueryString["sb_url"];

            if ((returnTarget != null) && (returnTarget.Length > 0))
                Session["returnURL"] = returnTarget;

               Logger.WriteLine("LVPortal: " + Request.Url.ToString());

            // this should be the Experiment Coupon data
            if (!(passkey != null && passkey != "" && coupon_Id != null && coupon_Id != "" && issuerGUID != null && issuerGUID != ""))
            {
               Logger.WriteLine("LVPortal: " + "AccessDenied missing Experiment credentials");
                Response.Redirect("AccessDenied.aspx?text=missing+Experiment+credentials.", true);
            }

            long expCoupId = Convert.ToInt64(coupon_Id);
            Coupon expCoupon = new Coupon(issuerGUID, expCoupId, passkey);

            //Check the database for ticket and coupon, if not found Redeem Ticket from
            // issuer and store in database.
            //This ticket should include group, experiment id and be valid for this moment in time??
            Ticket expTicket = dbManager.RetrieveAndVerify(expCoupon, TicketTypes.EXECUTE_EXPERIMENT);

            if (expTicket != null)
            {
                if (expTicket.IsExpired())
                {
                    Response.Redirect("AccessDenied.aspx?text=The ExperimentExecution+ticket+has+expired.", true);

                }

                ////Parse experiment payload, only get what is needed
                string payload = expTicket.payload;
                XmlQueryDoc expDoc = new XmlQueryDoc(payload);
                string tzStr = expDoc.Query("ExecuteExperimentPayload/userTZ");
                if ((tzStr != null) && (tzStr.Length > 0))
                    Session["userTZ"] = tzStr;
                string groupName = expDoc.Query("ExecuteExperimentPayload/groupName");
                Session["groupName"] = groupName;
                string sbStr = expDoc.Query("ExecuteExperimentPayload/sbGuid");
                Session["brokerGUID"] = sbStr;

                //Get Lab specific info for this URL or group
                LabAppInfo appInfo = null;
                // Experiment is specified by 'app=appKey'
                if (appKey != null && appKey.Length > 0)
                {
                    appInfo = dbManager.GetLabApp(appKey);
                }
                else // Have to use groupName & Servicebroker THIS REQUIRES groups & permissions are set in database
                {    // This is no longer the case as the USS handles groups and permissions
                    appInfo = dbManager.GetLabAppForGroup(groupName, sbStr);
                }
                if (appInfo == null)
                {
                    Response.Redirect("AccessDenied.aspx?text=Unable+to+find+application+information,+please+notify+your+administrator.", true);
                }

                // Use taskFactory to create a new task, return an existing reentrant task or null if there is an error
                LabViewTaskFactory factory = new LabViewTaskFactory();
                task = factory.CreateLabTask(appInfo, expCoupon, expTicket);

                if (task != null)
                {

                    //Useful for debugging overloads the use of a field in the banner
                    //Session["GroupName"] = "TaskID: " + task.taskID.ToString();

                    //Utilities.WriteLog("TaskXML: " + task.taskID + " \t" + task.data);

                    //Construct the information to be passed to the target page
                    TimeSpan taskDur = task.endTime - task.startTime;
                    string vipayload = task.constructSessionPayload(appInfo,
                        task.startTime, taskDur.Ticks / TimeSpan.TicksPerSecond, task.taskID,
                        returnTarget, null, null);

                    //Utilities.WriteLog("sessionPayload: " + payload);
                    //Store Session information
                    Session["payload"] = vipayload;
                    if (appInfo.rev != null && appInfo.rev.Length > 0)
                    {
                        Session["lvversion"] = appInfo.rev;
                    }
                    else
                    {
                        Session.Remove("lvversion");
                    }

                    //redirect to Presentation page...
                    Response.Redirect(appInfo.page, true);
                }
                else
                {
                    Response.Redirect("AccessDenied.aspx?text=Unable+to+launch++application,+please+notify+your+administrator.", true);
                }

            }
        }
        public IntTag LaunchLabClient(Coupon coupon, string clientGuid, string groupName,
            string userName, string authorityUrl, long duration, int autoStart)
        {
            IntTag result = new IntTag(-1, "Access Denied");
                    StringBuilder buf = new StringBuilder();
                    int userID = -1;
                    int clientID = -1;
                    int groupID = -1;

                    try
                    {
                        Ticket clientAuthTicket = null;
                        Authority authority = null;
                        // Need to check opHeader
                        if (coupon != null)
                        {

                            authority = AuthorityRetrieveByUrl(authorityUrl);
                            // Coupon is from the client SCORM
                            clientAuthTicket = RetrieveIssuedTicket(coupon, TicketTypes.AUTHORIZE_CLIENT, ProcessAgentDB.ServiceGuid);
                            if (authority == null || clientAuthTicket == null)
                            {
                                return result;
                            }
                            if (!clientAuthTicket.IsExpired() && !clientAuthTicket.isCancelled)
                            {
                                XmlQueryDoc xDoc = new XmlQueryDoc(clientAuthTicket.payload);
                                string cGuid = xDoc.Query("AuthorizeClientPayload/clientGuid");
                                string gName = xDoc.Query("AuthorizeClientPayload/groupName");
                                if ((cGuid.CompareTo(clientGuid) == 0) && (gName.CompareTo(groupName) == 0))
                                {
                                    userID = AdministrativeAPI.GetUserID(userName, authority.authorityID);
                                    if (userID <= 0)
                                    { //User does not exist
                                        //Check if Authority has a default group
                                        if (authority.defaultGroupID > 0)
                                        {
                                            //Should try & Query Authority for more information
                                            string firstName = null;
                                            string lastName = null;
                                            string email = null;
                                            string reason = null;
                                            userID = AdministrativeAPI.AddUser(userName, authority.authorityID, authority.authTypeID,
                                                firstName, lastName, email, authority.authName, reason, null, authority.defaultGroupID, false);
                                        }
                                    }
                                    if (userID > 0)
                                    {
                                        if (cGuid != null && clientGuid != null && cGuid.Length > 0 && (cGuid.CompareTo(clientGuid) == 0))
                                        {
                                            clientID = AdministrativeAPI.GetLabClientID(clientGuid);
                                        }
                                        else
                                        {
                                            return result;
                                        }
                                        if (gName != null && groupName != null && gName.Length > 0 && (gName.CompareTo(groupName) == 0))
                                        {
                                            groupID = AdministrativeAPI.GetGroupID(groupName);
                                        }
                                        else
                                        {
                                            return result;
                                        }
                                    }
                                    else
                                    {
                                        return result;
                                    }

                                    if (userID > 0 && clientID > 0 && groupID > 0)
                                    {

                                        //Check for group access & User
                                        result = ResolveAction(clientID, userID, groupID, DateTime.UtcNow, duration, autoStart > 0);
                                        //http://your.machine.com/iLabServiceBroker/default.aspx?sso=t&amp;usr=USER_NAME&amp;key=USER_PASSWD&amp;cid=CLIENT_GUID&amp;grp=GROUP_NAME"
                                    }
                                }
                            }
                        }
                        //    Coupon coupon = brokerDB.CreateCoupon();
                        //    TicketLoadFactory tlc = TicketLoadFactory.Instance();
                        //    string payload = tlc.createAuthenticateAgentPayload(authorityGuid, clientGuid, userName, groupName);
                        //    brokerDB.AddTicket(coupon, TicketTypes.AUTHENTICATE_AGENT, ProcessAgentDB.ServiceGuid, authorityGuid, 600L, payload);
                        //    buf.Append(ProcessAgentDB.ServiceAgent.codeBaseUrl);
                        //    buf.Append("/default.aspx?sso=t");
                        //    buf.Append("&usr="******"&cid=" + clientGuid);
                        //    buf.Append("&grp=" + groupName);
                        //    buf.Append("&auth=" + authorityUrl);
                        //    buf.Append("&key=" + coupon.passkey);
                        //    if (autoStart > 0)
                        //        buf.Append("&auto=t");

                        //    tag.id = 1;
                        //    tag.tag = buf.ToString();
                        //    //
                        //    //
                        //    //if (test.id > 0)
                        //    //{
                        //    //    string requestGuid = Utilities.MakeGuid("N");
                        //    //

                        //    //}
                        //    //else
                        //    //{
                        //    //    tag.tag = "Access Denied";
                        //    //}
                        //}

                    }
                    catch (Exception e)
                    {
                        result.id = -1;
                        result.tag = e.Message;
                    }
                    //context.Response.AddHeader("Access-Control-Allow-Origin", "*");
                    return result;
        }
        protected virtual void register(string registerGuid, ServiceDescription[] info)
        {
            StringBuilder message = new StringBuilder("Register called on " + ProcessAgentDB.ServiceAgent.codeBaseUrl);

            if (info != null && info.Length > 0)
            {
                foreach (ServiceDescription sd in info)
                {
                    Coupon coupon = null;
                    if (sd.coupon != null)
                    {
                        coupon = sd.coupon;
                    }
                    XmlQueryDoc xdoc = new XmlQueryDoc(sd.serviceProviderInfo);
                    string descriptorType = xdoc.GetTopName();
                    if (descriptorType.Equals("systemSupport"))
                    {
                        SystemSupport ss = SystemSupport.Parse(xdoc);
                        if (ss.agentGuid != null && ss.agentGuid.Length > 0)
                        {
                            int id = dbTicketing.GetProcessAgentID(ss.agentGuid);
                            if (id > 0)
                            {
                                dbTicketing.SaveSystemSupport(ss.agentGuid, ss.contactEmail, ss.bugEmail,
                                    ss.infoUrl, ss.description, ss.location);
                                if (sd.consumerInfo != null && sd.consumerInfo.CompareTo("requestSystemSupport") == 0)
                                {
                                    ProcessAgentInfo paInfo = dbTicketing.GetProcessAgentInfo(ss.agentGuid);
                                    if (paInfo != null)
                                    {
                                        SystemSupport mySS = dbTicketing.RetrieveSystemSupport(ProcessAgentDB.ServiceGuid);
                                        if (mySS != null)
                                        {
                                            ServiceDescription[] values = new ServiceDescription[1];
                                            values[0] = new ServiceDescription(mySS.ToXML(), null, null);
                                            ProcessAgentProxy proxy = new ProcessAgentProxy();
                                            proxy.Url = paInfo.webServiceUrl;
                                            proxy.AgentAuthHeaderValue = new AgentAuthHeader();
                                            proxy.AgentAuthHeaderValue.coupon = paInfo.identOut;
                                            proxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                                            proxy.Register(registerGuid, values);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }