Пример #1
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;
        }
        protected void goButton_Click(object sender, System.EventArgs e)
        {
            LabDB labDB = new LabDB();

            // Update Task data for graph page. Note XmlQueryDocs are read-only
            LabTask task = labDB.GetTask(Convert.ToInt64(hdnExpId.Value), Session["opIssuer"].ToString());
            if (task != null)
            {
                Coupon opCoupon = new Coupon(task.issuerGUID, task.couponID, Session["opPasscode"].ToString());
               ExperimentStorageProxy essProxy = new ExperimentStorageProxy();
               essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
               essProxy.OperationAuthHeaderValue.coupon = opCoupon;
               essProxy.Url = task.storage;
               essProxy.AddRecord(task.experimentID, "BEElab", "profile", false, hdnProfile.Value, null);
               essProxy.AddRecord(task.experimentID, "BEElab", "climateProfile", false, hdnClimateProfile.Value, null);
               essProxy.AddRecord(task.experimentID, "BEElab", "sunLamp", false, hdnSunLamp.Value, null);

               // send The CR1000 programs
               sendProfile(ConfigurationManager.AppSettings["climateController"],
                   hdnProfile.Value, hdnSunProfile, ConfigurationManager.AppSettings["climateServer"]);
               sendFile(ConfigurationManager.AppSettings["chamberController"],
                  ConfigurationManager.AppSettings["chamberFile"],
                  ConfigurationManager.AppSettings["chamberServer"]);
                StringBuilder buf = new StringBuilder("BEEgraph.aspx?expid=");

                sendEwsCientProfile(hdnClientProfile.Value,hdnExpLength.Value);
                buf.Append(task.experimentID);
                task.Status = LabTask.eStatus.Running;
                TaskProcessor.Instance.Modify(task);
                labDB.SetTaskStatus(task.taskID, (int) LabTask.eStatus.Running);
                Session["opCouponID"] = hdnCoupon.Value;
                Session["opIssuer"] = hdnIssuer.Value;
                Session["opPasscode"] = hdnPasscode.Value;
                Response.Redirect(buf.ToString(), true);
            }
            else
            {
                throw new Exception("Task was not found.");
            }
        }
 public DataSourceManager(LabTask task)
     : this()
 {
     taskID = task.taskID;
     experimentID = task.experimentID;
     if (task.storage != null && task.storage.Length > 0)
     {
         LabDB labDB = new LabDB();
         Coupon expCoupon = labDB.GetCoupon(task.couponID, task.issuerGUID);
         if (expCoupon != null)
         {
             essProxy = new ExperimentStorageProxy();
             essProxy.Url = task.storage;
             essProxy.OperationAuthHeaderValue = new OperationAuthHeader();
             essProxy.OperationAuthHeaderValue.coupon = expCoupon;
         }
         else
             throw new Exception("ExpCoupon not found");
     }
     else
      throw new Exception("ESS is not specified");
 }
