/// <summary> /// save the new Admin URL /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSaveChanges_Click(object sender, EventArgs e) { if (ttDropDownList.SelectedIndex == 0) { // Show Error Message string jScript = "<script language='javascript'>" + "alert('Please select a ticket type')" + "</script>"; Page.RegisterStartupScript("Error Window", jScript); return; } if (txtURL == null || txtURL.Equals("")) { // URL Text box should be filled // Show Error Message string jScript = "<script language='javascript'>" + "alert('Please provide a value for the URL')" + "</script>"; Page.RegisterStartupScript("Error Window", jScript); return; } // create new Admin URL BrokerDB issuer = new BrokerDB(); issuer.InsertAdminURL(paTag.id, txtURL.Text, ttDropDownList.SelectedItem.Value); // refresh repeater refreshUrlRepeater(); // reset Gui ttDropDownList.SelectedIndex = 0; txtURL.Text = ""; }
protected void Page_Load(object sender, EventArgs e) { txtAgentGUID.Text = System.Configuration.ConfigurationManager.AppSettings["serviceGUID"].ToString(); txtURL.Text = System.Configuration.ConfigurationManager.AppSettings["codebaseURL"].ToString(); txtName.Text = System.Configuration.ConfigurationManager.AppSettings["serviceName"].ToString(); BrokerDB ticketing = new BrokerDB(); if (ticketing.GetProcessAgent(txtAgentGUID.Text) != null) { btnAssociated.Enabled = false; } else { btnAssociated.Enabled = true; } }
protected void btnAssociated_Click(object sender, EventArgs e) { BrokerDB ticketing = new BrokerDB(); Coupon coupon = null; string webserviceURL = System.Configuration.ConfigurationManager.AppSettings["serviceURL"].ToString(); //string infoURL = System.Configuration.ConfigurationManager.AppSettings["infoURL"].ToString(); string contactEmail = System.Configuration.ConfigurationManager.AppSettings["registrationMailAddress"].ToString(); ticketing.SelfRegisterProcessAgent(txtAgentGUID.Text, txtName.Text, ProcessAgentType.SERVICE_BROKER, txtAgentGUID.Text, txtURL.Text, webserviceURL); ProcessAgentDB.RefreshServiceAgent(); //ticketing.InsertProcessAgent(txtAgentGUID.Text, txtName.Text, // ProcessAgentType.SERVICE_BROKER, null, webserviceURL, txtURL.Text, infoURL, contactEmail, -5, // coupon, coupon); }
/// <summary> /// Queries the IssuedTicket table, for any 'Expired' tickets trys to notify any users /// close any active data references and to delete the Issued Ticket. Then checks to /// see if any of the ticket coupons no longer are needed and removes them. /// May be called directly as the standard Run method waits until the timeout is /// done before calling this, useful for debugging. /// </summary> public void ProcessIssuedTickets() { BrokerDB brokerDb = new BrokerDB(); try { List<Ticket> expired = brokerDb.GetExpiredIssuedTickets(); if (expired.Count > 0) { RemoveTickets(expired, brokerDb); } } catch (Exception e) { Utilities.WriteLog("TicketRemover: " + e.Message + ": " + Utilities.DumpException(e)); } }
/// <summary> /// /// </summary> /// <param name="username"></param> /// <param name="groupName"></param> /// <param name="labClientName"></param> /// <param name="labClientVersion"></param> /// <returns>The redirect url where the user should be redirected, with the coupon appended to it</returns> public string ExecuteExerimentSchedulingRecipe(string ussGuid, string lssGuid, string username, string groupName, string labServerGuid, string clientGuid, string labClientName, string labClientVersion, long duration, int userTZ) { try { BrokerDB issuer = new BrokerDB(); TicketLoadFactory factory = TicketLoadFactory.Instance(); string ticketType = TicketTypes.SCHEDULE_SESSION; //the uss is the redeemer of the scheduling ticket //string redeemerId = uss.agentGuid; //the SB is the sponsor of the scheduling ticket //string sponsorId = issuer.GetIssuerGuid(); string payload1 = factory.createScheduleSessionPayload(username, groupName, issuer.GetIssuerGuid(), labServerGuid, clientGuid, labClientName, labClientVersion, userTZ); string payload2 = factory.createRequestReservationPayload(); Coupon schedulingCoupon = issuer.CreateTicket(TicketTypes.SCHEDULE_SESSION, ussGuid, issuer.GetIssuerGuid(), duration, payload1); issuer.AddTicket(schedulingCoupon, TicketTypes.REQUEST_RESERVATION, lssGuid, ussGuid, duration, payload2); // // construct the redirection url // string issuerGuid = schedulingCoupon.issuerGuid; string passkey = schedulingCoupon.passkey; string couponId = schedulingCoupon.couponId.ToString(); // obtain the reservation URL from the admin URLs table string schedulingUrl = issuer.RetrieveAdminURL(ussGuid, TicketTypes.SCHEDULE_SESSION).Url; schedulingUrl += "?coupon_id=" + couponId + "&issuer_guid=" + issuerGuid + "&passkey=" + passkey; return schedulingUrl; } catch { throw; } }
private void reenterLabClient() { if (Session["UserID"] == null) { Response.Redirect("login.aspx"); } BrokerDB brokerDB = new BrokerDB(); StringBuilder message = new StringBuilder("Message: clientID = "); int[] labIds = new int[1]; message.Append(btnReenter.CommandArgument + " "); iLabParser parser = new iLabParser(); long expid = Convert.ToInt64(btnReenter.CommandArgument); LabClient client = AdministrativeAPI.GetLabClient(Convert.ToInt32(Session["ClientID"])); if (client.clientID > 0) { if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT) { iLabProperties properties = new iLabProperties(); properties.Add("sb",ProcessAgentDB.ServiceAgent); long[] coupIDs = InternalDataDB.RetrieveExperimentCouponIDs(expid); Coupon coupon = brokerDB.GetIssuedCoupon(coupIDs[0]); if(coupon != null) properties.Add("op", coupon); // construct the redirect query ProcessAgentInfo lsInfo = getLabServer(client.clientID,effectiveGroupID); if(lsInfo != null) properties.Add("ls",lsInfo); StringBuilder url = new StringBuilder(client.loaderScript.Trim()); // Add the return url to the redirect if (url.ToString().IndexOf("?") == -1) url.Append('?'); else url.Append('&'); url.Append("sb_url="); url.Append(Utilities.ExportUrlPath(Request.Url)); string targetURL = parser.Parse(url,properties,true); // Now open the lab within the current Window/frame Response.Redirect(targetURL, true); } } }
/// <summary> /// protected constructor /// </summary> protected ResourceDescriptorFactory() { brokerDb = new BrokerDB(); }
private static void ExecuteExperimentExecutionRecipe(ProcessAgentInfo labServer, ref LabClient client, ref DateTime startExecution, long duration, int userTZ, int userID, int groupID, string groupName, out BrokerDB brokerDB, out Coupon coupon) { int essId = 0; ProcessAgentInfo essAgent = null; long ticketDuration = 7200; //Default to 2 hours // Add a 10 minutes to ESS ticket duration ( in seconds ) to extend beyond experiment expiration if (duration != -1) { //ticketDuration = duration + 60; // For testing only add a minute ticketDuration = duration + 600; // Add 10 minutes beyond the experiment end } else { ticketDuration = -1; } // Authorization wrapper AuthorizationWrapperClass wrapper = new AuthorizationWrapperClass(); // create ticket issuer and payload factory brokerDB = new BrokerDB(); TicketLoadFactory factory = TicketLoadFactory.Instance(); if (client.needsESS) { essId = brokerDB.FindProcessAgentIdForClient(client.clientID, ProcessAgentType.EXPERIMENT_STORAGE_SERVER); } // 1. Create Coupon for ExperimentCollection coupon = brokerDB.CreateCoupon(); // // 2. create ServiceBroker experiment record and get corresponding experiment id // This checks authorization. long experimentID = wrapper.CreateExperimentWrapper(StorageStatus.INITIALIZED, userID, groupID, labServer.agentId, client.clientID, essId, startExecution, duration); // Store a record of the Experiment Collection Coupon DataStorageAPI.InsertExperimentCoupon(experimentID, coupon.couponId); string essWebAddress = null; // If a ESS is specified Create the ESS Tickets, this should only happen if a resource is mapped if (essId > 0) { //3.A create ESS administer experiment ticket, Add 10 minutes to duration // This must be created before the ESS experiment records may be created essAgent = brokerDB.GetProcessAgentInfo(essId); if ((essAgent != null) && !essAgent.retired) { brokerDB.AddTicket(coupon, TicketTypes.ADMINISTER_EXPERIMENT, essAgent.AgentGuid, brokerDB.GetIssuerGuid(), ticketDuration, factory.createAdministerExperimentPayload(experimentID, essAgent.webServiceUrl)); //3.B create store record ticket brokerDB.AddTicket(coupon, TicketTypes.STORE_RECORDS, essAgent.agentGuid, labServer.agentGuid, ticketDuration, factory.StoreRecordsPayload(true, experimentID, essAgent.webServiceUrl)); //3.C create retrieve experiment ticket, retrieve Experiment Records never expires, unless experiment deleted // This should be changed to a long but finite period once eadExisting Expermint is in place. brokerDB.AddTicket(coupon, TicketTypes.RETRIEVE_RECORDS, essAgent.agentGuid, brokerDB.GetIssuerGuid(), -1, factory.RetrieveRecordsPayload(experimentID, essAgent.webServiceUrl)); // 3.D Create the ESS Experiment Records ExperimentStorageProxy ess = new ExperimentStorageProxy(); ess.AgentAuthHeaderValue = new AgentAuthHeader(); ess.AgentAuthHeaderValue.coupon = essAgent.identOut; ess.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; ess.Url = essAgent.webServiceUrl; essWebAddress = essAgent.webServiceUrl; // Call the ESS to create the ESS Records and open the experiment StorageStatus status = ess.OpenExperiment(experimentID, ticketDuration); if (status != null) DataStorageAPI.UpdateExperimentStatus(status); } } // // 4. create the execution ticket for the experiment // // 4.A create payload string payload = factory.createExecuteExperimentPayload(essWebAddress, startExecution, duration, userTZ, groupName, brokerDB.GetIssuerGuid(), experimentID); // 4.B create experiment execution ticket. brokerDB.AddTicket(coupon, TicketTypes.EXECUTE_EXPERIMENT, labServer.agentGuid, labServer.agentGuid, ticketDuration, payload); // 4.C Create sessionRedemption Ticket string sessionPayload = factory.createRedeemSessionPayload(userID, groupID, client.clientID); brokerDB.AddTicket(coupon, TicketTypes.REDEEM_SESSION, brokerDB.GetIssuerGuid(), brokerDB.GetIssuerGuid(), ticketDuration, sessionPayload); }
protected void lbxSelectExperiment_SelectedIndexChanged(object sender, System.EventArgs e) { clearExperimentDisplay(); try { ExperimentSummary[] expInfo = wrapper.GetExperimentSummaryWrapper (new long[] {Int64.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value)}); if(expInfo[0] != null) { if( expInfo[0].essGuid != null){ int expStatus = expInfo[0].status; if ((expStatus == StorageStatus.UNKNOWN || expStatus == StorageStatus.INITIALIZED || expStatus == StorageStatus.OPEN || expStatus == StorageStatus.REOPENED || expStatus == StorageStatus.RUNNING || expStatus == StorageStatus.BATCH_QUEUED || expStatus == StorageStatus.BATCH_RUNNING || expStatus == StorageStatus.BATCH_TERMINATED || expStatus == StorageStatus.BATCH_TERMINATED_ERROR)) { // This operation should happen within the Wrapper BrokerDB ticketIssuer = new BrokerDB(); ProcessAgentInfo ess = ticketIssuer.GetProcessAgentInfo(expInfo[0].essGuid); if (ess.retired) { throw new Exception("The experiments ESS has been retired"); } Coupon opCoupon = ticketIssuer.GetEssOpCoupon(expInfo[0].experimentId, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid); if (opCoupon != null) { ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = opCoupon; essProxy.Url = ess.webServiceUrl; essProxy.OperationAuthHeaderValue = header; StorageStatus curStatus = essProxy.GetExperimentStatus(expInfo[0].experimentId); if (expInfo[0].status != curStatus.status || expInfo[0].recordCount != curStatus.recordCount || expInfo[0].closeTime != curStatus.closeTime) { DataStorageAPI.UpdateExperimentStatus(curStatus); expInfo[0].status = curStatus.status; expInfo[0].recordCount = curStatus.recordCount; expInfo[0].closeTime = curStatus.closeTime; } } } } txtExperimentID.Text = expInfo[0].experimentId.ToString () ; txtUserName1.Text = expInfo[0].userName ; txtLabServerName.Text =expInfo[0].labServerName; txtClientName.Text = expInfo[0].clientName; txtGroupName1.Text = expInfo[0].groupName; txtStatus.Text = DataStorageAPI.getStatusString(expInfo[0].status); txtSubmissionTime.Text = DateUtil.ToUserTime(expInfo[0].creationTime,culture,userTZ); if ((expInfo[0].closeTime != null) && (expInfo[0].closeTime != DateTime.MinValue)) txtCompletionTime.Text = DateUtil.ToUserTime(expInfo[0].closeTime, culture, userTZ); else txtCompletionTime.Text = "Not Closed!"; txtRecordCount.Text = expInfo[0].recordCount.ToString(); txtAnnotation.Text = expInfo[0].annotation; txtAnnotation.ReadOnly = false; trShowExperiment.Visible = (expInfo[0].recordCount >0); trSaveAnnotation.Visible = true; trDeleteExperiment.Visible = true; } //txtExperimentSpecification.Text = wrapper.RetrieveExperimentSpecificationWrapper (Int32.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value)); //txtExperimentResult.Text = wrapper.RetrieveExperimentResultWrapper (Int32.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value)); //txtLabconfig.Text = wrapper.RetrieveLabConfigurationWrapper (Int32.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value)); } catch(Exception ex) { lblResponse.Text ="<div class=errormessage><p>Exception: Error retrieving experiment information. "+ex.Message+"</p></div>"; lblResponse.Visible=true; } }
public static ExperimentInformation[] GetExperimentInformation(int[] experimentIDs) { List<ExperimentInformation> list = new List<ExperimentInformation>(); try { long[] expIDs = new long[experimentIDs.Length]; for (int i = 0; i < experimentIDs.Length; i++) { expIDs[i] = (long)experimentIDs[i]; } ExperimentAdminInfo[] expSummaries = InternalDataDB.SelectExperimentAdminInfos(expIDs); if (expSummaries != null) foreach (ExperimentAdminInfo expSum in expSummaries) { ExperimentInformation info = new ExperimentInformation(); info.experimentID = expSum.experimentID; info.userID = expSum.userID; info.effectiveGroupID = expSum.groupID; info.labServerID = expSum.agentID; info.statusCode = expSum.status & StorageStatus.BATCH_MASK; info.submissionTime = expSum.creationTime; info.completionTime = expSum.closeTime; DateTime endTime = expSum.startTime.AddSeconds(expSum.duration); info.expirationTime = endTime; double hours = new TimeSpan(endTime.Ticks - DateTime.UtcNow.Ticks).TotalHours; info.minTimeToLive = hours > 0 ? hours : 0; info.annotation = expSum.annotation; //Get the Experiment records from the ESS if one is used if (expSum.essID > 0) { // This operation should happen within the Wrapper BrokerDB brokerDB = new BrokerDB(); ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(expSum.essID); Coupon opCoupon = brokerDB.GetEssOpCoupon( expSum.experimentID, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid); ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = opCoupon; essProxy.Url = ess.webServiceUrl; essProxy.OperationAuthHeaderValue = header; Criterion errors = new Criterion("record_type", "like", "*Message"); Criterion extensions = new Criterion("record_type", "like", "*Extension"); Criterion [] criteria = new Criterion[] {errors,extensions }; ExperimentRecord[] records = brokerDB.RetrieveExperimentRecords(expSum.experimentID, criteria); if (records != null) { List<String> valWarnings = new List<String>(); List<String> execWarnings = new List<String>(); foreach (ExperimentRecord rec in records) { if (rec.type.CompareTo(BatchRecordType.EXECUTION_ERROR) == 0) { info.executionErrorMessage = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.VALIDATION_ERROR) == 0) { info.validationErrorMessage = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.BLOB_EXTENSION) == 0) { info.xmlBlobExtension = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.RESULT_EXTENSION) == 0) { info.xmlResultExtension = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.EXECUTION_WARNING) == 0) { execWarnings.Add(rec.contents); } else if (rec.type.CompareTo(BatchRecordType.VALIDATION_WARNING) == 0) { valWarnings.Add(rec.contents); } } if (execWarnings.Count > 0) { info.executionWarningMessages = execWarnings.ToArray(); } if (valWarnings.Count > 0) { info.validationWarningMessages = valWarnings.ToArray(); } } } list.Add(info); } } catch { throw; } if (list.Count > 0) { return list.ToArray(); } else return null; }
protected void On_BlobSelected(object sender, GridViewCommandEventArgs e) { lblResponse.Visible = false; if (Session["EssGuid"] != null) { long blobId = Convert.ToInt64(e.CommandArgument); BrokerDB brokerDB = new BrokerDB(); ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(Session["EssGuid"].ToString()); if (ess == null || ess.retired) { throw new Exception("The ESS is not registered or is retired"); } Coupon opCoupon = brokerDB.GetEssOpCoupon(Convert.ToInt64(txtExperimentID.Text), TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid); if (opCoupon != null) { ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = opCoupon; essProxy.Url = ess.webServiceUrl; essProxy.OperationAuthHeaderValue = header; string url = essProxy.RequestBlobAccess(blobId, "http", 30); if (url != null) { string jScript = "<script language='javascript'>" + "window.open('" + url + "')" + "</script>"; Page.RegisterStartupScript("Open New Window", jScript); //Response.Redirect(url); } else{ lblResponse.Text = Utilities.FormatWarningMessage("Could not access BLOB. "); lblResponse.Visible = true; } } } else { lblResponse.Text = Utilities.FormatWarningMessage("No ESS is specified, so no records. "); lblResponse.Visible = true; } }
public int RemoveTickets(List<Ticket> ticketList, BrokerDB brokerDb) { ArrayList coupons = new ArrayList(); Coupon coupon = null; int ticketCount = 0; int couponCount = 0; if (ticketList.Count > 0) { Utilities.WriteLog("RemoveTickets: expired count = " + ticketList.Count); foreach (Ticket ticket in ticketList) { if (!coupons.Contains(ticket.couponId)) { coupons.Add(ticket.couponId); } if (coupon == null || coupon.couponId != ticket.couponId) { coupon = brokerDb.GetIssuedCoupon(ticket.couponId); } switch (ticket.type) { case TicketTypes.ADMINISTER_EXPERIMENT: string payload = ticket.payload; if (payload != null) { XmlQueryDoc xDoc = new XmlQueryDoc(payload); string url = xDoc.Query("AdministerExperimentPayload/essURL"); string expStr = xDoc.Query("AdministerExperimentPayload/experimentID"); long expID = Convert.ToInt64(expStr); ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); essProxy.OperationAuthHeaderValue = new OperationAuthHeader(); essProxy.OperationAuthHeaderValue.coupon = coupon; essProxy.Url = url; StorageStatus expStatus = essProxy.SetExperimentStatus(expID, (int)StorageStatus.CLOSED_TIMEOUT); DataStorageAPI.UpdateExperimentStatus(expStatus); } break; case TicketTypes.RETRIEVE_RECORDS: case TicketTypes.STORE_RECORDS: break; case TicketTypes.EXECUTE_EXPERIMENT: case TicketTypes.ALLOW_EXPERIMENT_EXECUTION: break; default: // Every other Ticket type break; } bool statusR = false; if (ticket.redeemerGuid != brokerDb.GetIssuerGuid()) { ProcessAgentInfo redeemer = brokerDb.GetProcessAgentInfo(ticket.redeemerGuid); if ((redeemer != null) && !redeemer.retired) { ProcessAgentProxy paProxy = new ProcessAgentProxy(); paProxy.AgentAuthHeaderValue = new AgentAuthHeader(); paProxy.Url = redeemer.webServiceUrl; paProxy.AgentAuthHeaderValue.coupon = redeemer.identOut; paProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; statusR = paProxy.CancelTicket(coupon, ticket.type, ticket.redeemerGuid); } } if (ticket.issuerGuid == brokerDb.GetIssuerGuid()) { brokerDb.DeleteIssuedTicket(ticket.ticketId); ticketCount++; } } foreach (long id in coupons) { int count = brokerDb.GetIssuedCouponCollectionCount(id); if (count == 0) { brokerDb.DeleteIssuedCoupon(id); couponCount++; } } Utilities.WriteLog("RemoveTickets: ticketCount=" + ticketCount + " \tcouponCount=" + couponCount); } return ticketCount; }
private void LoadAuthorityList() { ddlAuthority.Items.Clear(); BrokerDB brokerDB = new BrokerDB(); IntTag[] authTags = brokerDB.GetAuthorityTags(); if (authTags != null && authTags.Length > 0) { foreach (IntTag t in authTags) { ListItem li = new ListItem(t.tag, t.id.ToString()); ddlAuthority.Items.Add(li); } ddlAuthority.SelectedValue = "0"; } }
public static long[] RetrieveAuthorizedExpIDs(int userID, int groupID, Criterion[] carray) { long[] expIDs = null; List<Criterion> sbList = new List<Criterion>(); List<Criterion> essList = new List<Criterion>(); if (carray != null && carray.Length > 0) { // Parse the criterion for (int i = 0; i < carray.Length; i++) { switch (carray[i].attribute.ToLower()) { //these criterion are based on external values, requiring special processing of the fields. case "username": sbList.Add(new Criterion("User_ID", carray[i].predicate, "(select user_id from users where user_name=" + carray[i].value + ")")); break; case "groupname": sbList.Add(new Criterion("Group_ID", carray[i].predicate, "(select group_id from group where group_name=" + carray[i].value + ")")); break; case "clientname": sbList.Add(new Criterion("Client_ID", carray[i].predicate, "(select client_id from lab_clients where lab_client_name=" + carray[i].value + ")")); break; case "labservername": sbList.Add(new Criterion("Agent_ID", carray[i].predicate, "(select agent_id from processAgent where agent_name=" + carray[i].value + ")")); break; case "start": sbList.Add(new Criterion("creationtime", carray[i].predicate, carray[i].value)); break; case "agent_id": // Actual SB experiment column names case "annotation": case "client_id": case "creationtime": case "ess_id": case "group_id": case "scheduledstart": case "user_id": sbList.Add(carray[i]); break; // ESS targets case "record_count": case "record_type": // Individual record criterion send to ESS case "contents": default: // any unhandled attributes are record attributes essList.Add(carray[i]); break; } } //parsing of Criterion done } if (sbList.Count == 0 && essList.Count == 0) { // No search items - Get all experiments allowed expIDs = InternalDataDB.RetrieveExperimentIDs(userID, groupID); } else { // Query SB database to find all possible Experiments and related ESS's //As there are criteria only experiments with hits will be returned bool hasEssCriteria = (essList.Count > 0); List<long> workExp = new List<long>(); Hashtable essLists = null; // DataSet contains all experimentID and ess ids that pass SB criteria, // and a set of all ess_ids for the authorized experiments DataSet results = InternalDataDB.RetrieveExperimentIDsCriteria(userID, groupID, sbList.ToArray()); if (results != null) { if (hasEssCriteria) { DataTable essids = results.Tables["ess"]; if (essids != null && essids.Rows != null && essids.Rows.Count > 0) { essLists = new Hashtable(); foreach (DataRow er in essids.Rows) { if (er[0] != DBNull.Value) { List<Int64> exps = new List<Int64>(); essLists.Add(Convert.ToInt32(er[0]), exps); } } } } DataTable hits = results.Tables["sbHits"]; if (hits != null) { // Add SB hits to list foreach (DataRow r in hits.Rows) { workExp.Add(Convert.ToInt64(r[0])); if (hasEssCriteria) { if (r[1] != DBNull.Value) { ((List<Int64>)essLists[Convert.ToInt32(r[1])]).Add(Convert.ToInt64(r[0])); } } } } if (hasEssCriteria) { // Have ESS criteria, use the workList and further filter List<Int64> essHits = new List<Int64>(); BrokerDB brokerDB = new BrokerDB(); //Process ess criteria foreach (object obj in essLists.Keys) { List<Int64> essExps = (List<Int64>)essLists[obj]; if (essExps.Count > 0) { int essId = Convert.ToInt32(obj); ProcessAgentInfo info = brokerDB.GetProcessAgentInfo(essId); if ((info != null) && !info.retired) { ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); AgentAuthHeader authHeader = new AgentAuthHeader(); authHeader.agentGuid = ProcessAgentDB.ServiceGuid; authHeader.coupon = info.identOut; essProxy.AgentAuthHeaderValue = authHeader; essProxy.Url = info.webServiceUrl; long[] essExpids = essProxy.GetExperimentIDs(essExps.ToArray(), essList.ToArray()); if (essExpids != null && essExpids.Length > 0) { foreach (long e in essExpids) { essHits.Add(e); } } } } }// End of ESS processing expIDs = essHits.ToArray(); } else { expIDs = workExp.ToArray(); } } } return expIDs; }
private void LoadAuthorityList() { BrokerDB brokerDB = new BrokerDB(); ddlAuthorities.Items.Clear(); ListItem liHeaderAdminGroup = new ListItem("--- Select Authority ---", "-1"); ddlAuthorities.Items.Add(liHeaderAdminGroup); IntTag[] authTags = brokerDB.GetAuthorityTags(); if (authTags != null && authTags.Length > 0) { foreach (IntTag t in authTags) { ListItem li = new ListItem(t.tag, t.id.ToString()); ddlAuthorities.Items.Add(li); } } }
protected void Page_Load(object sender, EventArgs e) { StringBuilder buf; long couponID = -1L; int userID = -1; int groupID = -1; int clientID = -1; int labServerID = -1; int userTZ = 0; string clientGuid = null; string serverGuid = null; string groupName = null; string userName = null; string authKey = null; string startStr = null; string durStr = null; Coupon initCoupon = null; LabClient client = null; BrokerDB brokerDB = new BrokerDB(); buf = new StringBuilder(); string cidStr = Request.QueryString["cid"]; string authStr = Request.QueryString["ss"]; if (!String.IsNullOrEmpty(cidStr)) { string test =hdnUserTZ.Value; couponID = Int64.Parse(cidStr); initCoupon = brokerDB.GetIssuedCoupon(couponID); if (initCoupon != null) { Ticket launchTicket = brokerDB.RetrieveIssuedTicket(initCoupon, TicketTypes.LAUNCH_CLIENT, ProcessAgentDB.ServiceGuid); if (launchTicket != null && !launchTicket.isCancelled && !launchTicket.IsExpired()) { XmlQueryDoc xDoc = new XmlQueryDoc(launchTicket.payload); //Check that the coupon matches the passcode in the ticket payload string passChk = xDoc.Query("LaunchClient/passcode"); string ssChk = xDoc.Query("LaunchClient/ss"); if (String.IsNullOrEmpty(passChk) || passChk.CompareTo(initCoupon.passkey) != 0) { buf.AppendLine("Passkey Error"); processError(buf); } if (String.IsNullOrEmpty(ssChk) || passChk.CompareTo(authStr) != 0) { buf.AppendLine("ss_key Error"); processError(buf); } clientGuid = xDoc.Query("LaunchClient/clientGuid"); serverGuid = xDoc.Query("LaunchClient/serverGuid"); groupName = xDoc.Query("LaunchClient/groupName"); authKey = xDoc.Query("LaunchClient/authorityKey"); string userIdStr = xDoc.Query("LaunchClient/userId"); userName = xDoc.Query("LaunchClient/userName"); if (String.IsNullOrEmpty(authKey)) { buf.AppendLine("authority Error"); processError(buf); } if (!String.IsNullOrEmpty(userIdStr)) { userID = Int32.Parse(userIdStr); if (userID <= 0) { buf.AppendLine("userID invalid value"); processError(buf); } } else { buf.AppendLine("userID not specified"); processError(buf); } if (!String.IsNullOrEmpty(groupName)) { groupID = AdministrativeAPI.GetGroupID(groupName); if (groupID <= 0) { buf.AppendLine("groupName invalid value"); processError(buf); } } else { buf.AppendLine("groupName not specified"); processError(buf); } startStr = xDoc.Query("LaunchClient/start"); durStr = xDoc.Query("LaunchClient/duration"); if (!String.IsNullOrEmpty(clientGuid)) { clientID = AdministrativeAPI.GetLabClientID(clientGuid); if (clientID > 0) { // do the real work IntTag results = brokerDB.ProcessLaunchClientRequest(initCoupon, clientID, labServerID, groupID, userID, userTZ); // Checks for different status values //TODO Check for Scheduling redirect -- May be checked before we get here if (results.id > -1) { long sessionID = AdministrativeAPI.InsertUserSession(userID, groupID, clientID, userTZ, Session.SessionID); //add Session cookie HttpCookie cookie = new HttpCookie(ConfigurationManager.AppSettings["isbAuthCookieName"], sessionID.ToString()); Response.AppendCookie(cookie); Response.AddHeader("Access-Control-Allow-Origin", "*"); if ((results.id & LabClient.APPLET_BIT) == LabClient.APPLET_BIT) { Session["LoaderScript"] = results.tag; Response.Redirect("applet2.aspx", true); } else if ((results.id & LabClient.REDIRECT_BIT) == LabClient.REDIRECT_BIT) { string url = results.tag; Response.Redirect(url, true); } else { buf.AppendLine("Client type not supported"); } } else { buf.AppendLine("Client not found"); } } else { buf.AppendLine("client not specified"); processError(buf); } } } else { buf.AppendLine("Ticket Error"); } } } else { buf.AppendLine("Missing cid"); } // If the code above does not complete fall through to processError() processError(buf); }
public ClientSubmissionReport Submit(string labServerID, string experimentSpecification, int priorityHint, bool emailNotification) { // Default to 24 hours duration long duration = TimeSpan.TicksPerDay/TimeSpan.TicksPerSecond; int seqNo = 0; ClientSubmissionReport clientSReport = null; try{ // Checking if user has permission to use the lab server. The method will set headers for lab server calls //if authorization is successful. CheckAndSetLSAuthorization(labServerID); //Retrieve variables from session int userID = Convert.ToInt32(Session["UserID"]); int effectiveGroupID = Convert.ToInt32(Session["GroupID"]); int clientID = 0; if (Session["ClientID"] != null ) clientID = Convert.ToInt32(Session["ClientID"]); string effectiveGroup = Session["GroupName"].ToString(); ProcessAgentInfo infoLS = dbTicketing.GetProcessAgentInfo(labServerID); if (infoLS.retired) { throw new Exception("The Batch Lab Server is retired"); } // get qualifier ID of labServer int qualifierID = AuthorizationAPI.GetQualifierID(infoLS.agentId, Qualifier.labServerQualifierTypeID); /* End collecting information */ // Checking if user has permission to use the lab server if (!AuthorizationAPI.CheckAuthorization(userID, Function.useLabServerFunctionType, qualifierID)) { // check fails throw new AccessDeniedException("Access denied using labServer '" + infoLS.agentName + "'."); } else { int[] groupIDs = new int[1]; groupIDs[0] = effectiveGroupID; SubmissionReport sReport = new SubmissionReport(); clientSReport = new ClientSubmissionReport(); clientSReport.vReport = new ValidationReport(); clientSReport.wait = new WaitEstimate(); BrokerDB brokerDB = new BrokerDB(); // 1. Create Coupon for ExperimentCollection Coupon coupon = brokerDB.CreateCoupon(); int essID = brokerDB.FindProcessAgentIdForClient(clientID, ProcessAgentType.EXPERIMENT_STORAGE_SERVER); // // 2. create ServiceBroker experiment record and get corresponding experiment id // This checks authorization. long experimentID = wrapper.CreateExperimentWrapper(StorageStatus.INITIALIZED, userID, effectiveGroupID, infoLS.agentId, clientID, essID, DateTime.UtcNow, duration); // Store a record of the Experiment Collection Coupon DataStorageAPI.InsertExperimentCoupon(experimentID, coupon.couponId); //3.A create ESS administer experiment ticket, Add 10 minutes to duration // This must be created before the ESS experiment records may be created ProcessAgentInfo essAgent = brokerDB.GetProcessAgentInfo(essID); if (essAgent.retired) { throw new Exception("The Batch Lab Server is retired"); } TicketLoadFactory factory = TicketLoadFactory.Instance(); brokerDB.AddTicket(coupon, TicketTypes.ADMINISTER_EXPERIMENT, essAgent.AgentGuid, ProcessAgentDB.ServiceGuid, duration, factory.createAdministerExperimentPayload(experimentID, essAgent.webServiceUrl)); //3.B create store record ticket, in the MergedSB the records are all saved via the serviceBroker brokerDB.AddTicket(coupon, TicketTypes.STORE_RECORDS, essAgent.agentGuid, ProcessAgentDB.ServiceGuid, duration, factory.StoreRecordsPayload(true, experimentID, essAgent.webServiceUrl)); //3.C create retrieve experiment ticket, retrieve Experiment Records never expires, unless experiment deleted // This should be changed to a long but finite period once eadExisting Expermint is in place. brokerDB.AddTicket(coupon, TicketTypes.RETRIEVE_RECORDS, essAgent.agentGuid, ProcessAgentDB.ServiceGuid, -1, factory.RetrieveRecordsPayload(experimentID, essAgent.webServiceUrl)); // 3.D Create the ESS Experiment Records ExperimentStorageProxy ess = new ExperimentStorageProxy(); ess.AgentAuthHeaderValue = new AgentAuthHeader(); ess.AgentAuthHeaderValue.coupon = essAgent.identOut; ess.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; ess.OperationAuthHeaderValue = new OperationAuthHeader(); ess.OperationAuthHeaderValue.coupon = coupon; ess.Url = essAgent.webServiceUrl; // Call the ESS to create the ESS Records and open the experiment StorageStatus status = ess.OpenExperiment(experimentID, duration); if (status != null) DataStorageAPI.UpdateExperimentStatus(status); seqNo = ess.AddRecord(experimentID, ProcessAgentDB.ServiceGuid, BatchRecordType.SPECIFICATION, true, experimentSpecification, null); // save lab configuration string labConfiguration = batchLS_Proxy.GetLabConfiguration(effectiveGroup); seqNo = ess.AddRecord(experimentID, labServerID, BatchRecordType.LAB_CONFIGURATION, true, labConfiguration, null); // call labServer submit sReport = batchLS_Proxy.Submit(Convert.ToInt32(experimentID), experimentSpecification, effectiveGroup, priorityHint); // save submission report //wrapper.SaveSubmissionReportWrapper(experimentID, sReport); if (sReport.vReport != null) if ((sReport.vReport.errorMessage != null) && (sReport.vReport.errorMessage.CompareTo("") != 0)) { seqNo = ess.AddRecord(experimentID, labServerID, BatchRecordType.VALIDATION_ERROR, false, sReport.vReport.errorMessage, null); } if (sReport.vReport.warningMessages != null) foreach (string s in sReport.vReport.warningMessages) { if ((s != null) && (s.CompareTo("") != 0)) seqNo = ess.AddRecord(experimentID, labServerID, BatchRecordType.VALIDATION_WARNING, false, s, null); } // return clientSubmissionReport if (sReport.vReport != null) { clientSReport.vReport.accepted = sReport.vReport.accepted; clientSReport.vReport.errorMessage = sReport.vReport.errorMessage; // if error exists then change status to "an experiment with a problem" if ((sReport.vReport.errorMessage != null) && (!sReport.vReport.errorMessage.Equals(""))) { StorageStatus sStatus = new StorageStatus(); sStatus.experimentId = experimentID; //sStatus.estRuntime=sReport.vReport.estRuntime; sStatus.status = StorageStatus.BATCH_TERMINATED_ERROR; DataStorageAPI.UpdateExperimentStatus(sStatus); } clientSReport.vReport.estRuntime = sReport.vReport.estRuntime; clientSReport.vReport.warningMessages = sReport.vReport.warningMessages; } clientSReport.experimentID = Convert.ToInt32(experimentID); clientSReport.minTimeToLive = sReport.minTimetoLive; if (sReport.wait != null) { clientSReport.wait.effectiveQueueLength = sReport.wait.effectiveQueueLength; clientSReport.wait.estWait = sReport.wait.estWait; } } return clientSReport; } catch { throw; } }
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { brokerDB = new BrokerDB(); }
protected void Page_Load(object sender, System.EventArgs e) { if (Session["UserID"]==null) Response.Redirect("../login.aspx"); labClientID = int.Parse(Request.Params["lc"]); labClientIDs = new int[1]; labClientIDs[0] = labClientID; labClients = wrapper.GetLabClientsWrapper(labClientIDs); // Get Available Lab Servers BrokerDB brokerDB = new BrokerDB(); int[] serverIDs = brokerDB.GetProcessAgentIDsByType(new int[]{ (int)ProcessAgentType.AgentType.LAB_SERVER, (int)ProcessAgentType.AgentType.BATCH_LAB_SERVER}); AvailLabServers = wrapper.GetProcessAgentInfosWrapper(serverIDs); /// Get Associated Lab Servers (i.e. associated to a specified Lab Client) AssocLabServers = wrapper.GetProcessAgentInfosWrapper(labClients[0].labServerIDs); // Current Lab Client name lblLabClient.Text = labClients[0].clientName; // Error Message divErrorMessage.Visible = false; lblResponse.Visible = false; if(!IsPostBack) { LoadListBoxes(); } }
private void reenterLabClient() { if (Session["UserID"] == null) { Response.Redirect("login.aspx"); } BrokerDB brokerDB = new BrokerDB(); StringBuilder message = new StringBuilder("Message: clientID = "); int[] labIds = new int[1]; message.Append(btnReenter.CommandArgument + " "); long expid = Convert.ToInt64(btnReenter.CommandArgument); LabClient client = AdministrativeAPI.GetLabClient(Convert.ToInt32(Session["ClientID"])); if (client.clientID > 0) { if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT || client.clientType == LabClient.INTERACTIVE_APPLET) { long[] coupIDs = InternalDataDB.RetrieveExperimentCouponIDs(expid); Coupon coupon = brokerDB.GetIssuedCoupon(coupIDs[0]); if (client.clientType == LabClient.INTERACTIVE_HTML_REDIRECT) { // construct the redirect query StringBuilder url = new StringBuilder(client.loaderScript.Trim()); if (url.ToString().IndexOf("?") == -1) url.Append('?'); else url.Append('&'); url.Append("coupon_id=" + coupon.couponId + "&passkey=" + coupon.passkey + "&issuer_guid=" + brokerDB.GetIssuerGuid()); // Add the return url to the redirect url.Append("&sb_url="); url.Append(Utilities.ExportUrlPath(Request.Url)); // Now open the lab within the current Window/frame Response.Redirect(url.ToString(), true); } else if (client.clientType == LabClient.INTERACTIVE_APPLET) { // we have the coupon what do we need now to lauch the lab....? // the whole loader script part should have run... so we should be // able to skip that part. // one question would be is the coupon the same... // if they're not the same we need to change it. // It seems that it is the same. // then we just need to launch the client... string jScript = @"<script language='javascript'>parent.theapplet.location.href = '" + "applet.aspx" + @"'</script>"; Page.RegisterStartupScript("ReloadFrame", jScript); } } } }
protected void Page_Load(object sender, System.EventArgs e) { ticketing = new BrokerDB(); if (Session["UserID"] == null) Response.Redirect("../login.aspx"); //only superusers can view this page if (!Session["GroupName"].ToString().Equals(Group.SUPERUSER)) Response.Redirect("../home.aspx"); // Set the popup buttons' "CausesValidation" property. // For any button that is related to a popup, you have to set the CausesValidation // propery to false, otherwise // any RequiredFieldValidator control will cause the onclick event to be // comandeered by a routine in ASP.NET's WebValidationUI.js file. // The result would be that the custom onclick for the popup would not fire. //btnEditList.CausesValidation = false; btnAddEditResources.CausesValidation = false; btnRemove.CausesValidation = false; btnMetadata.CausesValidation = false; // This button enables the popup to fire an event on the caller when the Save button is hit. btnRefresh.CausesValidation = false; // "Are you sure" javascript for Remove button StringBuilder jScript = new StringBuilder(); jScript.Append( "javascript:if(confirm('Are you sure you want to remove this Lab Client? "); jScript.Append(" Removing the client will also delete all past experiments and clientItems!"); jScript.Append(" Deleting a ClientID should only be done prior to any user experiments being run."); jScript.Append( "')== false) return false;"); btnRemove.Attributes.Add("onclick",jScript.ToString()); // This is a hidden input tag. The associatedLabServers popup changes its value using a window.opener call in javascript, // then the GetPostBackEventReference fires the event associated with the btnRefresh button. // The result is that the LabServer repeater (repLabServers) is refreshed when the Save button is clicked // on the popup. hiddenPopupOnSave.Attributes.Add("onpropertychange", Page.GetPostBackEventReference(btnRefresh)); if (!Page.IsPostBack) { hdnEssID.Value = zero; hdnNeedsEss.Value = zero; hdnLabServerID.Value = zero; hdnUssID.Value = zero; hdnNeedsUss.Value = zero; // Load Lab Client dropdown InitializeClientDropDown(); //Put in client types ddlClientTypes.Items.Add(new ListItem("--- Select a Client Type ---", zero)); string[] clientTypes = InternalAdminDB.SelectLabClientTypes(); foreach (string cType in clientTypes) { ddlClientTypes.Items.Add(new ListItem(cType)); } ddlLabServer.Items.Add(new ListItem("--- Select a Lab Server ---", zero)); IntTag[] lsTags = ticketing.GetProcessAgentTagsByType(new int[] { (int)ProcessAgentType.AgentType.BATCH_LAB_SERVER, (int)ProcessAgentType.AgentType.LAB_SERVER }); foreach (IntTag ls in lsTags) { ListItem li = new ListItem(ls.tag, ls.id.ToString()); ddlLabServer.Items.Add(li); } //Put in availabe USS ListItem liHeaderUss = new ListItem("---Select User Side Scheduling Server---", zero); ddlAssociatedUSS.Items.Add(liHeaderUss); IntTag[] usses = ticketing.GetProcessAgentTagsByType(ProcessAgentType.SCHEDULING_SERVER, ProcessAgentDB.ServiceGuid); foreach (IntTag uss in usses) { ListItem li = new ListItem(uss.tag, uss.id.ToString()); ddlAssociatedUSS.Items.Add(li); } //Put in availabe ESS ListItem liHeaderEss = new ListItem("---Select Experiment Storage Server---", "0"); ddlAssociatedESS.Items.Add(liHeaderEss); IntTag[] esses = ticketing.GetProcessAgentTagsByType(ProcessAgentType.EXPERIMENT_STORAGE_SERVER, ProcessAgentDB.ServiceGuid); foreach (IntTag ess in esses) { ListItem li = new ListItem(ess.tag, ess.id.ToString()); ddlAssociatedESS.Items.Add(li); } // Disable the "Edit Lab Servers" button at first //btnEditList.Visible = false; txtLabServer.ReadOnly = true; txtLabServer.BackColor = disabled; txtLsUrl.ReadOnly = true; txtLsUrl.BackColor = disabled; txtAssociatedESS.ReadOnly = true; txtAssociatedESS.BackColor = disabled; txtAssociatedUSS.ReadOnly = true; txtAssociatedUSS.BackColor = disabled; ClearFormFields(); // Reset error/confirmation message lblResponse.Text = ""; lblResponse.Visible = false; } else if (Request.Params["refresh"] != null) { string tst = Request.Params["refresh"]; int cid = Int32.Parse(Request.Params["refresh"]); ListItem theItem = ddlLabClient.Items.FindByValue(cid.ToString()); if (theItem != null) { theItem.Selected = true; LoadFormFields(); } } }
/// <summary> /// /// </summary> /// <param name="qualifierReferenceID">the ID of the resource represented by the qualifier (null if not necessary);</param> /// <param name="type">one of the statically configured qualifierTypes registered with the Service Broker; the qualifier type is used to check type compatibility between function and qualifier in grants</param> /// <param name="name">A semantically meaningful string describing the purpose of the qualifier</param> /// <param name="parentQualifierID">the ID of a previously created Qualifier to serve as the parent of the Qualifier being added; the parentID locates the new Qualifier in the hierarchy; additional parents may be added by the AddQualifier-Parent() method</param> /// <returns>the ID of the new qualifier if it is successfully created, null otherwise</returns> public static int AddQualifier( int qualifierReferenceID, int type, string name, int parentQualifierID ) { Qualifier q = new Qualifier(); q.qualifierReferenceID = qualifierReferenceID; q.qualifierType = type; q.qualifierName = name; bool qualifierReferenceIDValid = false; int qualifierID = -1; ProcessAgentDB db = new ProcessAgentDB(); ProcessAgent agent = null; //need to check whether the qualifierReferenceID for a particular qualifierType //actually exists before it is added to the table switch (type) { // LabServerfo // Replace with case for all processAgent types an use exits for the combination of ID & type case Qualifier.labServerQualifierTypeID: { agent = db.GetProcessAgent(qualifierReferenceID); if(agent != null && ((agent.type.Equals(ProcessAgentType.BATCH_LAB_SERVER)) ||(agent.type.Equals(ProcessAgentType.LAB_SERVER)))){ qualifierReferenceIDValid = true; } break; } //LabClient case Qualifier.serviceBrokerQualifierTypeID: { agent = db.GetProcessAgent(qualifierReferenceID); if (agent != null && ((agent.type.Equals(ProcessAgentType.SERVICE_BROKER)) ||(agent.type.Equals(ProcessAgentType.BATCH_SERVICE_BROKER)) || (agent.type.Equals(ProcessAgentType.REMOTE_SERVICE_BROKER)))) { qualifierReferenceIDValid = true; } break; } case Qualifier.labSchedulingQualifierTypeID: { agent = db.GetProcessAgent(qualifierReferenceID); if (agent != null && agent.type.Equals(ProcessAgentType.LAB_SCHEDULING_SERVER)) { qualifierReferenceIDValid = true; } break; } case Qualifier.userSchedulingQualifierTypeID: { agent = db.GetProcessAgent(qualifierReferenceID); if (agent != null && agent.type.Equals(ProcessAgentType.SCHEDULING_SERVER)) { qualifierReferenceIDValid = true; } break; } case Qualifier.storageServerQualifierTypeID: { agent = db.GetProcessAgent(qualifierReferenceID); if (agent != null && agent.type.Equals(ProcessAgentType.EXPERIMENT_STORAGE_SERVER)) { qualifierReferenceIDValid = true; } break; } case Qualifier.labClientQualifierTypeID: { int[] labClientIDs = InternalAdminDB.SelectLabClientIDs(); foreach (int labClientID in labClientIDs) { if (labClientID == qualifierReferenceID) { qualifierReferenceIDValid = true; break; } } break; } //Group case Qualifier.groupQualifierTypeID: { int[] groupIDs = InternalAdminDB.SelectGroupIDs(); foreach(int groupID in groupIDs) { if(groupID == qualifierReferenceID) { qualifierReferenceIDValid = true; break; } } break; } //Experiment Collection case Qualifier.experimentCollectionQualifierTypeID: { int[] groupIDs = InternalAdminDB.SelectGroupIDs(); foreach(int groupID in groupIDs) { if(groupID == qualifierReferenceID) { qualifierReferenceIDValid = true; break; } } break; } //Experiment case Qualifier.experimentQualifierTypeID: { Criterion c = new Criterion("experiment_id","=",qualifierReferenceID.ToString()); if (InternalDataDB.SelectExperimentIDs(new Criterion[] { c }).Length > 0) qualifierReferenceIDValid = true; break; } // Resource Mapping case Qualifier.resourceMappingQualifierTypeID: { BrokerDB brokerDb = new BrokerDB(); ResourceMapping mapping = brokerDb.GetResourceMapping(qualifierReferenceID); if (mapping != null) qualifierReferenceIDValid = true; break; } } if(qualifierReferenceIDValid) { try { qualifierID = InternalAuthorizationDB.InsertQualifier(q); if(qualifierID != -1) { InternalAuthorizationDB.InsertQualifierHierarchy(qualifierID,parentQualifierID); } } catch(Exception ex) { throw; } } return qualifierID; }
/// <summary> /// Retrieves an experiment's ResultReport from the ESS /// </summary> /// <param name="experimentID"></param> /// <param name="roles"></param> /// <returns>THe ResultStatus or an empty report with status set, when the experiment has not terminated that have not</returns> public static ResultReport GetResultReport(int experimentID) { ResultReport report = null; BrokerDB brokerDB = new BrokerDB(); try { ExperimentAdminInfo expInfo = InternalDataDB.SelectExperimentAdminInfo(experimentID); if (expInfo == null || expInfo.experimentID <= 0) { //experiment does not exist throw new SoapException("Invalid experiment ID. ", SoapException.ServerFaultCode); } else { ProcessAgentInfo ess = brokerDB.GetProcessAgentInfo(expInfo.essID); if(ess.retired){ throw new Exception("The requested ESS has been retired"); } ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); essProxy.AgentAuthHeaderValue = new AgentAuthHeader(); essProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid; essProxy.AgentAuthHeaderValue.coupon = ess.identOut; essProxy.Url = ess.webServiceUrl; Coupon opCoupon = brokerDB.GetEssOpCoupon(expInfo.experimentID, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid); OperationAuthHeader opHeader = new OperationAuthHeader(); opHeader.coupon = opCoupon; essProxy.OperationAuthHeaderValue = opHeader; if ((expInfo.status & StorageStatus.CLOSED) == 0) { ProcessAgentInfo lsInfo = brokerDB.GetProcessAgentInfo(expInfo.agentID); if (lsInfo != null) { if(lsInfo.retired){ throw new Exception("The requested batch LabServer has ben retired."); } BatchLSProxy batchLS_Proxy = new BatchLSProxy(); batchLS_Proxy.AuthHeaderValue = new AuthHeader(); batchLS_Proxy.AuthHeaderValue.identifier = ProcessAgentDB.ServiceGuid; batchLS_Proxy.AuthHeaderValue.passKey = lsInfo.identOut.passkey; batchLS_Proxy.Url = lsInfo.webServiceUrl; // retrieve resultReport from labServer LabExperimentStatus expStatus = batchLS_Proxy.GetExperimentStatus(experimentID); if (expStatus != null) { if ((expStatus.statusReport.statusCode >= 3) && (expStatus.statusReport.statusCode != 6)) { report = batchLS_Proxy.RetrieveResult(experimentID); if (report != null) { ExperimentRecord theRecord = null; List<ExperimentRecord> recordList = new List<ExperimentRecord>(); if (report.experimentResults != null && report.experimentResults.Length > 0) { theRecord = new ExperimentRecord(); theRecord.submitter = lsInfo.agentGuid; theRecord.type = BatchRecordType.RESULT; theRecord.contents = report.experimentResults; theRecord.xmlSearchable = false; recordList.Add(theRecord); } if (report.errorMessage != null && report.errorMessage.Length > 0) { theRecord = new ExperimentRecord(); theRecord.submitter = lsInfo.agentGuid; theRecord.type = BatchRecordType.EXECUTION_ERROR; theRecord.contents = report.errorMessage; theRecord.xmlSearchable = false; recordList.Add(theRecord); } if (report.warningMessages != null && report.warningMessages.Length > 0) { foreach (string s in report.warningMessages) { if (s.Length > 0) { theRecord = new ExperimentRecord(); theRecord.submitter = lsInfo.agentGuid; theRecord.type = BatchRecordType.EXECUTION_WARNING; theRecord.contents = s; theRecord.xmlSearchable = false; recordList.Add(theRecord); } } } if (report.xmlResultExtension != null && report.xmlResultExtension.Length > 0) { theRecord = new ExperimentRecord(); theRecord.submitter = lsInfo.agentGuid; theRecord.type = BatchRecordType.RESULT_EXTENSION; theRecord.contents = report.xmlResultExtension; theRecord.xmlSearchable = true; recordList.Add(theRecord); } if (report.xmlBlobExtension != null && report.xmlBlobExtension.Length > 0) { theRecord = new ExperimentRecord(); theRecord.submitter = lsInfo.agentGuid; theRecord.type = BatchRecordType.BLOB_EXTENSION; theRecord.contents = report.xmlBlobExtension; theRecord.xmlSearchable = true; recordList.Add(theRecord); } if (recordList.Count > 0) { essProxy.AddRecords(experimentID, recordList.ToArray()); } StorageStatus sStatus = essProxy.SetExperimentStatus(experimentID, report.statusCode | StorageStatus.CLOSED); DataStorageAPI.UpdateExperimentStatus(sStatus); } } } } } else { report = new ResultReport(); ExperimentRecord[] records = essProxy.GetRecords(experimentID, null); if (records != null) { List<String> execWarnings = new List<String>(); foreach (ExperimentRecord rec in records) { if (rec.type.CompareTo(BatchRecordType.EXECUTION_ERROR) == 0) { report.errorMessage = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.BLOB_EXTENSION) == 0) { report.xmlBlobExtension = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.RESULT_EXTENSION) == 0) { report.xmlResultExtension = rec.contents; } else if (rec.type.CompareTo(BatchRecordType.EXECUTION_WARNING) == 0) { execWarnings.Add(rec.contents); } else if (rec.type.CompareTo(BatchRecordType.RESULT) == 0) { report.experimentResults = rec.contents; } } if (execWarnings.Count > 0) { report.warningMessages = execWarnings.ToArray(); } } report.statusCode = expInfo.status & StorageStatus.BATCH_MASK; } } } catch (Exception ex) { throw new SoapException(ex.Message + ". " + ex.GetBaseException(), SoapException.ServerFaultCode, ex); } return report; }
protected void Page_Load(object sender, System.EventArgs e) { ticketing = new BrokerDB(); if (Session["UserID"]==null) Response.Redirect("../login.aspx"); //only superusers can view this page if (!Session["GroupName"].ToString().Equals(Group.SUPERUSER)) Response.Redirect("../home.aspx"); labClientIDs = wrapper.ListLabClientIDsWrapper(); labClients = wrapper.GetLabClientsWrapper(labClientIDs); // Set the popup buttons' "CausesValidation" property. // For any button that is related to a popup, you have to set the CausesValidation // propery to false, otherwise // any RequiredFieldValidator control will cause the onclick event to be // comandeered by a routine in ASP.NET's WebValidationUI.js file. // The result would be that the custom onclick for the popup would not fire. btnEditList.CausesValidation = false; btnAddEditResources.CausesValidation = false; btnRemove.CausesValidation = false; // This button enables the popup to fire an event on the caller when the Save button is hit. btnRefresh.CausesValidation = false; // "Are you sure" javascript for Remove button btnRemove.Attributes.Add("onclick", "javascript:if(confirm('Are you sure you want to remove this Lab Client?')== false) return false;"); // This is a hidden input tag. The associatedLabServers popup changes its value using a window.opener call in javascript, // then the GetPostBackEventReference fires the event associated with the btnRefresh button. // The result is that the LabServer repeater (repLabServers) is refreshed when the Save button is clicked // on the popup. hiddenPopupOnSave.Attributes.Add("onpropertychange", Page.GetPostBackEventReference(btnRefresh)); if(!Page.IsPostBack ) { Session.Remove("ClientUssMappingID"); Session.Remove("ClientEssMappingID"); // Load Lab Client dropdown ddlLabClient.Items.Add(new ListItem(" --- select Lab Client --- ", "0")); foreach (LabClient lc in labClients) { ddlLabClient.Items.Add(new ListItem(lc.clientName,lc.clientID.ToString())); } //Put in availabe USS ListItem liHeaderUss = new ListItem("---Select User Side Scheduling Server---", "0"); ddlAssociatedUSS.Items.Add(liHeaderUss); IntTag[] usses = ticketing.GetProcessAgentTagsByType(ProcessAgentType.SCHEDULING_SERVER,ProcessAgentDB.ServiceGuid); foreach (IntTag uss in usses) { ListItem li = new ListItem(uss.tag, uss.id.ToString()); ddlAssociatedUSS.Items.Add(li); } //Put in availabe ESS ListItem liHeaderEss = new ListItem("---Select Experiment Storage Server---", "0"); ddlAssociatedESS.Items.Add(liHeaderEss); IntTag[] esses = ticketing.GetProcessAgentTagsByType(ProcessAgentType.EXPERIMENT_STORAGE_SERVER, ProcessAgentDB.ServiceGuid); foreach (IntTag ess in esses) { ListItem li = new ListItem(ess.tag, ess.id.ToString()); ddlAssociatedESS.Items.Add(li); } //Put in client types string[] clientTypes = InternalAdminDB.SelectLabClientTypes(); foreach (string cType in clientTypes) { ListItem li = new ListItem(cType); ddlClientTypes.Items.Add(li); } // Disable the "Edit Lab Servers" button at first btnEditList.Visible = false; ddlAssociatedESS.Enabled = false; ddlAssociatedUSS.Enabled = false; btnRegisterUSS.Visible = false; btnRegisterESS.Visible = false; btnDissociateUSS.Visible = false; btnDissociateESS.Visible = false; // Reset error/confirmation message lblResponse.Text = ""; lblResponse.Visible = false; } }
protected void displayRecords(long experimentId, string essGuid) { BrokerDB ticketIssuer = new BrokerDB(); ProcessAgentInfo ess = ticketIssuer.GetProcessAgentInfo(essGuid); if (ess == null || ess.retired) { throw new Exception("The ESS is not registered or is retired"); } Coupon opCoupon = ticketIssuer.GetEssOpCoupon(experimentId, TicketTypes.RETRIEVE_RECORDS, 60, ess.agentGuid); if (opCoupon != null) { ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = opCoupon; essProxy.Url = ess.webServiceUrl; essProxy.OperationAuthHeaderValue = header; ExperimentRecord[] records = essProxy.GetRecords(experimentId,null); if (records != null) { StringBuilder buf = null; if (cbxContents.Checked) { buf = new StringBuilder(); foreach (ExperimentRecord rec in records) { buf.AppendLine(rec.contents); } txtExperimentRecords.Text = buf.ToString(); txtExperimentRecords.Visible = true; grvExperimentRecords.Visible = false; } else { dtRecords = new DataTable(); dtRecords.Columns.Add("Seq_Num", typeof(System.Int32)); dtRecords.Columns.Add("Record Type", typeof(System.String)); dtRecords.Columns.Add("Contents", typeof(System.String)); foreach (ExperimentRecord rec in records) { DataRow recTmp = dtRecords.NewRow(); recTmp["Seq_Num"] = rec.sequenceNum; recTmp["Record Type"] = rec.type; recTmp["Contents"] = rec.contents; dtRecords.Rows.InsertAt(recTmp, dtRecords.Rows.Count); } grvExperimentRecords.DataSource = dtRecords; grvExperimentRecords.DataBind(); grvExperimentRecords.Visible = true; txtExperimentRecords.Visible = false; } divRecords.Visible = true; } Blob[] blobs = essProxy.GetBlobs(experimentId); if (blobs != null) { dtBlobs = new DataTable(); dtBlobs.Columns.Add("Blob_ID", typeof(System.Int64)); dtBlobs.Columns.Add("Seq_Num", typeof(System.Int32)); dtBlobs.Columns.Add("MimeType", typeof(System.String)); dtBlobs.Columns.Add("Description", typeof(System.String)); foreach (Blob b in blobs) { DataRow blobTmp = dtBlobs.NewRow(); blobTmp["Blob_ID"] = b.blobId; blobTmp["Seq_Num"] = b.recordNumber; blobTmp["MimeType"] = b.mimeType; blobTmp["Description"] = b.description; dtBlobs.Rows.InsertAt(blobTmp, dtBlobs.Rows.Count); } grvBlobs.DataSource = dtBlobs; grvBlobs.DataBind(); divBlobs.Visible = true; } } }
protected void repAdminURLs_ItemCommand(object source, RepeaterCommandEventArgs e) { refreshUrlRepeater(); if (e.CommandName.Equals("Remove")) { // delete the admin URL BrokerDB issuer = new BrokerDB(); issuer.DeleteAdminURL(Int32.Parse(e.CommandArgument.ToString())); } }
protected void lbxSelectExperiment_SelectedIndexChanged(object sender, System.EventArgs e) { clearExperimentDisplay(); long experimentID = Int64.Parse (lbxSelectExperiment.Items [lbxSelectExperiment.SelectedIndex ].Value); try { ExperimentSummary[] expInfo = wrapper.GetExperimentSummaryWrapper (new long[] {experimentID}); if(expInfo[0] != null) { txtExperimentID.Text = expInfo[0].experimentId.ToString(); txtUsername.Text = expInfo[0].userName ; txtGroupName.Text = expInfo[0].groupName; txtLabServerName.Text = expInfo[0].labServerName; txtClientName.Text = expInfo[0].clientName; //Check if update needed from the ESS if one is used if( expInfo[0].essGuid != null){ int expStatus = expInfo[0].status; if((expStatus == StorageStatus.UNKNOWN || expStatus == StorageStatus.INITIALIZED || expStatus == StorageStatus.OPEN || expStatus == StorageStatus.REOPENED ||expStatus == StorageStatus.RUNNING ||expStatus == StorageStatus.BATCH_QUEUED ||expStatus == StorageStatus.BATCH_RUNNING ||expStatus == StorageStatus.BATCH_TERMINATED ||expStatus == StorageStatus.BATCH_TERMINATED_ERROR)) { // This operation should happen within the Wrapper BrokerDB ticketIssuer = new BrokerDB(); ProcessAgentInfo ess = ticketIssuer.GetProcessAgentInfo(expInfo[0].essGuid); if (ess == null || ess.retired) { throw new Exception("The ESS is not registered or is retired"); } Coupon opCoupon = ticketIssuer.GetEssOpCoupon(expInfo[0].experimentId, TicketTypes.RETRIEVE_RECORDS,60,ess.agentGuid); if (opCoupon != null) { ExperimentStorageProxy essProxy = new ExperimentStorageProxy(); OperationAuthHeader header = new OperationAuthHeader(); header.coupon = opCoupon; essProxy.Url = ess.webServiceUrl; essProxy.OperationAuthHeaderValue = header; StorageStatus curStatus = essProxy.GetExperimentStatus(expInfo[0].experimentId); if (expInfo[0].status != curStatus.status || expInfo[0].recordCount != curStatus.recordCount || expInfo[0].closeTime != curStatus.closeTime) { DataStorageAPI.UpdateExperimentStatus(curStatus); expInfo[0].status = curStatus.status; expInfo[0].recordCount = curStatus.recordCount; expInfo[0].closeTime = curStatus.closeTime; } } } } txtStatus.Text = DataStorageAPI.getStatusString(expInfo[0].status); txtSubmissionTime.Text = DateUtil.ToUserTime(expInfo[0].creationTime,culture,userTZ); if ((expInfo[0].closeTime != null) && (expInfo[0].closeTime != DateTime.MinValue)) { txtCompletionTime.Text = DateUtil.ToUserTime(expInfo[0].closeTime, culture, userTZ); } else{ txtCompletionTime.Text = "Experiment Not Closed!"; } txtRecordCount.Text = expInfo[0].recordCount.ToString(" 0"); txtAnnotation.Text = expInfo[0].annotation; trSaveAnnotation.Visible = true; trDeleteExperiment.Visible = true; trShowExperiment.Visible = (expInfo[0].recordCount > 0); } } catch(Exception ex) { lblResponse.Text = Utilities.FormatErrorMessage("Error retrieving experiment information. " + ex.Message); lblResponse.Visible = true; } }
private void refreshUrlRepeater() { try { BrokerDB ticketIssuer = new BrokerDB(); AdminUrl[] adminUrls = ticketIssuer.RetrieveAdminURLs(paTag.id); adminUrlList = new ArrayList(); foreach (AdminUrl url in adminUrls) { adminUrlList.Add(url); } repAdminURLs.DataSource = adminUrlList; repAdminURLs.DataBind(); } catch (Exception ex) { lblResponse.Text = Utilities.FormatErrorMessage("Cannot list administration URLs. " + ex.GetBaseException()); } }
protected void rbtnSelectType_SelectedIndexChanged(object sender, System.EventArgs e) { ResetState(); //lbxSelectMessage.Items.Clear(); switch (rbtnSelectType.SelectedValue) { case "group": try { ddlMessageTarget.Items .Clear (); ddlMessageTarget.Items .Add(new ListItem("--Select one--",zero)); int[] groupIDs = wrapper.ListGroupIDsWrapper(); Group[] groups=wrapper.GetGroupsWrapper(groupIDs); foreach(Group gr in groups) { //if(!gr.groupName.EndsWith ("request")) if ((gr.groupID > 0) && gr.GroupType.Equals(GroupType.REGULAR) && (!gr.groupName.Equals(Group.ROOT)) && (!gr.groupName.Equals(Group.SUPERUSER)) && (!gr.groupName.Equals(Group.NEWUSERGROUP)) && (!gr.groupName.Equals(Group.ORPHANEDGROUP))) ddlMessageTarget.Items .Add(new ListItem(gr.groupName,gr.groupID.ToString())); } } catch(Exception ex) { string msg = "Exception: Cannot list groups. "+ex.Message+". "+ex.GetBaseException()+"."; lblResponse.Text = Utilities.FormatErrorMessage(msg); lblResponse.Visible = true; } break; case "lab": try { BrokerDB brokerDB = new BrokerDB(); ddlMessageTarget.Items .Clear (); ddlMessageTarget.Items .Add(new ListItem("--Select one--",zero)); int[] labServerIDs = wrapper.ListLabServerIDsWrapper(); DbParameter param = FactoryDB.CreateParameter("@typeMask", ProcessAgentType.AgentType.LAB_SERVER,DbType.Int32); IntTag[] labServers = brokerDB.GetIntTags("GetProcessAgentTagsByTypeMask", param); foreach(IntTag ls in labServers) { if (ls.id > 0) ddlMessageTarget.Items .Add(new ListItem(ls.tag,ls.id.ToString())); } } catch(Exception ex) { string msg = "Exception: Cannot list lab servers. "+ex.Message+"."+ex.GetBaseException()+"."; lblResponse.Text = Utilities.FormatErrorMessage(msg); lblResponse.Visible = true; } break; case "system": { ddlMessageTarget.Items .Clear (); ddlMessageTarget.Items .Add("System"); ddlMessageTarget.Items[0].Selected=true; BuildMsgListBox(SystemMessage.SYSTEM, 0, 0, 0); } break; } }
protected void btnSaveChanges_Click(object sender, System.EventArgs e) { BrokerDB brokerDB = new BrokerDB(); AuthorizationWrapperClass wrapper = new AuthorizationWrapperClass(); if(txtNewPassword.Text.CompareTo(txtConfirmPassword.Text) != 0 ) { lblResponse.Text = Utilities.FormatErrorMessage("Password fields don't match. Try again!"); lblResponse.Visible = true; txtNewPassword.Text = null; txtConfirmPassword.Text = null; } else { //if a field is left blank, it is not updated try { User userInfo = wrapper.GetUsersWrapper(new int[] {Convert.ToInt32(Session["UserID"])})[0]; Authority auth = brokerDB.AuthorityRetrieve(userInfo.authID); if (txtUsername.Text.Trim()=="") { txtUsername.Text = userInfo.userName; } if(txtFirstName.Text.Trim() == "") { txtFirstName.Text = userInfo.firstName ; } if(txtLastName.Text.Trim() == "") { txtLastName.Text = userInfo.lastName ; } if(txtEmail.Text.Trim() == "") { txtEmail.Text = userInfo.email ; } if (userInfo.reason==null) userInfo.reason = ""; if (userInfo.affiliation==null) userInfo.affiliation=""; if (userInfo.xmlExtension==null) userInfo.xmlExtension=""; wrapper.ModifyUserWrapper (userInfo.userID,txtUsername.Text,auth.authorityID,auth.authTypeID, txtFirstName.Text , txtLastName.Text , txtEmail.Text ,userInfo.affiliation, userInfo.reason, userInfo.xmlExtension,userInfo.lockAccount ); lblResponse.Text = Utilities.FormatConfirmationMessage("User \"" + txtUsername.Text + "\" information has been updated."); lblResponse.Visible = true; if (auth.authTypeID == (int) AuthenticationType.AuthTypeID.Native) { if (txtNewPassword.Text != "") { wrapper.SetNativePasswordWrapper(Convert.ToInt32(Session["UserID"]), txtNewPassword.Text); } } if (txtUsername.Text.CompareTo(Session["UserName"].ToString())!= 0) Session["UserName"]= txtUsername.Text; // Send a confirmation message to the user string email; if(txtEmail.Text.Trim() == "") { // use old email if it wasn't changed, new if it was email = userInfo.email; } else { email = txtEmail.Text.Trim(); } if (email != null && email.Length > 0) { MailMessage mail = new MailMessage(); mail.From = registrationMailAddress; mail.To = email; mail.Subject = "[iLabs] Service Broker Account Update Confirmation"; mail.Body = "Your Service Broker account has been updated to the following:\n\r"; mail.Body += "-------------------------------------------------------------\n\r\n\r"; mail.Body += "User Name: " + txtUsername.Text + "\n\r"; mail.Body += "First Name: " + txtFirstName.Text + "\n\r"; mail.Body += "Last Name: " + txtLastName.Text + "\n\r"; mail.Body += "Email: " + txtEmail.Text + "\n\r\n\r"; mail.Body += "For security reasons, your password has not been included in this message." + "\n\r"; SmtpMail.SmtpServer = "127.0.0.1"; try { SmtpMail.Send(mail); } catch(Exception e2) { // if the confirmation message fails, c'est la vie... string msg = "Error sending email notification: (" + e2.Message + ". " + e2.GetBaseException() + "). Contact " + supportMailAddress + "."; lblResponse.Text = Utilities.FormatErrorMessage(msg); lblResponse.Visible = true; } } } catch (Exception ex) { string msg = "Error updating account ("+ex.Message+". "+ex.GetBaseException()+"). Contact " + supportMailAddress + "."; lblResponse.Text = Utilities.FormatErrorMessage(msg); lblResponse.Visible = true; } } }