Пример #4
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if(Session["userTZ"] != null)
                tz = Convert.ToInt32(Session["userTZ"]);
            String returnURL = (string)Session["sbUrl"];
            if ((returnURL != null) && (returnURL.Length > 0))
            {
                lnkBackSB.NavigateUrl = returnURL;
                lnkBackSB.Visible = true;
            }
            else{
                lnkBackSB.Visible = false;
            }
            if (Session["opCouponID"] != null && Session["opIssuer"] != null && Session["opPasscode"] != null)
            {
                opCoupon = new Coupon(Session["opIssuer"].ToString(), Convert.ToInt64(Session["opCouponID"].ToString()), Session["opPasscode"].ToString());

            }
            else
            {
                throw new AccessDeniedException("Missing credentials for BEE Lab graph.");
            }
            LabDB dbManager = new LabDB();
            if (!IsPostBack)
            {
                lblResponse.Text = "";
                lblResponse.Visible = false;
                // Query values from the request
                hdnExperimentID.Value = Request.QueryString["expid"];
                if (hdnExperimentID.Value != null && hdnExperimentID.Value.Length > 0)
                    hdnChannelID.Value = ChecksumUtil.ToMD5Hash("BEElab" + hdnExperimentID.Value);
                else
                    hdnChannelID.Value = "experiment-channel";

                if (Session["opCouponID"] != null && Session["opIssuer"] != null && Session["opPasscode"] != null)
                {
                    // Save the coupon data for when the session times out
                    ViewState["opCouponID"] = Session["opCouponID"].ToString();
                    ViewState["opIssuer"] = Session["opIssuer"].ToString();
                    ViewState["opPasscode"] = Session["opPasscode"].ToString();
                }

                InteractiveSBProxy sbProxy = new InteractiveSBProxy();
                ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(Session["opIssuer"].ToString());
                if (sbInfo != null)
                {
                    sbProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                    sbProxy.OperationAuthHeaderValue.coupon = opCoupon;
                    sbProxy.Url = sbInfo.webServiceUrl;

                    //Criterion[] search = new Criterion[] { new Criterion("experiment_ID", "=", hdnExperimentID.Value) };
                    //ExperimentSummary[] expInfo = sbProxy.RetrieveExperimentSummary(search);
                    //if (expInfo.Length > 0)
                    //{
                    //    theExperiment = expInfo[0];
                    //}
                    ExperimentRecord[] profileRecords = getRecords(sbProxy, Convert.ToInt64(hdnExperimentID.Value),
                      new Criterion[] { new Criterion("Record_Type", "=", "profile") });
                    ExperimentRecord[] records = getRecords(sbProxy,Convert.ToInt64(hdnExperimentID.Value),
                       new Criterion[] { new Criterion("Record_Type", "=", "data")});
                    if(hdnChannelID.Value != null)
                        writeChannelID(hdnChannelID.Value);
                    //processProfile(profileRecords);
                    processRecords(records);
                }
            }
        }
        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;
        }
        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;
                    }

                }
            }
        }
Пример #7
0
        protected void Application_Start(Object sender, EventArgs e)
        {
            try
            {
                string path = ConfigurationManager.AppSettings["logPath"];
                if (path != null && path.Length > 0)
                {
                    Logger.LogPath = path;
                    Logger.WriteLine("");
                    Logger.WriteLine("#############################################################################");
                    Logger.WriteLine(iLabGlobal.Release);
                    Logger.WriteLine("Application_Start: starting");
                }
                ProcessAgentDB.RefreshServiceAgent();
                //Should load any active tasks and update any expired tasks
                LabDB dbService = new LabDB();

                TaskProcessor.Instance.WaitTime = 60000;
                LabTask[] activeTasks = dbService.GetActiveTasks();
                int count = 0;
                foreach (LabTask task in activeTasks)
                {
                    if (task != null)
                    {
                        if (task.storage != null && task.storage.Length > 0)
                        {
                            Coupon expCoupon = dbService.GetCoupon(task.couponID, task.issuerGUID);
                            DataSourceManager dsManager = new DataSourceManager(task);
                            BeeAPI api = new BeeAPI();
                            FileWatcherDataSource fds = api.CreateBeeDataSource(expCoupon, task, "data", false);
                            dsManager.AddDataSource(fds);
                            fds.Start();
                            TaskProcessor.Instance.AddDataManager(task.taskID, dsManager);
                        }
                        TaskProcessor.Instance.Add(new BeeTask(task));
                        count++;
                    }
                }
                taskThread = new TaskHandler(TaskProcessor.Instance);
                ticketRemover = new TicketRemover();
                if (Logger.IsLogging)
                    Logger.WriteLine("Added " + count + " active Tasks\r\n");

            }
            catch (Exception err)
            {
                if (Logger.IsLogging)
                Logger.WriteLine(Utilities.DumpException(err));
            }
        }
Пример #8
0
        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);
                }

            }
        }
Пример #9
0
 protected void Application_Start(Object sender, EventArgs e)
 {
     string path = ConfigurationManager.AppSettings["logPath"];
     if (path != null && path.Length > 0)
     {
        Logger.LogPath = path;
        Logger.WriteLine("");
        Logger.WriteLine("#############################################################################");
        Logger.WriteLine(iLabGlobal.Release);
        Logger.WriteLine("Application_Start: starting");
     }
     ProcessAgentDB.RefreshServiceAgent();
     //Should load any active tasks and update any expired tasks
     LabDB dbService = new LabDB();
     LabTask[] activeTasks = dbService.GetActiveTasks();
     if (activeTasks != null && activeTasks.Length > 0)
     {
         foreach (LabTask task in activeTasks)
         {
             if(task != null)
                 TaskProcessor.Instance.Add(task);
         }
     }
     taskThread = new TaskHandler(TaskProcessor.Instance);
     ticketRemover = new TicketRemover();
 }
Пример #10
0
 protected void btnSaveAnnotation_Click(object sender, System.EventArgs e)
 {
     lblResponse.Visible=false;
     LabDB dbManager = new LabDB();
     try
     {
         InteractiveSBProxy sbProxy = new InteractiveSBProxy();
         ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(hdnIssuer.Value);
         if (sbInfo != null)
         {
             sbProxy.OperationAuthHeaderValue = new OperationAuthHeader();
             sbProxy.OperationAuthHeaderValue.coupon
                 = new Coupon(hdnIssuer.Value, Convert.ToInt64(hdnCoupon.Value), hdnPasscode.Value);
             sbProxy.Url = sbInfo.webServiceUrl;
             sbProxy.SetAnnotation(Int32.Parse(txtExperimentID.Text), txtAnnotation.Text);
             Criterion[] search = new Criterion[] { new Criterion("experiment_ID", "=", txtExperimentID.Text) };
             ExperimentSummary[] expInfo = sbProxy.RetrieveExperimentSummary(search);
             if (expInfo.Length > 0)
             {
                 displayExperimentSummary(expInfo[0]);
             }
             lblResponse.Text = Utilities.FormatConfirmationMessage("Annotation saved for experiment ID " + txtExperimentID.Text);
             lblResponse.Visible = true;
         }
     }
     catch (Exception ex)
     {
         lblResponse.Text = Utilities.FormatErrorMessage("Error saving experiment annotation. " + ex.Message);
         lblResponse.Visible = true;
     }
 }
Пример #11
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;
        }
Пример #12
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if(! IsPostBack)
            {
                //int[] lsIDs = AdministrativeAPI.ListLabServerIDs();
                LabDB service = new LabDB();
                LabAppInfo[] labs = service.GetLabApps();
                ddlWhichLab.Items.Add("System-wide error");

                String optList = ConfigurationManager.AppSettings["helpOptions"];
                if((optList != null)&& (optList.Length >0)){
                    char [] delimiter = {','};
                    String [] options =optList.Split(delimiter,100);
                    for(int i =0;i< options.Length;i++)
                    {
                        ddlWhichLab.Items.Add(new ListItem(options[i],"0"));
                    }
                    if(options.Length > 0)
                    {
                        ddlWhichLab.Items[0].Selected = false;
                    }
                }

                foreach (LabAppInfo p in labs)
                {
                    //if(l.labServerID >0)
                    ddlWhichLab.Items.Add(new ListItem(p.application,p.appID.ToString()));
                }

            }
        }
Пример #13
0
        public static BeeTask[] GetActiveTasks()
        {
            List<BeeTask> list = null;
            LabDB labDb = new LabDB();
            LabTask[] tasks = labDb.GetActiveTasks();
            if (tasks != null && tasks.Length > 0)
            {

                list = new List<BeeTask>();
                foreach (LabTask t in tasks)
                {
                    BeeTask bt = new BeeTask(t);
                    if (bt.Status == eStatus.Running)
                    {
                        //t.createDataSource(
                    }
                    list.Add(bt);
                }
            }
            return list.ToArray(); ;
        }
        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);
            }
        }
Пример #15
0
        protected void btnGo_Click(object sender, System.EventArgs e)
        {
            //clearExperimentDisplay();
            List<Criterion> cList = new List<Criterion>();
            LabDB dbManager = new LabDB();
            LabAppInfo clientInfo = dbManager.GetLabApp(hdnAppkey.Value);
            if (clientInfo == null)
            {
                throw new Exception("Client does not exist!");
            }
            if( clientInfo.extraInfo != null &&  clientInfo.extraInfo.Length > 0)
                cList.Add(new Criterion("clientguid", "=", clientInfo.extraInfo));
            if((ddlTimeAttribute.SelectedIndex >0))
            {
                DateTime time1 = FactoryDB.MinDbDate;
                try
                {
                    time1 = DateUtil.ParseUserToUtc(txtTime1.Text,culture,Convert.ToInt32(Session["UserTZ"]));
                }
                catch
                {
                    lblResponse.Text = Utilities.FormatErrorMessage("Please enter a valid date & time in the first time field .");
                    lblResponse.Visible = true;
                    return;
                }
                if (ddlTimeAttribute.SelectedIndex == 1)
                {
                    cList.Add(new Criterion("CreationTime", ">=", time1.ToString()));
                    cList.Add(new Criterion("CreationTime", "<", time1.AddDays(1).ToString()));
                }
                else if (ddlTimeAttribute.SelectedIndex == 2)
                {
                    cList.Add(new Criterion("CreationTime", "<", time1.ToString()));
                }
                else if (ddlTimeAttribute.SelectedIndex == 3)
                {
                    cList.Add(new Criterion("CreationTime", ">=", time1.ToString()));
                }
                if (ddlTimeAttribute.SelectedIndex == 4)
                {
                    DateTime time2 = FactoryDB.MaxDbDate;
                    try
                    {
                        time2 = DateUtil.ParseUserToUtc(txtTime2.Text, culture, Convert.ToInt32(Session["UserTZ"]));
                    }
                    catch
                    {
                        lblResponse.Text = Utilities.FormatErrorMessage("Please enter a valid date & time in the second time field.");
                        lblResponse.Visible = true;
                        return;
                    }
                    cList.Add(new Criterion("CreationTime", ">=", time1.ToString()));
                    cList.Add(new Criterion("CreationTime", "<=", time2.ToString()));
                }
            }

            InteractiveSBProxy sbProxy = new InteractiveSBProxy();
            ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(hdnIssuer.Value);
            if (sbInfo != null)
            {
                sbProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                sbProxy.OperationAuthHeaderValue.coupon
                    = new Coupon(hdnIssuer.Value, Convert.ToInt64(hdnCoupon.Value), hdnPasscode.Value);
                sbProxy.Url = sbInfo.webServiceUrl;

                List<Criterion> cri = new List<Criterion>();
                cri.Add(new Criterion("clientguid", "=", clientInfo.extraInfo));
                ExperimentSummary[] expSum = sbProxy.RetrieveExperimentSummary(cri.ToArray());
                if (expSum.Length == 0)
                {
                    string msg = "No experiment records were found for user '" + Session["UserName"] + "' in group '" + Session["GroupName"] + "'.";
                    lblResponse.Text = Utilities.FormatErrorMessage(msg);
                    lblResponse.Visible = true;
                }
                listSummaries(expSum);

            }
        }
Пример #16
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            LabDB dbManager = new LabDB();
            if (!IsPostBack)
            {
                // Query values from the request
                //clearSessionInfo();
                hdnAppkey.Value = Request.QueryString["app"];
                hdnCoupon.Value = Request.QueryString["coupon_id"];
                hdnPasscode.Value = Request.QueryString["passkey"];
                hdnIssuer.Value = Request.QueryString["issuer_guid"];
                hdnSbUrl.Value = Request.QueryString["sb_url"];
                if (hdnSbUrl.Value != null && hdnSbUrl.Value.Length > 0)
                    Session["sbUrl"] = hdnSbUrl.Value;
                else
                    Session.Remove("sbUrl");
                string userName = null;
                string userIdStr = null;

                int tz = 0;
                if (Session["userTZ"] != null)
                    tz = Convert.ToInt32(Session["userTZ"]);

                // this should be the RedeemSession & Experiment Coupon data
                if (!(hdnPasscode.Value != null && hdnPasscode.Value != ""
                    && hdnCoupon.Value != null && hdnCoupon.Value != ""
                    && hdnIssuer.Value != null && hdnIssuer.Value != ""))
                {
                    Logger.WriteLine("BEEanaylsis: " + "AccessDenied missing credentials");
                    Response.Redirect("AccessDenied.aspx?text=missing+credentials.", true);
                }

                Coupon expCoupon = new Coupon(hdnIssuer.Value, Convert.ToInt64(hdnCoupon.Value), hdnPasscode.Value);

                //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");
                    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;

                    if ((tzStr != null) && (tzStr.Length > 0))
                    {
                        Session["userTZ"] = tzStr;
                    }
                    LabAppInfo clientInfo = dbManager.GetLabApp(hdnAppkey.Value);
                    if (clientInfo == null)
                    {
                        throw new Exception("Client does not exist!");
                    }
                    long experimentID = Convert.ToInt64(expIdStr);
                    InteractiveSBProxy sbProxy = new InteractiveSBProxy();
                    ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(hdnIssuer.Value);
                    if (sbInfo != null)
                    {
                        sbProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                        sbProxy.OperationAuthHeaderValue.coupon = expCoupon;
                        sbProxy.Url = sbInfo.webServiceUrl;
                        // Use the extraInfo field to provide the target ClientGUID
                        List<Criterion> cri = new List<Criterion>();
                        if (clientInfo.extraInfo != null && clientInfo.extraInfo.Length > 0)
                            cri.Add(new Criterion("clientguid", "=", clientInfo.extraInfo));

                        ExperimentSummary[] expSum = sbProxy.RetrieveExperimentSummary(cri.ToArray());
                        listSummaries(expSum);
                    }
                }
            }
        }
Пример #17
0
        protected void lbxSelectExperiment_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            LabDB dbManager = new LabDB();
            //clearSessionInfo();
            //clearExperimentDisplay();
            long experimentID = Int64.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value);
            InteractiveSBProxy sbProxy = new InteractiveSBProxy();
            ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(hdnIssuer.Value);
            if (sbInfo != null)
            {
                sbProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                sbProxy.OperationAuthHeaderValue.coupon
                    = new Coupon(hdnIssuer.Value, Convert.ToInt64(hdnCoupon.Value), hdnPasscode.Value);
                sbProxy.Url = sbInfo.webServiceUrl;
                try
                {
                    //ExperimentSummary[] expInfo = wrapper.GetExperimentSummaryWrapper(new long[] { experimentID });
                    Criterion[] search = new Criterion[] { new Criterion("experiment_ID", "=", experimentID.ToString()) };
                    ExperimentSummary[] expInfo = sbProxy.RetrieveExperimentSummary(search);

                    if (expInfo[0] != null)
                    {
                        displayExperimentSummary(expInfo[0]);
                    }
                }
                catch (Exception ex)
                {
                    lblResponse.Text = Utilities.FormatErrorMessage("Error retrieving experiment information. " + ex.Message);
                    lblResponse.Visible = true;
                }
            }
        }
Пример #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            LabDB dbManager = new LabDB();
            if (Session["opCouponID"] != null && Session["opIssuer"] != null && Session["opPasscode"] != null)
            {
                opCoupon = new Coupon(Session["opIssuer"].ToString(),
                    Convert.ToInt64(Session["opCouponID"].ToString()),
                    Session["opPasscode"].ToString());
            }
            else
            {
                throw new AccessDeniedException("Missing credentials for BEE Lab graph.");
            }
            if (Request.QueryString["expid"] != null)
                experimentID = Convert.ToInt64(Request.QueryString["expid"]);
            if (Request.QueryString["min"] != null && Request.QueryString["min"].Length > 0)
                minRecord = Convert.ToInt32(Request.QueryString["min"]);
            if (Request.QueryString["max"] != null && Request.QueryString["max"].Length > 0)
                maxRecord = Convert.ToInt32(Request.QueryString["max"]) +1;
            if (Request.QueryString["index"] != null && Request.QueryString["index"].Length > 0)
                indices = Request.QueryString["index"];

            InteractiveSBProxy sbProxy = new InteractiveSBProxy();
            //ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(Session["opIssuer"].ToString());
            ProcessAgentInfo sbInfo = dbManager.GetProcessAgentInfo(ProcessAgentDB.ServiceAgent.domainGuid);
            if (sbInfo != null)
            {
                sbProxy.OperationAuthHeaderValue = new OperationAuthHeader();
                sbProxy.OperationAuthHeaderValue.coupon = opCoupon;
                sbProxy.Url = sbInfo.webServiceUrl;
                List<Criterion> criteria = new List<Criterion>();
                //criteria.Add(new Criterion("experiment_ID", "=", experimentID));
                criteria.Add(new Criterion("Record_Type", "=", "data"));
                if (minRecord > -1)
                    criteria.Add(new Criterion("sequence_no", ">=", minRecord.ToString()));
                if (maxRecord > -1)
                    criteria.Add(new Criterion("sequence_no", "<=", maxRecord.ToString()));
                //ExperimentSummary[] expInfo = sbProxy.RetrieveExperimentSummary(search);
                //if (expInfo.Length > 0)
                //{
                //    theExperiment = expInfo[0];
                //}
                //ExperimentRecord[] profileRecords = getRecords(sbProxy, Convert.ToInt64(hdnExperimentID.Value),
                //  new Criterion[] { new Criterion("Record_Type", "=", "profile") });
                ExperimentRecord[] records = getRecords(sbProxy, experimentID, criteria.ToArray());
                if (records != null)
                {
                    if (records.Length > 0)
                    {

                        //processProfile(profileRecords);
                        StringBuilder buf = processRecords(records, indices);
                        int bufLen = buf.Length * 2;
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
                        //Response.AddHeader("Content-Length",bufLen.ToString());
                        Response.ContentType = "application/octet-stream";
                        Response.Write(buf.ToString());
                        Response.Flush();
                    }
                }
            }
        }
Пример #19
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (Request.UserAgent.Contains("MSIE 6") || Request.UserAgent.Contains("MSIE 7"))
            {
                recaptcha.EmbedJavascript = true;
            }
            if(! IsPostBack)
            {
                //int[] lsIDs = AdministrativeAPI.ListLabServerIDs();
                lblRevision.Text = "<!--  " + iLabGlobal.Release + "  -->";
                LabDB service = new LabDB();
                LabAppInfo[] labs = service.GetLabApps();
                ddlWhichLab.Items.Add("System-wide error");

                String optList = ConfigurationManager.AppSettings["helpOptions"];
                if((optList != null)&& (optList.Length >0)){
                    char [] delimiter = {','};
                    String [] options =optList.Split(delimiter,100);
                    for(int i =0;i< options.Length;i++)
                    {
                        ddlWhichLab.Items.Add(new ListItem(options[i],"0"));
                    }
                    if(options.Length > 0)
                    {
                        ddlWhichLab.Items[0].Selected = false;
                    }
                }

                foreach (LabAppInfo p in labs)
                {
                    //if(l.labServerID >0)
                    ddlWhichLab.Items.Add(new ListItem(p.application,p.appID.ToString()));
                }

            }
        }
        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 void Page_Load(object sender, System.EventArgs e)
        {
            LabDB dbManager = new LabDB();
            int appID = 0;
            long expID = 0;
            LabTask task = null;
            string expLen = null;
            string pageURL = null;
            bool useTaskDuration = true;
            // Query values from the request
            if (!IsPostBack)
            {
                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"];
                expLen = Request.QueryString["explen"];
                if ((returnTarget != null) && (returnTarget.Length > 0))
                    Session["sbUrl"] = 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);

                    }
                    Session[""] = issuerGUID;
                    Session[""] = expCoupId;
                    Session[""] = passkey;
                    ////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);
                    }
                    // This is no longer the case as the USS handles groups and permissions
                    //else // Have to use groupName & Servicebroker THIS REQUIRES groups & permissions are set in database
                    //{
                    //    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)
                            {
                                //ToDo: check if the tasks should all be closed
                                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
                        BeeAPI factory = new BeeAPI();
                        task = factory.CreateLabTask(appInfo, expTicket);

                        if (task != null)
                        {
                            if (task.storage != null && task.storage.Length > 0)
                            {
                                DataSourceManager dsManager = new DataSourceManager(task);
                                FileWatcherDataSource fds = factory.CreateBeeDataSource(expCoupon, task, "data", true);
                                dsManager.AddDataSource(fds);
                                fds.Start();
                                TaskProcessor.Instance.AddDataManager(task.taskID, dsManager);
                            }
                            TaskProcessor.Instance.Add(new BeeTask(task));

                            //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 = dbManager.GetTask(expID, sbStr);
                        if (task.Status == LabTask.eStatus.Scheduled)
                        {
                            pageURL = appInfo.appURL;
                        }
                        else if (task.Status == LabTask.eStatus.Running)
                        {
                            pageURL = ProcessAgentDB.ServiceAgent.codeBaseUrl + @"/BEEgraph.aspx";
                        }
                        else if (task.Status == LabTask.eStatus.Aborted
                            || task.Status == LabTask.eStatus.Closed
                            || task.Status == LabTask.eStatus.Completed
                            || task.Status == LabTask.eStatus.Expired)
                        {
                            Response.Redirect("AccessDenied.aspx?text=The+requested+experiment+is+no+longer+running.", true);
                        }

                    }
                }
                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);
                    if(expLen != null && expLen.Length > 0)
                        buf.Append("&explen=" + expLen);
                    //if (useTaskDuration)
                    //{
                    //    TimeSpan taskDur = task.endTime.Subtract(DateTime.UtcNow);
                    //    int hours = Convert.ToInt32(taskDur.TotalHours);
                    //    buf.Append("&explen=" + hours);
                    //}
                    Response.Redirect(buf.ToString(), true);
                }
                else
                {
                    Response.Redirect("AccessDenied.aspx?text=Unable+to+launch++application,+please+notify+your+administrator.", true);
                }
            }
        }
Пример #22
0
        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();
        }
Пример #23
0
 public BeeTask InsertTask(int appId, long expId, string groupName, DateTime startTime, long duration, LabTask.eStatus status,
     long coupon_ID, string issuerGuid, string essService, string taskData)
 {
     BeeTask beeTask = null;
     LabDB dbManager = new LabDB();
     LabTask labTask = dbManager.InsertTask(appId, expId,
                 groupName, startTime, duration, status,
                 coupon_ID, issuerGuid, essService, taskData);
     beeTask = new BeeTask(labTask);
     return beeTask;
 }
Пример #24
0
        protected void Application_Start(Object sender, EventArgs e)
        {
            string path = ConfigurationSettings.AppSettings["logPath"];
            if (path != null && path.Length > 0)
            {
                Utilities.LogPath = path;
                Utilities.WriteLog("");
                Utilities.WriteLog("#############################################################################");
                Utilities.WriteLog("");
                Utilities.WriteLog("Application_Start: starting");
            }

            //Should load any active tasks and update any expired tasks
            LabDB dbService = new LabDB();
            LabTask[] activeTasks = dbService.GetActiveTasks();
            foreach (LabTask task in activeTasks)
            {
                TaskProcessor.Instance.Add(task);
            }
            taskThread = new TaskHandler(TaskProcessor.Instance);
            ticketRemover = new TicketRemover();
        }
Пример #25
0
        /// <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;
        }
 public int CloseExperiment(long experimentId, int reason)
 {
     int sstatus = StorageStatus.UNKNOWN;
     LabDB dbManager = new LabDB();
     if (dbManager.AuthenticateAgentHeader(agentAuthHeader))
     {
         LabTask.eStatus estatus = dbManager.ExperimentStatus(experimentId, agentAuthHeader.agentGuid);
         if(estatus == LabTask.eStatus.Running
             || estatus == LabTask.eStatus.Scheduled
              || estatus == LabTask.eStatus.Pending
              || estatus == LabTask.eStatus.Waiting)
         {
             LabTask task = TaskProcessor.Instance.GetTask(experimentId, agentAuthHeader.agentGuid);
             TaskProcessor.Instance.Remove(task);
             // close existing data Sources ln task.Close
             estatus = task.Close();
             switch (estatus)
             {
                 case LabTask.eStatus.Aborted:
                 case LabTask.eStatus.Closed:
                 case LabTask.eStatus.Completed:
                     sstatus = StorageStatus.CLOSED;
                     break;
                 case LabTask.eStatus.Expired:
                     sstatus = StorageStatus.CLOSED_TIMEOUT;
                     break;
                 case LabTask.eStatus.Pending:
                 case LabTask.eStatus.Running:
                 case LabTask.eStatus.Scheduled:
                 case LabTask.eStatus.Waiting:
                     sstatus = StorageStatus.RUNNING;
                     break;
                 default:
                     break;
             }
         }
     }
     else
     {
         sstatus = StorageStatus.ERROR;
     }
     return sstatus;
 }
Пример #27
0
        public virtual eStatus Close(eStatus reason)
        {
            LabDB dbService = new LabDB();

            try
            {
                if (data != null)
                {
                    XmlQueryDoc taskDoc = new XmlQueryDoc(data);
                    string app = taskDoc.Query("task/application");
                    string statusName = taskDoc.Query("task/status");
                    string server = taskDoc.Query("task/server");
                    string portStr = taskDoc.Query("task/serverPort");

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

                   //Stop the application & close ESS sessions

                }
                Logger.WriteLine("TaskID = " + taskID + " is being closed");
                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);
            }

            return status;
        }