/// <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(ProcessAgent uss, ProcessAgent lss, string username, int userID, string groupName, 
            string labServerGuid, LabClient labClient, 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, userID, groupName, issuer.GetIssuerGuid(),
                    labServerGuid, labClient.clientGuid, labClient.clientName, labClient.version, uss.webServiceUrl, userTZ);
                string payload2 = factory.createRequestReservationPayload();

                Coupon schedulingCoupon = issuer.CreateTicket(TicketTypes.SCHEDULE_SESSION, uss.agentGuid,
                    issuer.GetIssuerGuid(), duration, payload1);
                issuer.AddTicket(schedulingCoupon, TicketTypes.REQUEST_RESERVATION, lss.agentGuid, uss.agentGuid,
                    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(uss.agentGuid, TicketTypes.SCHEDULE_SESSION).Url;
                schedulingUrl += "?coupon_id=" + couponId + "&issuer_guid=" + issuerGuid + "&passkey=" + passkey;

                return schedulingUrl;
            }
            catch
            {
                throw;
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            int groupID = 0;
            int authID = -1;
            Coupon opCoupon = null;
            string groupName = null;
            lblResponse.Visible = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

                int count = 0;

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

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

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

                if (serverMessages != null && serverMessages.Length > 0)
                {
                    lblServerSystemMessage.Text = "Client/Server Messages:";
                    lblServerSystemMessage.Visible = true;
                    repServerMessage.DataSource = serverMessages;
                    repServerMessage.DataBind();
                }
                else
                {
                    lblServerSystemMessage.Visible = false;
                }
            }
        }
Example #3
0
        /// <summary>
        /// Modified ExecuteExperimentExecutionRecipe inorder to better support interactive applets. 
        /// </summary>
        /// <param name="labServer"></param>
        /// <param name="client"></param>
        /// <param name="startExecution"></param>
        /// <param name="duration"></param>
        /// <param name="userTZ"></param>
        /// <param name="userID"></param>
        /// <param name="groupID"></param>
        /// <param name="groupName"></param>
        /// <returns></returns> added silly bool should be changed
        public IDictionary<string, string> ExecuteExperimentExecutionRecipe(ProcessAgentInfo labServer, LabClient client,
            DateTime startExecution, long duration, int userTZ, int userID, int groupID, string groupName, bool silly)
        {
            BrokerDB brokerDB;
            Coupon coupon;
            // refactored out
            ExecuteExperimentExecutionRecipe(labServer, ref client, ref startExecution, duration, userTZ, userID, groupID, groupName, out brokerDB, out coupon);

            //
            IDictionary<string,string> ht = new Dictionary<string,string>();
            ht["passkey"] = coupon.passkey;
            ht["coupon_id"] = coupon.couponId.ToString();
            ht["issuer_guid"] = brokerDB.GetIssuerGuid();
            //return the appended url
            return ht;
        }
Example #4
0
        private void RefreshClientInfoRepeater()
        {
            // refresh the array of LabClient objects from the database.
            // This insures that any changed ClientInfo arrays (one per LabClient Object)
            // are retrieved.
            labClientIDs = new int[1];
            labClientIDs[0] = labClientID;
            labClients = wrapper.GetLabClientsWrapper(labClientIDs);

            LabClient lc = new LabClient();
            lc = labClients[0];

            clientInfosList.Clear();

            foreach(ClientInfo ci in lc.clientInfos)
            {
                if (!ci.infoURLName.ToUpper().Equals("DOCUMENTATION"))
                    clientInfosList.Add(ci);
            }

            repClientInfo.DataSource = clientInfosList;
            repClientInfo.DataBind();

            // update public clientInfos object
            clientInfos = lc.clientInfos;
            if (clientInfos.Length == 0)
            {
                clientInfos = new ClientInfo[1];
            }
        }
        ///// <summary>
        ///// Creates an ArrayList of LabServer objects.
        ///// Binds the LabServer Repeater to this ArrayList.
        ///// </summary>
        //private void RefreshLabServerRepeater()
        //{
        //    ProcessAgentInfo[]labServers  = AdministrativeAPI.GetLabServersForClient(labClient.clientID);
        //    repLabServers.DataSource = labServers;
        //    repLabServers.DataBind();
        //}
        ///// <summary>
        ///// This is a hidden HTML button that is "clicked" by an event raised 
        ///// by the closing of the associatedLabServers popup.
        ///// It causes the Lab Servers repeater to be refreshed.
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void btnRefresh_ServerClick(object sender, System.EventArgs e)
        //{
        //    lblResponse.Visible = false;
        //    lblResponse.Text = "";
        //    RefreshLabServerRepeater();
        //    RefreshClientInfoRepeater();
        //    LoadFormFields();
        //}
        //private void RefreshClientInfoRepeater()
        //{
        //    // refresh the array of LabClient objects from the database.
        //    // This insures that any changed ClientInfo arrays (one per LabClient Object)
        //    // are retrieved.
        //    if (labClient != null && labClient.clientID > 0)
        //    {
        //        ClientInfo[] clientInfos = AdministrativeAPI.ListClientInfos(labClient.clientID);
        //        ArrayList clientInfosList = new ArrayList();
        //        foreach (ClientInfo ci in clientInfos)
        //        {
        //            clientInfosList.Add(ci);
        //        }
        //        repClientInfo.DataSource = clientInfosList;
        //        repClientInfo.DataBind();
        //        //Disable guid modification
        //        txtClientGuid.ReadOnly = true;
        //        txtClientGuid.Enabled = false;
        //    }
        //}
        /// <summary>
        /// This will remove the client from the database and any ResourceMapping. 
        /// Because of cascading deletes all clientInfos, User's past experiments, and the user's clientItems will also be deleted
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRemove_Click(object sender, System.EventArgs e)
        {
            lblResponse.Visible = false;
            lblResponse.Text = "";

            if (ddlLabClient.SelectedIndex == 0)
            {
                lblResponse.Visible = true;
                lblResponse.Text = Utilities.FormatWarningMessage("Please select a lab client from dropdown list to delete!");
                return;
            }
            else
            {
                labClientID = Convert.ToInt32(ddlLabClient.SelectedValue);
                labClient = AdministrativeAPI.GetLabClient(labClientID);
                if (hasGroups() && labClient.needsScheduling)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatWarningMessage("You may not delete a client that has groups assigned to it and needs scheduling! Please remove the grpoup(s) first.");
                    return;
                }
                StringBuilder message = new StringBuilder();
                int status = 1;
                try
                {
                    int oldEssId = int.Parse(hdnEssID.Value);
                    if (oldEssId > 0)
                    {
                        status = Math.Min(status,dissociateESS(oldEssId, ref message));
                    }
                    int oldUssId = int.Parse(hdnUssID.Value);
                    if (oldUssId > 0)
                    {
                        status = Math.Min(status,dissociateUSS(oldUssId, ref message));
                    }
                    int oldLabServerId = int.Parse(hdnLabServerID.Value);
                    if (oldLabServerId > 0)
                    {
                        status = Math.Min(status,dissociateLS(oldLabServerId, ref message));
                    }
                    wrapper.RemoveLabClientsWrapper(new int[] { labClientID });
                    status = Math.Min(status, 1);
                    message.Append("Lab Client '" + txtLabClientName.Text + "' has been deleted");
                    lblResponse.Visible = true;
                    if(status < 1)
                        lblResponse.Text = Utilities.FormatWarningMessage(message.ToString());
                    else
                        lblResponse.Text = Utilities.FormatConfirmationMessage(message.ToString());
                    InitializeClientDropDown();
                    ClearFormFields();
                }
                catch (Exception ex)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Lab Client " + txtLabClientName.Text + "' cannot be deleted." + ex.GetBaseException());
                }
            }
        }
        /// <summary>
        /// This method loads the text fields on the form from an array of
        /// LabClient objects loaded from the database
        /// </summary>
        private void LoadFormFields()
        {
            ClearFormFields();
            //int labServerID = 0;
            // load the LabClient based on the ddlLabClient.SelectedValue
            labClientID = Convert.ToInt32(ddlLabClient.SelectedValue);
            if (labClientID > 0)
            {
                labClient = AdministrativeAPI.GetLabClient(labClientID);
                if (labClient != null)
                {
                    assocGroupIDs = AdministrativeUtilities.GetLabClientGroups(labClient.clientID, false);
                    txtClientGuid.Text = labClient.clientGuid;

                    if(labClient.clientName != null)
                        txtLabClientName.Text = labClient.clientName;
                    txtVersion.Text = labClient.version;
                    txtShortDesc.Text = labClient.clientShortDescription;
                    txtLongDesc.Text = labClient.clientLongDescription;
                    txtDocURL.Text = labClient.documentationURL;
                    txtContactFirstName.Text = labClient.contactFirstName;
                    txtContactLastName.Text = labClient.contactLastName;
                    txtContactEmail.Text = labClient.contactEmail;

                    cbxIsReentrant.Checked = labClient.IsReentrant;
                    if (labClient.clientType != null && labClient.clientType.Length > 0)
                        ddlClientTypes.SelectedValue = labClient.clientType;
                    txtNotes.Text = labClient.notes;
                    txtLoaderScript.Text = labClient.loaderScript;
                    cbxESS.Checked = labClient.needsESS;
                    hdnNeedsEss.Value = labClient.needsESS ? "1" : zero;
                    cbxScheduling.Checked = labClient.needsScheduling;
                    hdnNeedsUss.Value = labClient.needsScheduling ? "1" : zero;
                    //Check if there is an associated USS and/or ESS => lab experiment needs scheduling and/or storage
                    CheckAssociatedResources(labClient);

                    // NOTE: This code is not currently used, but may return once support for multiple labServers per client is implemented.
                    // Load Lab Server Repeater
                    // RefreshLabServerRepeater();

                    // Load ClientInfo Repeater
                    //RefreshClientInfoRepeater();

                    //// Associated LabServersPopup is currently not used as only one LabServer per client is supported.
                    //// Initialize and load the "Edit Associated Lab Servers" button's
                    //// javascript onclick routine with the correct Lab Client ID in the querystring
                    //string assocPopupScript;
                    //assocPopupScript = "javascript:window.open('assocLabServersPopup.aspx?lc=";
                    //assocPopupScript += labClient.clientID.ToString();
                    //assocPopupScript += "','managelabclients','scrollbars=yes,resizable=yes,width=700,height=400').focus()";
                    //btnEditList.Attributes.Remove("onClick");
                    //btnEditList.Attributes.Add("onClick", assocPopupScript);
                    // End: LabServer Popup code

                    // Initialize and load the "Edit Client Resources" button's
                    // javascript onclick routine with the correct Lab Client ID in the querystring
                    StringBuilder infoPopupScript = new StringBuilder("javascript:window.open('addInfoURLPopup.aspx?lc=");
                    infoPopupScript.Append(labClient.clientID);
                    infoPopupScript.Append("','manageclientinfo','scrollbars=yes,resizable=yes,width=800').focus()");
                    btnAddEditResources.Attributes.Remove("onClick");
                    btnAddEditResources.Attributes.Add("onClick", infoPopupScript.ToString());

                    // Initialize and load the "Edit Associated groups" button's
                    // javascript onclick routine with the correct Lab Client ID in the querystring
                    StringBuilder groupsPopupScript = new StringBuilder("javascript:window.open('manageLabGroups.aspx?lc=");
                    groupsPopupScript.Append(labClient.clientID);
                    groupsPopupScript.Append("','manageLabGroups','scrollbars=yes,resizable=yes,width=800').focus()");
                    btnAssociateGroups.Attributes.Remove("onClick");
                    btnAssociateGroups.Attributes.Add("onClick", groupsPopupScript.ToString());

                    //// Initialize and load the "Edit Metadata" button's
                    // No Longer a popup see btnMetadata_Click
                    //// javascript onclick routine with the correct Lab Client ID in the querystring
                    //StringBuilder metadataPopupScript = new StringBuilder("javascript:window.open('editMetadataPopup.aspx?lc=");
                    //metadataPopupScript.Append(labClient.clientID);
                    //metadataPopupScript.Append("','editMetadataPopup','scrollbars=yes,resizable=yes,width=800').focus()");
                    //btnMetadata.Attributes.Remove("onClick");
                    //btnMetadata.Attributes.Add("onClick", metadataPopupScript.ToString());
                    if (!Session["GroupName"].ToString().Equals(Group.SUPERUSER))
                    btnMetadata.Visible = true;
                    trOptions.Visible = true;
                }
            }
        }
 /// <summary>
 /// Clears the form in preparation for a new record
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void btnNew_Click(object sender, System.EventArgs e)
 {
     lblResponse.Visible = false;
     lblResponse.Text = "";
     labClientID = 0;
     labClient = null;
     ddlLabClient.SelectedIndex = 0;
     //hdnEssID.Value = zero;
     //hdnLabServerID.Value = zero;
     //hdnUssID.Value = zero;
     ClearFormFields();
 }
Example #8
0
        public string CreateClientDescriptor(LabClient client)
        {
            StringBuilder stringBuilder = new StringBuilder();
            try
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.OmitXmlDeclaration = true;
                settings.NewLineOnAttributes = true;
                settings.CheckCharacters = true;

                XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings);

                // write root element
                xmlWriter.WriteStartElement("clientDescriptor");
                //xmlWriter.WriteAttributeString("xmlns", "ns", null, nameSpace);

                if (client.clientGuid != null && client.clientGuid.Length > 0)
                    xmlWriter.WriteElementString("clientGuid", client.clientGuid);
                if (client.clientName != null && client.clientName.Length > 0)

                    xmlWriter.WriteElementString("clientName", client.clientName);
                if (client.version != null && client.version.Length > 0)
                    xmlWriter.WriteElementString("version", client.version);
                if (client.clientShortDescription != null && client.clientShortDescription.Length > 0)

                    xmlWriter.WriteElementString("clientShortDescription", client.clientShortDescription);
                if (client.clientLongDescription != null && client.clientLongDescription.Length > 0)
                    xmlWriter.WriteElementString("clientLongDescription", client.clientLongDescription);
                xmlWriter.WriteElementString("clientType", client.clientType);
                if (client.contactEmail != null && client.contactEmail.Length > 0)
                    xmlWriter.WriteElementString("contactEmail", HttpUtility.HtmlEncode(client.contactEmail));
                if (client.contactFirstName != null && client.contactFirstName.Length > 0)
                    xmlWriter.WriteElementString("contactFirstName", client.contactFirstName);
                if (client.contactLastName != null && client.contactLastName.Length > 0)
                    xmlWriter.WriteElementString("contactLastName", client.contactLastName);
                if (client.loaderScript != null && client.loaderScript.Length > 0)
                    xmlWriter.WriteElementString("loaderScript", client.loaderScript);
                xmlWriter.WriteElementString("needsScheduling", client.needsScheduling.ToString());
                xmlWriter.WriteElementString("needsESS", client.needsESS.ToString());
                xmlWriter.WriteElementString("isReentrant", client.IsReentrant.ToString());
                if (client.notes != null && client.notes.Length > 0)
                    xmlWriter.WriteElementString("notes", client.notes);
                if (client.labServerIDs != null && client.labServerIDs.Length > 0)
                {
                    xmlWriter.WriteStartElement("labServers");
                    for (int i = 0; i < client.labServerIDs.Length; i++)
                    {
                        ProcessAgent server = brokerDb.GetProcessAgent(client.labServerIDs[i]);
                        if (server != null)
                        {
                            xmlWriter.WriteStartElement("labServer");
                            xmlWriter.WriteAttributeString("guid", server.agentGuid);
                            xmlWriter.WriteEndElement();
                        }

                    }
                    xmlWriter.WriteEndElement();

                }
                if (client.clientInfos != null && client.clientInfos.Length > 0)
                {
                    xmlWriter.WriteStartElement("clientInfos");
                    foreach (ClientInfo i in client.clientInfos)
                    {
                        WriteClientInfo(xmlWriter, i);
                    }
                    xmlWriter.WriteEndElement();

                }
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
                return stringBuilder.ToString();
            }
            catch (Exception e)
            {
                Utilities.WriteLog("Create clientDescriptor: " + e.Message);
            }
            return null;
        }
Example #9
0
        protected void btnRegisterUSS_Click(object sender, EventArgs e)
        {
            lblResponse.Visible = false;
            lblResponse.Text = "";

            StringBuilder message = new StringBuilder();
            try
            {
                if (ddlLabClient.SelectedIndex == 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Please save the Lab Client information before attempting to dissociate it from a resource");
                    return;
                }

                if (ddlAssociatedUSS.SelectedIndex == 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Please select a desired USS to be associated with the client.");
                    return;
                }

                LabClient lc = new LabClient();
                lc = labClients[ddlLabClient.SelectedIndex - 1];

                Object keyObj = int.Parse(ddlLabClient.SelectedValue);
                string keyType = ResourceMappingTypes.CLIENT;

                ArrayList valuesList = new ArrayList();
                Object valueObj = null;

                ResourceMappingValue value = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER);
                valuesList.Add(value);

                int ussId = int.Parse(ddlAssociatedUSS.SelectedValue);

                if (ussId > 0)
                {
                    value = new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT, ussId);
                    valuesList.Add(value);

                    value = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE,
                        TicketTypes.GetTicketType(TicketTypes.SCHEDULE_SESSION));
                    valuesList.Add(value);

                    ResourceMappingKey key = new ResourceMappingKey(keyType, keyObj);
                    ResourceMappingValue[] values = (ResourceMappingValue[])valuesList.ToArray((new ResourceMappingValue()).GetType());

                    // Add the mapping to the database & cache
                    ResourceMapping newMapping = ticketing.AddResourceMapping(key, values);

                    // add mapping to qualifier list
                    int qualifierType = Qualifier.resourceMappingQualifierTypeID;
                    string name = ticketing.ResourceMappingToString(newMapping);
                    int qualifierID = AuthorizationAPI.AddQualifier(newMapping.MappingID, qualifierType, name, Qualifier.ROOT);

                    // Moved to ManageLabGroups
                    //Give the Manager Group a Grant "MANAGE_USS_GROUP" on the created resource mapping
                    //int agentID = Convert.ToInt32(ddlAdminGroup.SelectedValue);
                    //string function = Function.manageUSSGroup;
                    //int grantID = wrapper.AddGrantWrapper(agentID, function, qualifierID);

                    Session["ClientUssMappingID"] = newMapping.MappingID;

                    btnRegisterUSS.Visible = false;
                    btnDissociateUSS.Visible = true;
                    ddlAssociatedUSS.Enabled = false;

                    message.AppendLine("User-side Scheduling Server \"" + ddlAssociatedUSS.SelectedItem.Text + "\" succesfully "
                        + "associated with client \"" + ddlLabClient.SelectedItem.Text + "\".");

                    //wrapper.ModifyLabClientWrapper(lc.clientID, lc.clientName, lc.version, lc.clientShortDescription,
                    //    lc.clientLongDescription, lc.notes, lc.loaderScript, lc.clientType,
                    //    lc.labServerIDs, lc.contactEmail, lc.contactFirstName, lc.contactLastName,
                    //    lc.needsScheduling, lc.needsESS, lc.IsReentrant, lc.clientInfos);

                    TicketLoadFactory factory = TicketLoadFactory.Instance();
                    ProcessAgentInfo uss = ticketing.GetProcessAgentInfo(ussId);
                    if (uss.retired)
                    {
                        throw new Exception("The specified USS is retired");
                    }
                    //this should be in a loop
                    for(int i = 0;i<lc.labServerIDs.Length;i++){

                        if (lc.labServerIDs[i] > 0)
                        {
                            ProcessAgentInfo labServer = ticketing.GetProcessAgentInfo(lc.labServerIDs[i]);
                            if (labServer.retired)
                            {
                                throw new Exception("The lab server is retired");
                            }
                            int lssId = ticketing.FindProcessAgentIdForAgent(lc.labServerIDs[i], ProcessAgentType.LAB_SCHEDULING_SERVER);

                            if (lssId > 0)
                            {

                                ProcessAgentInfo lss = ticketing.GetProcessAgentInfo(lssId);
                                if (lss.retired)
                                {
                                    throw new Exception("The LSS is retired");
                                }
                                // The REVOKE_RESERVATION ticket
                                string revokePayload = factory.createRevokeReservationPayload();
                                Coupon ussCoupon = ticketing.CreateTicket(TicketTypes.REVOKE_RESERVATION, uss.agentGuid,
                                    lss.agentGuid, -1L, revokePayload);

                                // Is this in the domain or cross-domain
                                if (lss.domainGuid.Equals(ProcessAgentDB.ServiceGuid))
                                {
                                    // this domain
                                    //Add USS on LSS

                                    //string lssPayload = factory.createAdministerLSSPayload(Convert.ToInt32(Session["UserTZ"]));
                                    //long duration = 60; //seconds for the LSS to redeem the ticket of this coupon and Add LSS Info
                                    //ticketing.AddTicket(lssCoupon, TicketTypes.ADMINISTER_LSS, lss.agentGuid,
                                    //    ticketing.ServiceGuid(), duration, lssPayload);

                                    LabSchedulingProxy lssProxy = new LabSchedulingProxy();
                                    lssProxy.Url = lss.webServiceUrl;
                                    lssProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                                    lssProxy.AgentAuthHeaderValue.coupon = lss.identOut;
                                    lssProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                                    int ussAdded = lssProxy.AddUSSInfo(uss.agentGuid, uss.agentName, uss.webServiceUrl, ussCoupon);
                                    lssProxy.AddExperimentInfo(labServer.agentGuid, labServer.agentName, lc.clientGuid, lc.clientName, lc.version, lc.contactEmail);
                                }
                                else
                                {
                                    // cross-domain
                                    // send consumerInfo to remote SB
                                    int remoteSbId = ticketing.GetProcessAgentID(lss.domainGuid);
                                    message.AppendLine(RegistrationSupport.RegisterClientUSS(remoteSbId, null, lss.agentId, null, labServer.agentId,
                                        ussCoupon, uss.agentId, null, lc.clientID));

                                }
                                //ADD LSS on USS
                                string ussPayload = factory.createAdministerUSSPayload(Convert.ToInt32(Session["UserTZ"]));

                                UserSchedulingProxy ussProxy = new UserSchedulingProxy();
                                ussProxy.Url = uss.webServiceUrl;
                                ussProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                                ussProxy.AgentAuthHeaderValue.coupon = uss.identOut;
                                ussProxy.AgentAuthHeaderValue.agentGuid = ProcessAgentDB.ServiceGuid;
                                int lssAdded = ussProxy.AddLSSInfo(lss.agentGuid, lss.agentName, lss.webServiceUrl);

                                //Add Experiment Information on USS
                                int expInfoAdded = ussProxy.AddExperimentInfo(labServer.agentGuid, labServer.agentName,
                                    lc.clientGuid, lc.clientName, lc.version, lc.contactEmail, lss.agentGuid);

                                // Group Credentials MOVED TO THE MANAGE LAB GROUPS PAGE
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            lblResponse.Visible = true;
            lblResponse.Text = Utilities.FormatConfirmationMessage(message.ToString());
        }
Example #10
0
        protected void btnRegisterESS_Click(object sender, EventArgs e)
        {
            lblResponse.Visible = false;
            lblResponse.Text = "";

            try
            {
                if (ddlLabClient.SelectedIndex == 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Please save the Lab Client information before attempting to associate it with a resource");
                    return;
                }

                if (ddlAssociatedESS.SelectedIndex == 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Please select a desired ESS to be associated with the client.");
                    return;
                }

                LabClient lc = new LabClient();
                lc = labClients[ddlLabClient.SelectedIndex - 1];

                Object keyObj = int.Parse(ddlLabClient.SelectedValue);
                string keyType = ResourceMappingTypes.CLIENT;

                ArrayList valuesList = new ArrayList();
                Object valueObj = null;

                ResourceMappingValue value = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.EXPERIMENT_STORAGE_SERVER);
                valuesList.Add(value);

                value = new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT,
                    int.Parse(ddlAssociatedESS.SelectedValue));
                valuesList.Add(value);

                value = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE,
                    TicketTypes.GetTicketType(TicketTypes.ADMINISTER_EXPERIMENT));
                valuesList.Add(value);

                ResourceMappingKey key = new ResourceMappingKey(keyType, keyObj);
                ResourceMappingValue[] values = (ResourceMappingValue[])valuesList.ToArray((new ResourceMappingValue()).GetType());
                ResourceMapping newMapping = ticketing.AddResourceMapping(key, values);

                // add mapping to qualifier list
                int qualifierType = Qualifier.resourceMappingQualifierTypeID;
                string name = ticketing.ResourceMappingToString(newMapping);
                int qualId = AuthorizationAPI.AddQualifier(newMapping.MappingID, qualifierType, name, Qualifier.ROOT);

                // No Grant required for ESS

                Session["ClientEssMappingID"] = newMapping.MappingID;

                btnRegisterESS.Visible = false;
                btnDissociateESS.Visible = true;
                ddlAssociatedESS.Enabled = false;

                lblResponse.Visible = true;
                lblResponse.Text = Utilities.FormatConfirmationMessage("Experiment Storage Server \"" + ddlAssociatedESS.SelectedItem.Text + "\" succesfully "
                    + "associated with client \"" + ddlLabClient.SelectedItem.Text + "\".");

                //wrapper.ModifyLabClientWrapper(lc.clientID, lc.clientName, lc.version, lc.clientShortDescription,
                //    lc.clientLongDescription, lc.notes, lc.loaderScript, lc.clientType,
                //    lc.labServerIDs, lc.contactEmail, lc.contactFirstName, lc.contactLastName,
                //    lc.needsScheduling, lc.needsESS, lc.IsReentrant, lc.clientInfos);

            }
            catch
            {
                throw;
            }
        }
Example #11
0
        /// <summary>
        /// Creates an ArrayList of LabServer objects.
        /// Binds the LabServer Repeater to this ArrayList.
        /// </summary>
        private void RefreshLabServerRepeater()
        {
            LabClient lc = new LabClient();
            lc = labClients[ddlLabClient.SelectedIndex - 1];

            ArrayList labServersList = new ArrayList();
            labServerIDs = lc.labServerIDs;
            labServers  = wrapper.GetProcessAgentInfosWrapper(labServerIDs);
            foreach(ProcessAgentInfo ls in labServers)
            {
                if(!ls.retired)
                    labServersList.Add(ls);
            }
            repLabServers.DataSource = labServersList;
            repLabServers.DataBind();
        }
Example #12
0
        private void RefreshClientInfoRepeater()
        {
            //LoadFormFields();

            // refresh the array of LabClient objects from the database.
            // This insures that any changed ClientInfo arrays (one per LabClient Object)
            // are retrieved.
            labClientIDs = wrapper.ListLabClientIDsWrapper();
            labClients = wrapper.GetLabClientsWrapper(labClientIDs);

            LabClient lc = new LabClient();
            lc = labClients[ddlLabClient.SelectedIndex - 1];

            ArrayList clientInfosList = new ArrayList();

            foreach (ClientInfo ci in lc.clientInfos)
            {
                if (!ci.infoURLName.ToUpper().Equals("DOCUMENTATION"))
                    clientInfosList.Add(ci);
            }

            repClientInfo.DataSource = clientInfosList;
            repClientInfo.DataBind();
            //Disable guid modification
            txtClientGuid.ReadOnly = true;
            txtClientGuid.Enabled = false;
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (Session["UserID"]==null)
                Response.Redirect("../login.aspx");
            if(Request.Params["lc"] != null)
            labClientID = int.Parse(Request.Params["lc"]);
            labClient = AdministrativeAPI.GetLabClient(labClientID);

            // 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 = AdministrativeAPI.GetLabServersForClient(labClient.clientID);

            // Current Lab Client name
            lblLabClient.Text = labClient.clientName;

            // Error Message
            divErrorMessage.Visible = false;
            lblResponse.Visible = false;

            if(!IsPostBack)
            {
                btnSaveChanges.Enabled = false;
                LoadListBoxes();
            }
        }
Example #14
0
        /*
        /// <summary>
        /// to modify the outgoing passkey
        /// Method name changed from UpdateSBOutgoingPasskey
        /// </summary>
        public static void UpdateLSOutgoingPasskey(int labServerID,string passKey)
        {

            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("ModifyOutPasskey", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@lsID", labServerID));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@passKey", passKey));

            try
            {
                myConnection.Open();
                int i = myCommand.ExecuteNonQuery();
                if(i == 0)
                    throw new Exception ("No record modified exception");
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown in updating outgoing passkey",ex);
            }
            finally
            {
                myConnection.Close();
            }
        }

        /// <summary>
        /// to modify the incoming passkey
        /// Method name changed from UpdateSBIncomingPasskey
        /// </summary>
        public static void UpdateLSIncomingPasskey(int labServerID,string passKey)
        {

            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("ModifyInPasskey", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@lsID", labServerID));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@passKey", passKey));

            try
            {
                myConnection.Open();
                int i = myCommand.ExecuteNonQuery();
                if(i == 0)
                    throw new Exception ("No record modified exception");
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown in updating incoming passkey",ex);
            }
            finally
            {
                myConnection.Close();
            }
        }

        /// <summary>
        /// to select the passkey
        /// </summary>
        public static string selectSBOutgoingPasskey(int labServerID)
        {
            string passKey = null;
            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("SelectOutPasskey", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@lsID", labServerID));

            try
            {
                myConnection.Open();
                passKey = myCommand.ExecuteScalar().ToString ();
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown in selecting passkey",ex);
            }
            finally
            {
                myConnection.Close();
            }
            return passKey;
        }

        /// <summary>
        /// to select the passkey
        /// </summary>
        public static string selectSBIncomingPasskey(int labServerID)
        {
            string passKey = null;
            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("SelectInPasskey", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@lsID", labServerID));

            try
            {
                myConnection.Open();
                passKey = myCommand.ExecuteScalar().ToString ();
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown in selecting passkey",ex);
            }
            finally
            {
                myConnection.Close();
            }
            return passKey;
        }
        */
        /* !------------------------------------------------------------------------------!
         *							CALLS FOR LAB CLIENTS
         * !------------------------------------------------------------------------------!
         */
        /// <summary>
        /// to add a lab client
        /// The order in which lab servers are associated with this client is the array order
        /// </summary>
        public static int InsertLabClient(LabClient lc)
        {
            int clientID = -1;

            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("AddLabClient", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand, "@guid", lc.clientGuid, DbType.AnsiString,50));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand, "@labClientName", lc.clientName, DbType.String,256));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand, "@shortDescription", lc.clientShortDescription, DbType.String,256));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand, "@longDescription", lc.clientLongDescription, DbType.String));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@version", lc.version,DbType.String,50));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@loaderScript", lc.loaderScript, DbType.String,2000));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@clientType", lc.clientType, DbType.AnsiString,100));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@email",lc.contactEmail, DbType.String,256 ));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@firstName",lc.contactFirstName, DbType.String,128 ));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@lastName",lc.contactLastName, DbType.String,128 ));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@notes", lc.notes, DbType.String));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@needsScheduling", lc.needsScheduling, DbType.Boolean));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@needsESS", lc.needsESS, DbType.Boolean));
            myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@isReentrant", lc.IsReentrant, DbType.Boolean));

            //Encoding transaction here
            //Alternatively a dataset can be used, but it's not preferred bcos it's inefficient?
            DbTransaction transaction;

            myConnection.Open();
            transaction = myConnection.BeginTransaction();
            myCommand.Transaction = transaction;

            try
            {

                clientID = Int32.Parse ( myCommand.ExecuteScalar().ToString ());
                lc.clientID = clientID;

                /*-- ASSOCIATED LAB SERVERS --*/
                if(lc.labServerIDs != null)
                {
                    myCommand.Parameters.Clear();
                    myCommand.CommandText = "AddLabServerClient";
                    myCommand.CommandType = CommandType.StoredProcedure ;

                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand, "@labClientID", clientID, DbType.Int32));
                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@labServerID", null, DbType.Int32));
                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@displayOrder", null, DbType.Int32));

                    int count=1;
                    foreach (int id in lc.labServerIDs )
                    {
                        myCommand.Parameters["@labServerID"].Value = id;
                        myCommand.Parameters["@displayOrder"].Value = count;

                        int i = myCommand.ExecuteNonQuery();

                        if (i!=0)
                            count+=1;
                    }
                }

                /*-- ASSOCIATED INFO URLS --*/
                if(lc.clientInfos != null)
                {
                    myCommand.Parameters.Clear();
                    myCommand.CommandText = "AddClientInfo" ;
                    myCommand.CommandType = CommandType.StoredProcedure ;

                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand, "@labClientID", lc.clientID, DbType.Int32));
                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@infoURL", null, DbType.String,512));
                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@infoName", null, DbType.String,256));
                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@description", null, DbType.String));
                    myCommand.Parameters.Add(FactoryDB.CreateParameter(myCommand,"@displayOrder", null, DbType.Int32));

                    int count=1;
                    foreach (ClientInfo c in lc.clientInfos )
                    {
                        //if (c != null) - this doesn't work because ClientInfo is a struct
                        if ((c.infoURL!=null)&&(c.infoURL.CompareTo("")!=0))
                        {
                            myCommand.Parameters["@infoURL"].Value = c.infoURL;
                            myCommand.Parameters["@infoName"].Value = c.infoURLName;
                            myCommand.Parameters["@description"].Value = c.description;
                            myCommand.Parameters["@displayOrder"].Value = count;
                            //myCommand.Parameters["@displayOrder"].Value = c.displayOrder;

                            int i = myCommand.ExecuteNonQuery();

                            if (i!=0)
                                count+=1;
                        }
                    }
                }

                transaction.Commit();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new Exception("Exception thrown in inserting lab server to client",ex);
            }
            finally
            {
                myConnection.Close();
            }
            return clientID;
        }
Example #15
0
        /// <summary>
        /// to retrieve lab client metadata for lab clients specified by array of lab client IDs 
        /// </summary>
        public static LabClient[] SelectLabClients( int[] clientIDs )
        {
            LabClient[] lc = new LabClient[clientIDs.Length];
            for (int i=0; i<clientIDs.Length ; i++)
            {
                lc[i] = new LabClient();
            }

            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("RetrieveLabClient", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters .Add(FactoryDB.CreateParameter(myCommand, "@labClientID",null, DbType.Int32));

            try
            {
                myConnection.Open ();

                for (int i =0; i < clientIDs.Length ; i++)
                {
                    myCommand.Parameters["@labClientID"].Value = clientIDs[i];

                    // get labclient info from table lab_clients
                    DbDataReader myReader = myCommand.ExecuteReader ();
                    while(myReader.Read ())
                    {
                        lc[i].clientID = clientIDs[i];

                        if(myReader["lab_client_name"] != System.DBNull.Value )
                            lc[i].clientName = (string) myReader["lab_client_name"];
                        if(myReader["short_description"] != System.DBNull.Value )
                            lc[i].clientShortDescription = (string) myReader["short_description"];
                        if(myReader["long_description"] != System.DBNull.Value )
                            lc[i].clientLongDescription = (string) myReader["long_description"];
                        if(myReader["version"] != System.DBNull.Value )
                            lc[i].version = (string) myReader["version"];
                        if(myReader["loader_script"] != System.DBNull.Value )
                            lc[i].loaderScript= (string) myReader["loader_script"];
                        if(myReader["description"] != System.DBNull.Value )
                            lc[i].clientType= (string) myReader["description"];
                        if(myReader["contact_email"] != System.DBNull .Value )
                            lc[i].contactEmail= (string) myReader["contact_email"];
                        if(myReader["contact_first_name"]!= System.DBNull.Value)
                            lc[i].contactFirstName = (string) myReader["contact_first_name"];
                        if(myReader["contact_last_name"]!= System.DBNull.Value)
                            lc[i].contactLastName = (string) myReader["contact_last_name"];
                        if(myReader["notes"]!= System.DBNull.Value)
                            lc[i].notes = (string) myReader["notes"];
                        lc[i].needsScheduling = Convert.ToBoolean(myReader["needsScheduling"]);
                        lc[i].needsESS = Convert.ToBoolean(myReader["needsESS"]);
                        lc[i].IsReentrant = Convert.ToBoolean(myReader["isReentrant"]);
                        if (myReader["Client_Guid"] != System.DBNull.Value)
                            lc[i].clientGuid = (string)myReader["Client_Guid"];
                        /*if(myReader["date_created"] != System.DBNull .Value )
                            lc[i].= (string) myReader["date_created"];*/

                        //added by Karim
                        //if(myReader["info_URL"] != System.DBNull .Value )
                        //	lc[i].infoURL= (string) myReader["info_URL"];

                    }
                    myReader.Close ();
                }
                //Retrieve  lab servers for a client

                ArrayList lsIDs = new ArrayList();

                DbCommand myCommand2 = FactoryDB.CreateCommand("RetrieveClientServerIDs", myConnection);
                myCommand2.CommandType = CommandType.StoredProcedure;
                myCommand2.Parameters .Add(FactoryDB.CreateParameter(myCommand2,"@labClientID",null,DbType.Int32));

                for (int i =0; i < clientIDs.Length ; i++)
                {
                    myCommand2.Parameters["@labClientID"].Value = clientIDs[i];
                    DbDataReader myReader2 = myCommand2.ExecuteReader ();

                    while(myReader2.Read ())
                    {
                        if(myReader2["agent_id"] != System.DBNull.Value )
                            lsIDs.Add(Convert.ToInt32(myReader2["agent_id"]));
                    }

                    myReader2.Close();

                    // Convert to an int array and add to the current LabClient object
                    lc[i].labServerIDs = Utilities.ArrayListToIntArray(lsIDs);
                    lsIDs.Clear();
                }

                //Retrieve info urls for a client

                ArrayList infoURLs = new ArrayList();

                myCommand2 = FactoryDB.CreateCommand("RetrieveClientInfo", myConnection);
                myCommand2.CommandType = CommandType.StoredProcedure;
                myCommand2.Parameters .Add(FactoryDB.CreateParameter(myCommand2,"@labClientID",null, DbType.Int32));

                for (int i =0; i < clientIDs.Length ; i++)
                {
                    myCommand2.Parameters["@labClientID"].Value = clientIDs[i];

                    DbDataReader myReader2 = myCommand2.ExecuteReader ();

                    while(myReader2.Read ())
                    {
                        ClientInfo c = new ClientInfo();
                        if(myReader2["info_url"] != System.DBNull.Value )
                            c.infoURL = (string) myReader2["info_url"];
                        if(myReader2["info_name"] != System.DBNull.Value )
                            c.infoURLName  = (string) myReader2["info_name"];
                        if(myReader2["client_info_id"] != System.DBNull.Value )
                            c.clientInfoID = Convert.ToInt32( myReader2["client_info_id"]);
                        if(myReader2["description"] != System.DBNull.Value )
                            c.description = ((string) myReader2["description"]);
                        if(myReader2["display_order"] != System.DBNull.Value )
                            c.displayOrder = (int) myReader2["display_order"];

                        infoURLs.Add(c);
                    }

                    myReader2.Close();

                    // Converting to a clientInfo array
                    lc[i].clientInfos = new ClientInfo [infoURLs.Count];
                    for (int j=0;j <infoURLs.Count ; j++)
                    {
                        lc[i].clientInfos[j] = (ClientInfo) (infoURLs[j]);
                    }
                    infoURLs.Clear();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown SelectLabClients",ex);
            }
            finally
            {
                myConnection.Close ();
            }

            return lc;
        }
        /// <summary>
        /// to retrieve lab client metadata for lab clients specified by array of lab client IDs 
        /// </summary>
        public static LabClient SelectLabClient(string clientGuid)
        {
            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("Client_RetrieveByGuid", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters.Add(FactoryDB.CreateParameter( "@clientGuid",clientGuid, DbType.String,50));
            LabClient lc = new LabClient();
            try
            {
                myConnection.Open();

                // get labclient info from table lab_clients
                DbDataReader myReader = myCommand.ExecuteReader();
                while (myReader.Read())
                {
                    if (myReader["client_ID"] != System.DBNull.Value)
                        lc.clientID= (int)myReader["client_ID"];
                    if (myReader["lab_client_name"] != System.DBNull.Value)
                        lc.clientName = (string)myReader["lab_client_name"];
                    if (myReader["short_description"] != System.DBNull.Value)
                        lc.clientShortDescription = (string)myReader["short_description"];
                    if (myReader["long_description"] != System.DBNull.Value)
                        lc.clientLongDescription = (string)myReader["long_description"];
                    if (myReader["version"] != System.DBNull.Value)
                        lc.version = (string)myReader["version"];
                    if (myReader["loader_script"] != System.DBNull.Value)
                        lc.loaderScript = (string)myReader["loader_script"];
                    if (myReader["description"] != System.DBNull.Value)
                        lc.clientType = (string)myReader["description"];
                    if (myReader["contact_email"] != System.DBNull.Value)
                        lc.contactEmail = (string)myReader["contact_email"];
                    if (myReader["contact_first_name"] != System.DBNull.Value)
                        lc.contactFirstName = (string)myReader["contact_first_name"];
                    if (myReader["contact_last_name"] != System.DBNull.Value)
                        lc.contactLastName = (string)myReader["contact_last_name"];
                    if (myReader["notes"] != System.DBNull.Value)
                        lc.notes = (string)myReader["notes"];
                    lc.needsScheduling = Convert.ToBoolean(myReader["needsScheduling"]);
                    lc.needsESS = Convert.ToBoolean(myReader["needsESS"]);
                    lc.IsReentrant = Convert.ToBoolean(myReader["isReentrant"]);
                    if (myReader["Client_Guid"] != System.DBNull.Value)
                        lc.clientGuid = (string)myReader["Client_Guid"];
                    if (myReader["Documentation_URL"] != System.DBNull.Value)
                        lc.documentationURL = (string)myReader["Documentation_URL"];

                }
                myReader.Close();

                ////Retrieve  lab servers for a client

                //ArrayList lsIDs = new ArrayList();

                //DbCommand myCommand2 = FactoryDB.CreateCommand("LabServerClient_RetrieveServerIDs", myConnection);
                //myCommand2.CommandType = CommandType.StoredProcedure;
                //myCommand2.Parameters.Add(FactoryDB.CreateParameter(myCommand2, "@labClientID", lc.clientID, DbType.Int32));

                //DbDataReader myReader2 = myCommand2.ExecuteReader();

                //while (myReader2.Read())
                //{
                //    if (myReader2["agent_id"] != System.DBNull.Value)
                //        lsIDs.Add(Convert.ToInt32(myReader2["agent_id"]));
                //}

                //myReader2.Close();

                //// Convert to an int array and add to the current LabClient object
                //lc.labServerIDs = Utilities.ArrayListToIntArray(lsIDs);

                ////Retrieve info urls for a client

                //ArrayList infoURLs = new ArrayList();

                //myCommand2 = FactoryDB.CreateCommand("ClientInfo_Retrieve", myConnection);
                //myCommand2.CommandType = CommandType.StoredProcedure;
                //myCommand2.Parameters.Add(FactoryDB.CreateParameter(myCommand2, "@labClientID", lc.clientID, DbType.Int32));

                //DbDataReader myReader3 = myCommand2.ExecuteReader();

                //while (myReader3.Read())
                //{
                //    ClientInfo c = new ClientInfo();
                //    if (myReader3["info_url"] != System.DBNull.Value)
                //        c.infoURL = (string)myReader3["info_url"];
                //    if (myReader3["info_name"] != System.DBNull.Value)
                //        c.infoURLName = (string)myReader3["info_name"];
                //    if (myReader3["client_info_id"] != System.DBNull.Value)
                //        c.clientInfoID = Convert.ToInt32(myReader3["client_info_id"]);
                //    if (myReader3["description"] != System.DBNull.Value)
                //        c.description = ((string)myReader3["description"]);
                //    if (myReader3["display_order"] != System.DBNull.Value)
                //        c.displayOrder = (int)myReader3["display_order"];

                //    infoURLs.Add(c);
                //}

                //myReader2.Close();

                //// Converting to a clientInfo array
                //lc.clientInfos = new ClientInfo[infoURLs.Count];
                //for (int j = 0; j < infoURLs.Count; j++)
                //{
                //    lc.clientInfos[j] = (ClientInfo)(infoURLs[j]);
                //}
            }

            catch (Exception ex)
            {
                throw new Exception("Exception thrown SelectLabClients", ex);
            }
            finally
            {
                myConnection.Close();
            }

            return lc;
        }
        /// <summary>
        /// to retrieve lab client metadata for lab clients specified by array of lab client IDs 
        /// </summary>
        public static LabClient[] SelectLabClients( int[] clientIDs )
        {
            List<LabClient> clients = new List<LabClient>();

            DbConnection myConnection = FactoryDB.GetConnection();
            DbCommand myCommand = FactoryDB.CreateCommand("Client_Retrieve", myConnection);
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Parameters .Add(FactoryDB.CreateParameter( "@labClientID",null, DbType.Int32));

            try
            {
                myConnection.Open ();

                for (int i =0; i < clientIDs.Length ; i++)
                {
                    myCommand.Parameters["@labClientID"].Value = clientIDs[i];

                    // get labclient info from table lab_clients
                    DbDataReader myReader = myCommand.ExecuteReader ();
                    while(myReader.Read ())
                    {
                        LabClient lc = new LabClient();
                        lc.clientID = clientIDs[i];

                        if(myReader["lab_client_name"] != System.DBNull.Value )
                            lc.clientName = (string) myReader["lab_client_name"];
                        if(myReader["short_description"] != System.DBNull.Value )
                            lc.clientShortDescription = (string) myReader["short_description"];
                        if(myReader["long_description"] != System.DBNull.Value )
                            lc.clientLongDescription = (string) myReader["long_description"];
                        if(myReader["version"] != System.DBNull.Value )
                            lc.version = (string) myReader["version"];
                        if(myReader["loader_script"] != System.DBNull.Value )
                            lc.loaderScript= (string) myReader["loader_script"];
                        if(myReader["description"] != System.DBNull.Value )
                            lc.clientType= (string) myReader["description"];
                        if(myReader["contact_email"] != System.DBNull .Value )
                            lc.contactEmail= (string) myReader["contact_email"];
                        if(myReader["contact_first_name"]!= System.DBNull.Value)
                            lc.contactFirstName = (string) myReader["contact_first_name"];
                        if(myReader["contact_last_name"]!= System.DBNull.Value)
                            lc.contactLastName = (string) myReader["contact_last_name"];
                        if(myReader["notes"]!= System.DBNull.Value)
                            lc.notes = (string) myReader["notes"];
                        lc.needsScheduling = Convert.ToBoolean(myReader["needsScheduling"]);
                        lc.needsESS = Convert.ToBoolean(myReader["needsESS"]);
                        lc.IsReentrant = Convert.ToBoolean(myReader["isReentrant"]);
                        if (myReader["Client_Guid"] != System.DBNull.Value)
                            lc.clientGuid = (string)myReader["Client_Guid"];
                        if (myReader["Documentation_URL"] != System.DBNull.Value)
                            lc.documentationURL = (string)myReader["Documentation_URL"];
                        clients.Add(lc);

                    }
                    myReader.Close ();
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Exception thrown SelectLabClients",ex);
            }
            finally
            {
                myConnection.Close ();
            }
            clients.Sort();
            return clients.ToArray();;
        }
Example #18
0
        protected void btnDissociateESS_Click(object sender, EventArgs e)
        {
            lblResponse.Visible = false;
            lblResponse.Text = "";

            try
            {
                if (ddlLabClient.SelectedIndex == 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Please save the Lab Client information before attempting to dissociate it from a resource");
                    return;
                }

                if (ddlAssociatedESS.SelectedIndex == 0 || ddlLabClient.SelectedIndex == 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Please select a desired ESS to be dissociated from the client.");
                    return;
                }

                LabClient lc = new LabClient();
                lc = labClients[ddlLabClient.SelectedIndex - 1];

                ticketing.DeleteResourceMapping((int) Session["ClientEssMappingID"]);
                btnRegisterESS.Visible = true;
                btnDissociateESS.Visible = false;
                Session.Remove("ClientEssMappingID");
                lblResponse.Visible = true;
                lblResponse.Text = Utilities.FormatConfirmationMessage("Experiment Storage Server \"" + ddlAssociatedESS.SelectedItem.Text + "\" succesfully "
                    + "dissociated from client \"" + ddlLabClient.SelectedItem.Text + "\".");

                ddlAssociatedESS.Enabled = true;
                ddlAssociatedESS.SelectedIndex = 0;
            }
            catch
            {
                throw;
            }
        }
Example #19
0
        //Checks whether there are a USS and/or an ESS associated with the selected client
        private void CheckAssociatedResources(LabClient client)
        {
            int clientID = client.clientID;

            if (client.needsScheduling)
            {
                int ussId = 0;
                 ResourceMappingValue [] ussValues = new ResourceMappingValue[2];

                 ussValues[0] = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER);
                 ussValues[1] = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE,
                        TicketTypes.GetTicketType(TicketTypes.SCHEDULE_SESSION));
                List<ResourceMapping> ussList = ResourceMapManager.Find(
                    new ResourceMappingKey(ResourceMappingTypes.CLIENT,clientID),ussValues);
                if(ussList != null && ussList.Count > 0){
                    foreach(ResourceMapping rm in ussList){
                        for(int i=0; i<rm.values.Length;i++){
                            if(rm.values[i].Type == ResourceMappingTypes.PROCESS_AGENT){
                                ussId = (int) rm.values[i].Entry;
                                Session["ClientUssMappingID"] = rm.MappingID;
                                break;
                            }
                        }
                    }
                }
                if (ussId > 0)
                {
                    //ResourceMappingValue [] ussValues = new ResourceMappingValue[2];
                    //ussValues[0] = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER);
                    ////valuesList.Add(new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT, ussId));
                    //ussValues[1] = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE,
                    //    TicketTypes.GetTicketType(TicketTypes.SCHEDULE_SESSION));
                    //ResourceMappingValue[] valuesForKey = (ResourceMappingValue[])valuesList.ToArray((new ResourceMappingValue()).GetType());

                    //foreach (DictionaryEntry entry in mappingsTable)
                    //{
                    //    if (ticketing.EqualMappingValues((ResourceMappingValue[])entry.Value, valuesForKey))
                    //        (int)entry.Key;
                    //}

                    //int[] id = { ticketing.GetProcessAgentID(uss.agentGuid) };
                    //IntTag[] ussTag = ticketing.GetProcessAgentTags(id);
                    btnRegisterUSS.Visible = false;
                    btnDissociateUSS.Visible = true;
                    ddlAssociatedUSS.SelectedValue = ussId.ToString();
                    ddlAssociatedUSS.Enabled = false;
                }

                else
                {
                    btnRegisterUSS.Visible = true && client.labServerIDs.Length > 0;
                    btnDissociateUSS.Visible = false;
                    ddlAssociatedUSS.Enabled = true && client.labServerIDs.Length > 0;
                    Session.Remove("ClientUssMappingID");
                }
            }
            else{
                btnRegisterUSS.Visible = false;
                btnDissociateUSS.Visible = false;
                ddlAssociatedUSS.Enabled = false;
                Session.Remove("ClientUssMappingID");

            }
            if(client.needsESS){
               int essId = 0;
                 ResourceMappingValue [] essValues = new ResourceMappingValue[2];

                 essValues[0] = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.EXPERIMENT_STORAGE_SERVER);
                 essValues[1] = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE,
                        TicketTypes.GetTicketType(TicketTypes.ADMINISTER_EXPERIMENT));
                List<ResourceMapping> essList = ResourceMapManager.Find(
                    new ResourceMappingKey(ResourceMappingTypes.CLIENT,clientID),essValues);
                if(essList != null && essList.Count > 0){
                    foreach(ResourceMapping rm in essList){
                        for(int j=0; j<rm.values.Length;j++){
                            if(rm.values[j].Type == ResourceMappingTypes.PROCESS_AGENT){
                                essId = (int) rm.values[j].Entry;
                                Session["ClientEssMappingID"] = rm.MappingID;
                                break;
                            }
                        }
                    }
                }

                if (essId > 0)
                {
                    //int[] id = { ticketing.GetProcessAgentID(ess.agentGuid) };
                    btnRegisterESS.Visible = false;
                    btnDissociateESS.Visible = true;
                    ddlAssociatedESS.SelectedValue = essId.ToString();
                    ddlAssociatedESS.Enabled = false;
                }

                else
                {
                    btnRegisterESS.Visible = true;
                    btnDissociateESS.Visible = false;
                    ddlAssociatedESS.Enabled = true;
                    Session.Remove("ClientEssMappingID");
                }
            }

            else
            {

                btnRegisterESS.Visible = false;
                btnDissociateESS.Visible = false;
                ddlAssociatedESS.Enabled = false;

                Session.Remove("ClientEssMappingID");

            }
        }
Example #20
0
        /// <summary>
        /// This method loads the text fields on the form from an array of
        /// LabClient objects loaded from the database
        /// </summary>
        private void LoadFormFields()
        {
            ClearFormFields();
            // load values from the LabClient object whose array index matches
            // the dropdown (offset by 1, for the "Select" line at the top of the dropdown)
            LabClient lc = new LabClient();
            lc = labClients[ddlLabClient.SelectedIndex - 1];
            txtClientGuid.Text = lc.clientGuid;
            if (lc.clientGuid != null && lc.clientGuid.Length > 1)
            {
                txtClientGuid.ReadOnly = true;
                txtClientGuid.Enabled = false;
                btnGuid.Visible = false;
            }
            else
            {
                txtClientGuid.ReadOnly = false;
                txtClientGuid.Enabled = true;
                btnGuid.Visible = true;
            }
            txtLabClientName.Text = lc.clientName;
            txtVersion.Text = lc.version;
            txtShortDesc.Text = lc.clientShortDescription;
            txtLongDesc.Text = lc.clientLongDescription;
            txtContactFirstName.Text = lc.contactFirstName;
            txtContactLastName.Text = lc.contactLastName;
            txtContactEmail.Text = lc.contactEmail;
            cbxScheduling.Checked = lc.needsScheduling;
            cbxESS.Checked = lc.needsESS;
            cbxIsReentrant.Checked = lc.IsReentrant;

            ddlClientTypes.Items.Clear();
            string[] clientTypes = InternalAdminDB.SelectLabClientTypes();

            foreach (string cType in clientTypes)
            {
                ListItem li = new ListItem (cType);
                if (cType.Equals(lc.clientType))
                    li.Selected=true;
                ddlClientTypes.Items.Add(li);
            }

            // the Documentation URL is in an array of ClientInfo objects,
            // which is itself part of the LabClient object

            // Commented this out in the ASPX page, since this information is
            // duplicated in the ClientInfo repeater.
            // Also, there is no obvious way to handle multiple lines here.
            foreach(ClientInfo ci in lc.clientInfos)
            {
                if (ci.infoURLName.ToUpper().Equals("DOCUMENTATION"))
                    txtDocURL.Text = ci.infoURL;
                break;
            }

            txtNotes.Text = lc.notes;
            txtLoaderScript.Text = lc.loaderScript;

            //Check if there is an associated USS and/or ESS => lab experiment needs scheduling and/or storage
            CheckAssociatedResources(lc);

            // Load Lab Server Repeater
            RefreshLabServerRepeater();

            // Load ClientInfo Repeater
            RefreshClientInfoRepeater();

            // Initialize and load the "Edit Associated Lab Servers" button's
            // javascript onclick routine with the correct Lab Client ID in the querystring
            string assocPopupScript;
            assocPopupScript = "javascript:window.open('assocLabServersPopup.aspx?lc=";
            assocPopupScript += lc.clientID.ToString();
            assocPopupScript += "','managelabclients','scrollbars=yes,resizable=yes,width=700,height=400').focus()";
            btnEditList.Attributes.Remove("onClick");
            btnEditList.Attributes.Add("onClick", assocPopupScript);

            // Initialize and load the "Edit Associated Lab Servers" button's
            // javascript onclick routine with the correct Lab Client ID in the querystring
            string infoPopupScript = "javascript:window.open('addInfoURLPopup.aspx?lc=";
            infoPopupScript += lc.clientID.ToString();
            infoPopupScript += "','manageclientinfo','scrollbars=yes,resizable=yes,width=800,height=600').focus()";
            btnAddEditResources.Attributes.Remove("onClick");
            btnAddEditResources.Attributes.Add("onClick", infoPopupScript);

            // Initialize and load the "Edit Associated groups" button's
            // javascript onclick routine with the correct Lab Client ID in the querystring
            string groupsPopupScript = "javascript:window.open('manageLabGroups.aspx?lc=";
            groupsPopupScript += lc.clientID.ToString();
            groupsPopupScript += "','manageclientinfo','scrollbars=yes,resizable=yes,width=800,height=600').focus()";
            btnAssociateGroups.Attributes.Remove("onClick");
            btnAssociateGroups.Attributes.Add("onClick", groupsPopupScript);
        }
        //Checks whether there are a USS and/or an ESS associated with the selected client
        private void CheckAssociatedResources(LabClient client)
        {
            if (client == null)
                return;
            int labServerID = 0;
            int lssId = 0;
            int ussId = 0;
            int essId = 0;

            //cbxScheduling.Checked = client.needsScheduling;
            //cbxESS.Checked = client.needsESS;

            ProcessAgentInfo[] labServers = AdministrativeAPI.GetLabServersForClient(client.clientID);
            if (labServers != null && labServers.Length > 0 && labServers[0].agentId > 0)
            {
                labServerID = labServers[0].agentId;
                if (labServerID > 0)
                {
                    lssId = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.PROCESS_AGENT,
                        labServerID, ProcessAgentType.LAB_SCHEDULING_SERVER);
                }
            }
            hdnLabServerID.Value = labServerID.ToString();
            ddlLabServer.SelectedValue = hdnLabServerID.Value;
            ussId = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.CLIENT,
                   client.clientID, ProcessAgentType.SCHEDULING_SERVER);
            ddlAssociatedUSS.SelectedValue = ussId.ToString();
            hdnUssID.Value = ussId.ToString();
            essId = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.CLIENT, client.clientID,
                    ProcessAgentType.EXPERIMENT_STORAGE_SERVER);
            ddlAssociatedESS.SelectedValue = essId.ToString();
            hdnEssID.Value = essId.ToString();
            if (client.needsESS)
            {
                btnRegisterESS.Visible = true;

                if (essId > 0)
                {
                    btnRegisterESS.Text = "Dissociate";
                    ddlAssociatedESS.Visible = false;
                    txtAssociatedESS.Visible = true;
                    txtAssociatedESS.Text = ddlAssociatedESS.SelectedItem.Text;
                }
                else
                {

                    btnRegisterESS.Text = "Register";
                    //btnRegisterESS.Visible = true;
                    ddlAssociatedESS.Visible = true;
                    txtAssociatedESS.Visible = false;
                }
            }
            else // ESS Not needed
            {
                btnRegisterESS.Visible = false;
                ddlAssociatedESS.Visible = true;
                txtAssociatedESS.Visible = false;
            }

            if (labServerID  > 0)
            {
                ddlLabServer.Visible = false;
                txtLabServer.Visible = true;
                txtLabServer.Text = ddlLabServer.SelectedItem.Text;
                btnRegisterLS.Text = "Dissociate";
                txtLsUrl.Text = labServers[0].webServiceUrl;
            }
            else
            {
                ddlLabServer.Visible = true;
                txtLabServer.Visible = false;
                btnRegisterLS.Text = "Register";
            }
            btnRegisterLS.Visible = true;
            if (client.needsScheduling)
            {

                btnRegisterUSS.Visible = true;
                if (ussId > 0)
                {
                    btnRegisterUSS.Text = "Dissociate";
                    ddlAssociatedUSS.Visible = false;
                    txtAssociatedUSS.Visible = true;
                    txtAssociatedUSS.Text = ddlAssociatedUSS.SelectedItem.Text;
                }
                else
                {
                    if (Convert.ToInt32(ddlLabServer.SelectedValue) > 0)
                    {
                        btnRegisterUSS.Text = "Register";
                        ddlAssociatedUSS.Visible = true;
                        txtAssociatedUSS.Visible = false;

                    }
                }
            } // End needsScheduling
            else
            {
                ddlAssociatedUSS.Visible = true;
                txtAssociatedUSS.Visible = false;
                btnRegisterUSS.Text = "Register";
            }

            if (hasGroups())
            {
                btnRegisterLS.Enabled = false;
                btnRegisterLS.ToolTip = "You may not modify the LabServer while groups are associated with the client.";
                cbxScheduling.Enabled = false;
                btnRegisterUSS.Enabled = false;
                btnRegisterUSS.ToolTip = "You may not modify Scheduling while groups are associated with the client.";
                cbxScheduling.ToolTip = "You may not modify Scheduling while groups are associated with the client.";
            }
            else
            {
                btnRegisterLS.Enabled = true;
                btnRegisterLS.ToolTip = "";
                cbxScheduling.Enabled = true;
                btnRegisterUSS.Enabled = true;
                btnRegisterUSS.ToolTip = "";
                cbxScheduling.ToolTip = "";
            }

            if (labServerID == 0 && essId == 0 && ussId == 0 && !hasGroups())
            {
                txtClientGuid.ReadOnly = false;
                txtClientGuid.BackColor = enabled;
                btnGuid.Visible = true;
            }
            else
            {
                txtClientGuid.ReadOnly = true;
                txtClientGuid.BackColor = disabled;
                btnGuid.Visible = false;
            }
            // Check if we can assign groups, or if groups are assigned display button
            if (labServerID > 0)
            {
                if (!hasGroups() && client.needsScheduling)
                {
                    btnAssociateGroups.Visible = (lssId > 0 && ussId > 0) ? true : false;
                }
                else
                {
                    btnAssociateGroups.Visible = true;
                    btnAssociateGroups.Enabled = true;
                }
            }
            // for testing
            //btnAssociateGroups.Visible = true;
            //btnAssociateGroups.Enabled = true;
        }
Example #22
0
        protected void ddlLabClient_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            int id = int.Parse(ddlLabClient.SelectedValue);
            if (id > 0)
            {
                LabClient[] clients = wrapper.GetLabClientsWrapper(new int[] { id });
                if (clients.Length > 0 && clients[0].clientID > 0)
                {
                    theClient = clients[0];
                }
                else
                {
                    theClient = new LabClient();
                    repLabServers.DataSource = "";
                    repLabServers.DataBind();

                    repESS.DataSource = "";
                    repESS.DataBind();

                    repUSS.DataSource = "";
                    repUSS.DataBind();
                }

                // Now that the Lab Client is known the associated/available Group
                // ListBoxes can be loaded, along with the Lab Server Repeater
                LoadListBoxes();
                RefreshLabServerRepeater();
                RefreshUssAndEssRepeaters();
                RefreshAdminUserGroupsRepeater();

                //btnSaveChanges.Enabled = true;
            }
            else
            {
                //lbxAssociated.Items.Clear();
                //lbxAvailable.Items.Clear();
                repLabServers.DataSource = "";
                repLabServers.DataBind();

                repESS.DataSource = "";
                repESS.DataBind();

                repUSS.DataSource = "";
                repUSS.DataBind();

                //btnSaveChanges.Enabled = false;
            }
        }
        /*
                // this from the popup and needs to be changed 2011/01/10 PHB
                /// <summary>
                /// Save Button.
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                protected void btnSaveLabServerChanges_Click(object sender, System.EventArgs e)
                {
                    //load the labServerIDs integer array from the Associated Lab Servers listbox
                    labServerIDs = new int[lbxAssociated.Items.Count];
                    for (int i = 0; i < lbxAssociated.Items.Count; i++)
                    {
                        labServerIDs[i] = int.Parse(lbxAssociated.Items[i].Value);
                    }

                    // Update the Lab Client Record with the new Lab Server list (labServerIDs)
                    try
                    {
                        //1. find groups that can access this lab server
                        int[] groupIDs = AdministrativeUtilities.GetLabClientGroups(labClientID);

                        ArrayList oldUseLSGrants = new ArrayList();
                        // First delete all "uselabserver" grants for the groups that can access the old set of lab servers
                        foreach (int groupID in groupIDs)
                        {
                            foreach (ProcessAgentInfo pa in AssocLabServers)
                            {
                                int qID = AuthorizationAPI.GetQualifierID(pa.agentId, Qualifier.labServerQualifierTypeID);
                                int[] oldLSGrants = AuthorizationAPI.FindGrants(groupID, Function.useLabServerFunctionType, qID);
                                foreach (int oldGrant in oldLSGrants)
                                    oldUseLSGrants.Add(oldGrant);
                            }
                        }

                        // remove all the grants
                        int[] unremovedGrants = AuthorizationAPI.RemoveGrants(Utilities.ArrayListToIntArray(oldUseLSGrants));

                        ////Change the labclient's list of lab servers
                        //wrapper.ModifyLabClientWrapper(labClientID, labClient.clientName, labClient.version,
                        //    labClient.clientShortDescription, labClient.clientLongDescription,
                        //    labClient.notes, labClient.loaderScript, labClient.clientType,
                        //    labServerIDs, labClient.contactEmail, labClient.contactFirstName,
                        //    labClient.contactLastName, labClient.needsScheduling, labClient.needsESS,
                        //    labClient.IsReentrant, labClient.clientInfos);

                        // Create the javascript which will cause a page refresh event to fire on the popup's parent page
                        string jScript;
                        jScript = "<script language=javascript> window.opener.Form1.hiddenPopupOnSave.value='1';";
                        jScript += "window.close();</script>";
                        Page.RegisterClientScriptBlock("postbackScript", jScript);

                        // add uselabserver grants for agents that have uselabclientgrants

                        //1. assign uselabserver grants for each group
                        foreach (int labServerID in labServerIDs)
                        {
                            int qID = AuthorizationAPI.GetQualifierID(labServerID, Qualifier.labServerQualifierTypeID);
                            foreach (int groupID in groupIDs)
                                AuthorizationAPI.AddGrant(groupID, Function.useLabServerFunctionType, qID);
                        }

                        lblResponse.Visible = true;
                        lblResponse.Text = Utilities.FormatConfirmationMessage("The labclient '" + labClient + "' has successfully been modified.");
                        btnSaveChanges.Enabled = false;
                    }
                    catch (Exception ex)
                    {
                        divErrorMessage.Visible = true;
                        lblResponse.Visible = true;
                        lblResponse.Text = "Cannot update Lab Client. " + ex.Message;
                    }
                }
         * */
        protected void btnRegisterUSS_Click(object sender, EventArgs e)
        {
            int status = 1;
            int result = 1;
            labClientID = Convert.ToInt32(ddlLabClient.SelectedValue);
            if (labClientID > 0)
                labClient = AdministrativeAPI.GetLabClient(labClientID);
            StringBuilder message = new StringBuilder();
            lblResponse.Visible = false;
            lblResponse.Text = "";
            int oldUssId = int.Parse(hdnUssID.Value);
            int ussId = int.Parse(ddlAssociatedUSS.SelectedValue);
            if (btnRegisterUSS.Text.CompareTo("Register") == 0)
            {
                if (oldUssId != ussId)
                {
                    if (oldUssId > 0)
                    {
                        result = dissociateUSS(oldUssId, ref message);
                        status = Math.Min(status, result);
                    }
                    status = registerUSS(ussId, ref message);
                }
            }
            else if (btnRegisterUSS.Text.CompareTo("Dissociate") == 0)
            {
                result = dissociateUSS(oldUssId, ref message);
                status = Math.Min(status, result);
            }
            if (message.Length > 0)
            {
                lblResponse.Visible = true;
                if (status > 0)
                {
                    lblResponse.Text = Utilities.FormatConfirmationMessage(message.ToString());
                }
                else if (status < 0)
                {
                    lblResponse.Text = Utilities.FormatErrorMessage(message.ToString());
                }
                else
                {
                    lblResponse.Text = Utilities.FormatWarningMessage(message.ToString());
                }
            }
            LoadFormFields();
        }
Example #24
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            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");

            //RefreshAdminUserGroupsRepeater();

            if (!IsPostBack)
            {
                // Error Message
                lblResponse.Visible = false;
                InitializeDropDown();
                if (Request.Params["lc"] != null && Request.Params["lc"].Length > 0)
                {
                    labClientID = int.Parse(Request.Params["lc"]);
                    if (labClientID > 0)
                    {
                        LabClient[] clients = wrapper.GetLabClientsWrapper(new int[] { labClientID });
                        if (clients.Length > 0)
                        {
                            theClient = clients[0];
                        }

                        ddlLabClient.SelectedValue = labClientID.ToString();
                        ddlLabClient.Enabled = false;
                        // Now that the Lab Client is known the associated/available Group
                        // ListBoxes can be loaded, along with the Lab Server Repeater
                        LoadListBoxes();
                        RefreshLabServerRepeater();
                        RefreshUssAndEssRepeaters();
                        RefreshAdminUserGroupsRepeater();

                        //btnSaveChanges.Enabled = true;
                    }
                }

                // Save Button
                //btnSaveChanges.Enabled = false;

                //RefreshAdminUserGroupsRepeater();

            }
            else
            {
                int id = int.Parse(ddlLabClient.SelectedValue);
                if (id > 0)
                {
                    LabClient[] clients = wrapper.GetLabClientsWrapper(new int[] { id });
                    if (clients.Length > 0 && clients[0].clientID > 0)
                    {
                        theClient = clients[0];
                    }
                }
            }
        }
        /// <summary>
        /// The Save Button method.
        /// The index of the Lab Client dropdown will be used to determine whether 
        /// this is a new (0) or an existing (>0) Lab Client.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSaveChanges_Click(object sender, System.EventArgs e)
        {
            lblResponse.Visible = false;
            lblResponse.Text = "";
            StringBuilder message = new StringBuilder();
            int status = 1;
            int result = 1;
            int labServerID = 0;
            int lssID = 0;
            if (txtVersion.Text == null || txtVersion.Text.Equals(""))
            {
                status = Math.Min(status, 0);
                message.AppendLine("You must specify a version for the client!<br/>");
            }
            if (txtClientGuid.Text == null || txtClientGuid.Text.Equals(""))
            {
                status = Math.Min(status, 0);
                message.AppendLine("You must specify a GUID for the client!<br/>");
            }
            if (txtClientGuid.Text.Length > 50)
            {
                status = Math.Min(status, 0);
                message.AppendLine("The GUID is too long, the maximun number of characters is 50!<br/>");
            }
            if (txtLoaderScript.Text == null || txtLoaderScript.Text.Equals(""))
            {
                status = Math.Min(status, 0);
                message.AppendLine("You must specify a loader script for the client!<br/>");
            }
            if (ddlClientTypes.SelectedIndex <= 0)
            {
                status = Math.Min(status, 0);
                message.AppendLine("You must specify a Client Type!<br/>");
            }
            if (status < 1)
            {
                lblResponse.Text = Utilities.FormatWarningMessage(message.ToString());
                lblResponse.Visible = true;
                return;
            }
            if (ddlLabClient.SelectedIndex == 0)
            {
                ///////////////////////////////////////////////////////////////
                /// ADD a new Lab Client                                     //
                ///////////////////////////////////////////////////////////////

                // Add the Lab Client
                try
                {
                    labClientID = wrapper.AddLabClientWrapper(txtClientGuid.Text, txtLabClientName.Text, txtVersion.Text,
                        txtShortDesc.Text, txtLongDesc.Text, ddlClientTypes.SelectedItem.Text, txtLoaderScript.Text, txtDocURL.Text,
                        txtContactEmail.Text, txtContactFirstName.Text, txtContactLastName.Text, txtNotes.Text,
                        cbxESS.Checked, cbxScheduling.Checked, cbxIsReentrant.Checked);
                    if (labClientID > 0)
                    {
                        labClient = AdministrativeAPI.GetLabClient(labClientID);
                        message.AppendLine("Registering Lab Client: " + labClient.clientName + ".<br/>");
                        InitializeClientDropDown();
                        ddlLabClient.SelectedValue = labClientID.ToString();
                    }
                    labServerID = Convert.ToInt32(ddlLabServer.SelectedValue);
                    if (labServerID > 0)
                    {
                        result = registerLS(labServerID, ref message);
                        if (result > 0)
                        {
                            hdnLabServerID.Value = labServerID.ToString();
                            message.AppendLine("Associating Lab Server: " + ddlLabServer.SelectedItem.Text + ".<br/>");
                            status = Math.Min(status, result);
                        }
                        else
                        {
                            message.AppendLine("Unable to associate Lab Server: " + ddlLabServer.SelectedItem.Text + ".<br/>");
                            status = Math.Min(status, 0);
                        }
                    }
                    if (cbxESS.Checked)
                    {
                        int essId = Convert.ToInt32(ddlAssociatedESS.SelectedValue);
                        if (essId > 0)
                        {
                            status = Math.Min(status, registerESS(essId, ref message));
                            message.AppendLine("Associating ESS: " + ddlAssociatedESS.SelectedItem.Text + ".<br/>");
                            status = Math.Min(status, result);
                        }
                    }
                    if (cbxScheduling.Checked)
                    {
                        int ussId = Convert.ToInt32(ddlAssociatedUSS.SelectedValue);
                        if (ussId > 0)
                        {
                            if (labServerID > 0)
                            {
                                lssID = ResourceMapManager.FindResourceProcessAgentID(ResourceMappingTypes.PROCESS_AGENT,
                                labServerID, ProcessAgentType.LAB_SCHEDULING_SERVER);
                                if (lssID > 0)
                                {
                                    result = registerUSS(ussId, ref message);
                                    status = Math.Min(status, result);
                                    message.AppendLine("Associating USS: " + ddlAssociatedUSS.SelectedItem.Text + ".<br/>");
                                }
                                else
                                {
                                    message.AppendLine("You must assign a lab scheduling server before you may register a Scheduling Server!<br/>");
                                    status = Math.Min(status, 0);
                                }
                            }
                            else
                            {
                                message.AppendLine("You must assign a Lab Server and Lab Scheduling Server before you may register a User Scheduling Server!<br/>");
                                status = Math.Min(status, 0);
                            }
                        }
                    }
                }
                catch (AccessDeniedException ex)
                {
                    lblResponse.Visible = true;
                    message.AppendLine(ex.Message + ". " + ex.GetBaseException());
                    lblResponse.Text = Utilities.FormatErrorMessage(message.ToString());
                    return;
                }

                // If successful...
                if (labClientID > 0)
                {
                    lblResponse.Visible = true;
                    message.AppendLine("Lab Client " + txtLabClientName.Text + " has been added.");
                    lblResponse.Text = Utilities.FormatConfirmationMessage(message.ToString());
                    //// set dropdown to newly created Lab Client.
                    //InitializeClientDropDown();
                    //ddlLabClient.SelectedValue = labClientID.ToString();
                    // Prepare record for editing
                    LoadFormFields();
                }
                else // cannot create lab client
                {
                    lblResponse.Visible = true;
                    message.AppendLine("Cannot create Lab Client " + txtLabClientName.Text + ".");
                    lblResponse.Text = Utilities.FormatErrorMessage(message.ToString());
                }
                //Disable guid modification
                //txtClientGuid.ReadOnly = true;
                ////txtClientGuid.Enabled = false;
                // Enable the button that pops up the Associated Lab Server edit page
                //btnEditList.Visible = true;
            }
            else
            ///////////////////////////////////////////////////////////////
            /// MODIFY an existing Lab Client                            //
            /// Note: Modify only changes the primary attributes of      //
            /// the client, resourceMapped values use the butttons.      //
            ///////////////////////////////////////////////////////////////
            {
                // Save the index
                string savedSelectedValue = ddlLabClient.SelectedValue;

                // obtain information not edited in the text boxes from the array of LabClient objects
                labClientID = Convert.ToInt32(ddlLabClient.SelectedValue);

                // Modify the Lab Client Record
                try
                {
                    //LabClient lc = labClients[ddlLabClient.SelectedIndex -1];

                    wrapper.ModifyLabClientWrapper(labClientID, txtClientGuid.Text, txtLabClientName.Text, txtVersion.Text,
                        txtShortDesc.Text, txtLongDesc.Text, ddlClientTypes.SelectedItem.Text,
                        txtLoaderScript.Text, txtDocURL.Text,
                        txtContactEmail.Text, txtContactFirstName.Text, txtContactLastName.Text, txtNotes.Text,
                        cbxESS.Checked, cbxScheduling.Checked, cbxIsReentrant.Checked);
                    labClient = AdministrativeAPI.GetLabClient(labClientID);
            /***********
                    // Add support for Modified LabServer, Ess & Uss
                    int currentLS = Convert.ToInt32(hdnLabServerID.Value);
                    int lsId = Convert.ToInt32(ddlLabServer.SelectedValue);
                    if (currentLS != lsId)
                    {
                        if (currentLS > 0)
                        {
                            result = dissociateLS(currentLS, ref message);
                            status = Math.Min(status, result);
                        }
                        if (lsId > 0)
                        {
                            result = registerLS(lsId, ref message);
                            status = Math.Min(status, result);
                        }
                    }
                    int currentESS = Convert.ToInt32(hdnEssID.Value);
                    int essId = Convert.ToInt32(ddlAssociatedESS.SelectedValue);
                    if ((!labClient.needsESS && currentESS > 0) || (currentESS != essId))
                    {
                        if (currentESS > 0)
                        {
                            result = dissociateESS(currentESS, ref message);
                            status = Math.Min(status, result);
                        }
                    }
                    if (labClient.needsESS)
                    {
                        if (essId > 0)
                        {
                            result = registerESS(essId, ref message);
                            status = Math.Min(status, result);
                        }
                    }
                    int currentUSS = Convert.ToInt32(hdnUssID.Value);
                    int ussId = Convert.ToInt32(ddlAssociatedUSS.SelectedValue);
                    if ((!labClient.needsScheduling && currentUSS > 0) || (currentUSS != ussId))
                    {
                        if (currentUSS > 0)
                        {
                            result = dissociateUSS(currentUSS, ref message);
                            status = Math.Min(status, result);
                        }
                    }
                    if (labClient.needsScheduling)
                    {
                        if (ussId > 0)
                        {
                            result = registerUSS(ussId, ref message);
                            status = Math.Min(status, result);
                        }
                    }
             * ****************/

                    // Reload the Lab Client dropdown
                    InitializeClientDropDown();
                    ddlLabClient.SelectedValue = savedSelectedValue;
                    LoadFormFields();
                    //Disable guid modification
                    txtClientGuid.ReadOnly = true;
                    //txtClientGuid.Enabled = false;
                    lblResponse.Visible = true;
                    message.Insert(0, "Lab Client " + txtLabClientName.Text + " has been modified.<br/>");
                    if (status > 0)
                    {
                        lblResponse.Text = Utilities.FormatConfirmationMessage(message.ToString());
                    }
                    else if (status < 0)
                    {
                        lblResponse.Text = Utilities.FormatErrorMessage(message.ToString());
                    }
                    else
                    {
                        lblResponse.Text = Utilities.FormatWarningMessage(message.ToString());
                    }
                }
                catch (Exception ex)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatErrorMessage("Lab Client " + txtLabClientName.Text + " could not be modified." + ex.GetBaseException());
                }
            }
        }
Example #26
0
        // Error recovery must be added to this method
        protected void btnSaveChange_Click(object sender, EventArgs e)
        {
            int id = int.Parse(ddlLabClient.SelectedValue);
            if (id > 0)
            {
                LabClient[] clients = wrapper.GetLabClientsWrapper(new int[] { id });
                if (clients.Length > 0 && clients[0].clientID > 0)
                {
                    theClient = clients[0];
                }
            }
            // objects used in try block may be required for recovery if  errors
            bool noError = true;
            ProcessAgentInfo labServer = null;
            ProcessAgentInfo uss = null;
            ProcessAgentInfo lss = null;
            long rmUss = 0;

            lblResponse.Visible = false;
            lblResponse.Text = "";
            try
            {
                if (ddlUserGroup.SelectedIndex <= 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatWarningMessage("Please select a user group from the corresponding drop-down list.");
                    return;
                }
                int groupID = Convert.ToInt32(ddlUserGroup.SelectedValue);
                if (groupID <= 0)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatWarningMessage("The user group is invalid.");
                    return;
                }
                //Get the user Group Name to be displayed in the repeater
                Group[] userGroup = wrapper.GetGroupsWrapper(new int[] { groupID });
                string userGroupName = userGroup[0].GroupName;

                if (theClient.labServerIDs != null && theClient.labServerIDs.Length > 0)
                {
                    labServer = issuer.GetProcessAgentInfo(theClient.labServerIDs[0]);
                }
                if (labServer == null)
                {
                    lblResponse.Visible = true;
                    lblResponse.Text = Utilities.FormatWarningMessage("Lab Client should first be associated with a Lab Server");
                    return;
                }

                if (theClient.needsScheduling)
                {
                    if (ddlAdminGroup.SelectedIndex <= 0 || ddlUserGroup.SelectedIndex <= 0)
                    {
                        lblResponse.Visible = true;
                        lblResponse.Text = Utilities.FormatWarningMessage("Please select a user and management group from the corresponding drop-down lists.");
                        return;
                    }
                    int manageID = Convert.ToInt32(ddlAdminGroup.SelectedValue);
                    if (manageID <= 0)
                    {
                        lblResponse.Visible = true;
                        lblResponse.Text = Utilities.FormatWarningMessage("The management group is invalid.");
                        return;
                    }

                    int ussId = issuer.FindProcessAgentIdForClient(theClient.clientID, ProcessAgentType.SCHEDULING_SERVER);
                    if (ussId <= 0)
                    {
                        lblResponse.Visible = true;
                        lblResponse.Text = Utilities.FormatWarningMessage("Lab Client should first be associated with a USS");
                        return;
                    }
                    int lssId = issuer.FindProcessAgentIdForAgent(theClient.labServerIDs[0], ProcessAgentType.LAB_SCHEDULING_SERVER);
                    if (lssId <= 0)
                    {
                        lblResponse.Visible = true;
                        lblResponse.Text = Utilities.FormatWarningMessage("Lab Server should first be associated with an LSS");
                        return;
                    }

                    else
                    {

                        uss = issuer.GetProcessAgentInfo(ussId);
                        if (uss.retired)
                        {
                            throw new Exception("The USS is retired");
                        }
                        lss = issuer.GetProcessAgentInfo(lssId);
                        if (lss.retired)
                        {
                            throw new Exception("The LSS is retired");
                        }

                        //Object keyObj = groupID;
                        //string keyType = ResourceMappingTypes.GROUP;
                        ResourceMappingKey key = new ResourceMappingKey(ResourceMappingTypes.GROUP, groupID);
                        ResourceMappingValue[] values = new ResourceMappingValue[3];
                        values[0] = new ResourceMappingValue(ResourceMappingTypes.CLIENT, theClient.clientID);
                        values[1] = new ResourceMappingValue(ResourceMappingTypes.TICKET_TYPE,
                            TicketTypes.GetTicketType(TicketTypes.MANAGE_USS_GROUP));
                        values[2] = new ResourceMappingValue(ResourceMappingTypes.GROUP,manageID);

                        //values[0] = new ResourceMappingValue(ResourceMappingTypes.RESOURCE_TYPE, ProcessAgentType.SCHEDULING_SERVER);
                        //values[1] = new ResourceMappingValue(ResourceMappingTypes.PROCESS_AGENT, ussId);

                        ResourceMapping newMapping = issuer.AddResourceMapping(key, values);
                        rmUss = newMapping.MappingID;

                        // add mapping to qualifier list
                        int qualifierType = Qualifier.resourceMappingQualifierTypeID;
                        string name = issuer.ResourceMappingToString(newMapping);
                        int qualifierID = AuthorizationAPI.AddQualifier(newMapping.MappingID, qualifierType, name, Qualifier.ROOT);

                        //Give the Manager Group a Grant "MANAGE_USS_GROUP" on the created resource mapping
                        string function = Function.manageUSSGroup;
                        int grantID = wrapper.AddGrantWrapper(manageID, function, qualifierID);

                        //Get the management Group Name to be displayed in the repeater
                        Group[] adminGroup = wrapper.GetGroupsWrapper(new int[] { manageID });
                        string adminGroupName = adminGroup[0].GroupName;

                        //Create the Map between user and management group
                        GroupManagerUserMap groupMap = new GroupManagerUserMap(adminGroupName, userGroupName, grantID, newMapping.MappingID);

                        TicketLoadFactory factory = TicketLoadFactory.Instance();
                        //long duration = 60;
                        // Get this SB's domain Guid
                        string domainGuid = ProcessAgentDB.ServiceGuid;
                        string sbName = ProcessAgentDB.ServiceAgent.agentName;

                        //Add Credential set on the USS

                        //string ussPayload = factory.createAdministerUSSPayload(Convert.ToInt32(Session["userTZ"]));
                        //Coupon ussCoupon = issuer.CreateTicket(TicketTypes.ADMINISTER_USS, uss.agentGuid,
                        //    issuer.GetIssuerGuid(), duration, ussPayload);
                        UserSchedulingProxy ussProxy = new UserSchedulingProxy();
                        ussProxy.Url = uss.webServiceUrl;
                        ussProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                        ussProxy.AgentAuthHeaderValue.coupon = uss.identOut;
                        ussProxy.AgentAuthHeaderValue.agentGuid = domainGuid;

                        ussProxy.AddCredentialSet(domainGuid, sbName, userGroupName);

                        // Check for existing RevokeReservation ticket redeemer = USS, sponsor = LSS
                        Coupon[] revokeCoupons = issuer.RetrieveIssuedTicketCoupon(
                            TicketTypes.REVOKE_RESERVATION, uss.agentGuid, lss.agentGuid);
                        Coupon revokeCoupon = null;
                        if (revokeCoupons != null && revokeCoupons.Length > 0)
                        {
                            revokeCoupon = revokeCoupons[0];
                        }
                        else
                        {
                            // Create RevokeReservation ticket
                            revokeCoupon = issuer.CreateTicket(TicketTypes.REVOKE_RESERVATION,
                                 uss.agentGuid, lss.agentGuid, -1L, factory.createRevokeReservationPayload());
                        }

                        //Add Credential set on the LSS

                        // check if this domain
                        if (ProcessAgentDB.ServiceGuid.Equals(lss.domainGuid))
                        {
                            LabSchedulingProxy lssProxy = new LabSchedulingProxy();
                            lssProxy.Url = lss.webServiceUrl;
                            lssProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                            lssProxy.AgentAuthHeaderValue.coupon = lss.identOut;
                            lssProxy.AgentAuthHeaderValue.agentGuid = domainGuid;
                            // Add the USS to the LSS, this may be called multiple times with duplicate data
                            lssProxy.AddUSSInfo(uss.AgentGuid, uss.agentName, uss.webServiceUrl, revokeCoupon);
                            int credentialSetAdded = lssProxy.AddCredentialSet(domainGuid,
                                sbName, userGroupName, uss.agentGuid);
                        }
                        else
                        { // Cross-Domain Registration needed
                            ProcessAgentInfo remoteSB = issuer.GetProcessAgentInfo(lss.domainGuid);
                            if(remoteSB.retired){
                                throw new Exception("The remote service broker is retired");
                            }
                            ResourceDescriptorFactory resourceFactory = ResourceDescriptorFactory.Instance();
                            string ussDescriptor = resourceFactory.CreateProcessAgentDescriptor(ussId);
                            string lssDescriptor = resourceFactory.CreateProcessAgentDescriptor(lssId);
                            string groupDescriptor = resourceFactory.CreateGroupCredentialDescriptor(domainGuid, sbName, userGroupName, uss.agentGuid, lss.agentGuid);

                            ServiceDescription[] info = new ServiceDescription[3];
                            info[0] = new ServiceDescription(null, revokeCoupon, ussDescriptor);
                            info[1] = new ServiceDescription(null, null, lssDescriptor);
                            info[2] = new ServiceDescription(null, null, groupDescriptor);

                            ProcessAgentProxy sbProxy = new ProcessAgentProxy();
                            sbProxy.AgentAuthHeaderValue = new AgentAuthHeader();
                            sbProxy.AgentAuthHeaderValue.agentGuid = domainGuid;
                            sbProxy.AgentAuthHeaderValue.coupon = remoteSB.identOut;
                            sbProxy.Url = remoteSB.webServiceUrl;
                            sbProxy.Register(Utilities.MakeGuid(), info);
                        }
                    }
                }

                /*Update Lab Client grants*/

                //Get qualifier for labclient
                int lcQualifierID = AuthorizationAPI.GetQualifierID(theClient.clientID, Qualifier.labClientQualifierTypeID);
                //Get all "uselabclient" grants for this labclient
                int[] lcGrantIDs = wrapper.FindGrantsWrapper(-1, Function.useLabClientFunctionType, lcQualifierID);
                Grant[] lcGrants = wrapper.GetGrantsWrapper(lcGrantIDs);
                //Get list of agents that can use labclient
                ArrayList lcAgents = new ArrayList();
                foreach (Grant g in lcGrants)
                    lcAgents.Add(g.agentID);

                //if that agent doesn't already have the uselabclient permission
                if (!lcAgents.Contains(groupID))
                    //add lab client grant
                    wrapper.AddGrantWrapper(groupID, Function.useLabClientFunctionType, lcQualifierID);

                /*Update Lab Servers grant*/

                //Update grants for each of the associated lab servers
                foreach (int lsID in theClient.labServerIDs)
                {
                    //Get qualifier for labserver
                    int lsQualifierID = AuthorizationAPI.GetQualifierID(lsID, Qualifier.labServerQualifierTypeID);
                    //Get all "uselabserver" grants for this labserver
                    int[] lsGrantIDs = wrapper.FindGrantsWrapper(-1, Function.useLabServerFunctionType, lsQualifierID);
                    Grant[] lsGrants = wrapper.GetGrantsWrapper(lsGrantIDs);
                    //Get list of agents that can use labserver
                    ArrayList lsAgents = new ArrayList();
                    foreach (Grant g in lsGrants)
                        lsAgents.Add(g.agentID);

                    //int groupID = Convert.ToInt32(ddlUserGroup.SelectedValue);

                    //if that agent doesn't already have the uselabclient permission
                    if (!lsAgents.Contains(groupID))
                        //add lab server grant
                        wrapper.AddGrantWrapper(groupID, Function.useLabServerFunctionType, lsQualifierID);
                }

                //Refresh the repeater
                RefreshAdminUserGroupsRepeater();
                LoadListBoxes();

                lblResponse.Visible = true;
                lblResponse.Text = Utilities.FormatConfirmationMessage("Lab client (& corresponding lab servers) successfully updated. ");
            }
            catch (Exception ex)
            {
                lblResponse.Visible = true;
                lblResponse.Text = Utilities.FormatErrorMessage("Cannot update Lab Client. " + ex.GetBaseException());
            }
        }
Example #27
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="labServer"></param>
        /// <param name="client"></param>
        /// <param name="startExecution"></param>
        /// <param name="duration"></param>
        /// <param name="userTZ"></param>
        /// <param name="userID"></param>
        /// <param name="groupID"></param>
        /// <param name="groupName"></param>
        /// <returns>The redirect url where the user should be redirected, with the coupon appended to it</returns>
        public string ExecuteExperimentExecutionRecipe(ProcessAgentInfo labServer, LabClient client,
            DateTime startExecution, long duration, int userTZ, int userID, int groupID, string groupName)
        {
            BrokerDB brokerDB;
            Coupon coupon;
            // refactored out
            ExecuteExperimentExecutionRecipe(labServer, ref client, ref startExecution, duration, userTZ, userID, groupID, groupName, out brokerDB, out coupon);

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

            //return the appended url
            return url.ToString();
        }
Example #28
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            int groupID = 0;
            string groupName = null;
            lc = wrapper.GetLabClientsWrapper(new int[] { Convert.ToInt32(Session["ClientID"]) })[0];

            if (Session["GroupID"] != null && Session["GroupID"].ToString().Length > 0)
            {
                groupID = Convert.ToInt32(Session["GroupID"]);
            }
            if (Session["GroupName"] != null && Session["GroupName"].ToString().Length > 0)
            {
                groupName = Session["GroupName"].ToString();

                lblGroupNameTitle.Text = groupName;
                lblBackToLabs.Text = groupName;

                if (Convert.ToInt32(Session["ClientCount"]) == 1)
                    lblGroupNameSystemMessage.Text = "Messages for " + groupName;
                else
                    lblGroupNameSystemMessage.Text = "Messages for " + lc.clientName;
            }

            if (!IsPostBack)
            {
                auto = Request.QueryString["auto"];
                if (auto!= null && auto.Length > 0)
                {
                    if (auto.ToLower().Contains("t"))
                    {
                        autoLaunch = true;
                    }
                }
                if (lc.clientType == LabClient.INTERACTIVE_APPLET || lc.clientType == LabClient.INTERACTIVE_HTML_REDIRECT)
                {
                    // retrieve parameters from URL
                    couponId = Request.QueryString["coupon_id"];
                    passkey = Request.QueryString["passkey"];
                    issuerGuid = Request.QueryString["issuer_guid"];

                    if (lc.needsScheduling)
                    {
                        Coupon opCoupon = null;
                        if (couponId != null && passkey != null && issuerGuid != null)
                        {
                            opCoupon = new Coupon(issuerGuid, Int64.Parse(couponId), passkey);

                            // First check for an Allow Execution Ticket
                            Ticket allowExperimentExecutionTicket = issuer.RetrieveTicket(
                                opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION);
                            if (allowExperimentExecutionTicket == null)
                            {
                                // Try for a reservation

                                int ussId = issuer.FindProcessAgentIdForClient(lc.clientID, ProcessAgentType.SCHEDULING_SERVER);
                                if (ussId > 0)
                                {
                                    ProcessAgent uss = issuer.GetProcessAgent(ussId);
                                    ProcessAgent ls = issuer.GetProcessAgent(lc.labServerIDs[0]);

                                    UserSchedulingProxy ussProxy = new UserSchedulingProxy();
                                    OperationAuthHeader op = new OperationAuthHeader();
                                    op.coupon = opCoupon;
                                    ussProxy.Url = uss.webServiceUrl;
                                    ussProxy.OperationAuthHeaderValue = op;
                                    Reservation reservation = ussProxy.RedeemReservation(ProcessAgentDB.ServiceGuid, Session["UserName"].ToString(), ls.agentGuid, lc.clientGuid);

                                    if (reservation != null)
                                    {
                                        // Find efective group
                                        string effectiveGroupName = null;
                                        int effectiveGroupID = AuthorizationAPI.GetEffectiveGroupID(groupID, lc.clientID,
                                            Qualifier.labClientQualifierTypeID, Function.useLabClientFunctionType);
                                        if (effectiveGroupID == groupID)
                                        {
                                            if (Session["groupName"] != null)
                                            {
                                                effectiveGroupName = Session["groupName"].ToString();
                                            }
                                            else
                                            {
                                                effectiveGroupName = AdministrativeAPI.GetGroupName(groupID);
                                                Session["groupName"] = effectiveGroupName;
                                            }
                                        }
                                        else if (effectiveGroupID > 0)
                                        {
                                            effectiveGroupName = AdministrativeAPI.GetGroupName(effectiveGroupID);
                                        }
                                        // create the allowExecution Ticket
                                        DateTime start = reservation.Start;
                                        long duration = reservation.Duration;
                                        string payload = TicketLoadFactory.Instance().createAllowExperimentExecutionPayload(
                                            start, duration, effectiveGroupName);
                                        DateTime tmpTime = start.AddTicks(duration * TimeSpan.TicksPerSecond);
                                        DateTime utcNow = DateTime.UtcNow;
                                        long ticketDuration = (tmpTime.Ticks - utcNow.Ticks) / TimeSpan.TicksPerSecond;
                                        allowExperimentExecutionTicket = issuer.AddTicket(opCoupon, TicketTypes.ALLOW_EXPERIMENT_EXECUTION,
                                                ProcessAgentDB.ServiceGuid, ProcessAgentDB.ServiceGuid, ticketDuration, payload);
                                    }
                                }
                            }
                            if (allowExperimentExecutionTicket != null)
                            {
                                XmlDocument payload = new XmlDocument();
                                payload.LoadXml(allowExperimentExecutionTicket.payload);
                                startExecution = DateUtil.ParseUtc(payload.GetElementsByTagName("startExecution")[0].InnerText);
                                duration = Int64.Parse(payload.GetElementsByTagName("duration")[0].InnerText);

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

                                //groupId = payload.GetElementsByTagName("groupID")[0].InnerText;

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

                                    long[] ids = InternalDataDB.RetrieveActiveExperimentIDs(Convert.ToInt32(Session["UserID"]),
                                        Convert.ToInt32(Session["GroupID"]), lc.labServerIDs[0], lc.clientID);
                                    if (ids.Length > 0)
                                    {
                                        btnLaunchLab.Text = "Launch New Experiment";
                                        btnLaunchLab.Visible = true;
                                        pReenter.Visible = true;
                                        btnReenter.Visible = true;
                                        btnReenter.CommandArgument = ids[0].ToString();
                                    }
                                    else
                                    {

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

            btnSchedule.Visible = lc.needsScheduling;
            //Session["LoaderScript"] = lc.loaderScript;
            lblClientName.Text = lc.clientName;
            lblVersion.Text = lc.version;
            lblLongDescription.Text = lc.clientLongDescription;
            lblNotes.Text = lc.notes;
            string emailCmd = "mailto:" + lc.contactEmail;
            lblEmail.Text = "<a href=" + emailCmd + ">" + lc.contactEmail + "</a>";

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

            int count = 0;

            if (lc.clientInfos != null)
            {
                foreach (ClientInfo ci in lc.clientInfos)
                {
                    if (ci.infoURLName.CompareTo("Documentation") != 0)
                    {
                        System.Web.UI.WebControls.Button b = new System.Web.UI.WebControls.Button();
                        b.Visible = true;
                        b.CssClass = "button";
                        b.Text = ci.infoURLName;
                        b.CommandArgument = ci.infoURL;
                        b.CommandName = ci.infoURLName;
                        b.ToolTip = ci.description;
                        b.Command += new CommandEventHandler(this.HelpButton_Click);
                        repClientInfos.Controls.AddAt(count, b);
                        repClientInfos.Controls.AddAt(count + 1, new LiteralControl("&nbsp;&nbsp;"));
                        count += 2;
                    }
                }
            }

            List<SystemMessage> messagesList = new List<SystemMessage>();
            SystemMessage[] groupMessages = null;
            if (Session["ClientCount"] != null && Convert.ToInt32(Session["ClientCount"]) == 1)
            {
                groupMessages = wrapper.GetSystemMessagesWrapper(SystemMessage.GROUP, Convert.ToInt32(Session["GroupID"]), 0, 0);
                if (groupMessages != null)
                    messagesList.AddRange(groupMessages);
            }

            foreach (int labServerID in lc.labServerIDs)
            {
                SystemMessage[] labMessages = wrapper.GetSystemMessagesWrapper(SystemMessage.LAB, 0, 0, labServerID);
                if (labMessages != null)
                    messagesList.AddRange(labMessages);
            }

            if (messagesList != null && messagesList.Count > 0)
            {
                messagesList.Sort(SystemMessage.CompareDateDesc);
                //messagesList.Reverse();
                repSystemMessage.DataSource = messagesList;
                repSystemMessage.DataBind();
            }

            else
            {

                lblGroupNameSystemMessage.Text += "</h3><p>No Messages at this time</p><h3>";

            }
        }
Example #29
0
        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);
        }
Example #30
0
        /*
        /// <summary>
        /// Generates and installs a new passkey that will be used to authenticate web service calls made by the remote server identified by labServerID.
        /// The passkey returned must be conveyed out of band to the administrator of the remote server.
        /// </summary>
        /// <param name="labServerID">The ID of the (lab) server for which the passkey will be generated.</param>
        /// <returns>The passkey authenticating the remote server.</returns>
        /// <seealso cref="GetIncomingServerPasskey">GetIncomingServerPasskey</seealso>
        public static string GenerateIncomingServerPasskey(int labServerID)
        {
            // Random rand = new Random ();  // dynamic seeds
            // string key = rand.Next ().ToString ();

            // Changed from random number to a GUID - CF 1/21/2005
            string key = Guid.NewGuid().ToString("N");  // with no "-" in Guid string

            try
            {
                InternalAdminDB.UpdateLSIncomingPasskey (labServerID, key);
            }
            catch (Exception ex)
            {
                throw;
            }
            return key;
        }

        /// <summary>
        /// Retrieves a previously generated passkey to authenticate web service calls made by the remote server identified by labServerID.
        /// </summary>
        /// <param name="labServerID">The ID of the (lab) server for which the passkey will be retrieved.</param>
        /// <returns>The passkey authenticating the remote server.</returns>
        /// <seealso cref="GenerateIncomingServerPasskey">GenerateIncomingServerPasskey</seealso>
        public static string GetIncomingServerPasskey(int labServerID)
        {
            string incomingKey = "";
            try
            {
                incomingKey = InternalAdminDB.selectSBIncomingPasskey (labServerID);
            }
            catch(Exception ex)
            {
                throw;
            }
            return incomingKey;
        }

        /// <summary>
        /// Installs a per lab server passkey that authenticates this service broker.
        /// </summary>
        /// <param name="labServerID">The ID of the lab server for which the passkey will be installed.</param>
        /// <param name="passkey">The passkey or token that this Service Broker must present on each web service call to gain access to the lab server.</param>
        public static void RegisterOutgoingServerPasskey(int labServerID, string passkey)
        {
            try
            {
                InternalAdminDB.UpdateLSOutgoingPasskey (labServerID, passkey);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// Retrieve a previously registered passkey that this service broker must present on each web service call to gain access to the lab server identified by labServerID.
        /// </summary>
        /// <param name="labServerID">The ID of the (lab) server for which the passkey will be retrieved.</param>
        /// <returns>The passkey for the remote server.</returns>
        public static string GetOutgoingServerPasskey(int labServerID)
        {
            string outgoingKey = "";
            try
            {
                outgoingKey = InternalAdminDB.selectSBOutgoingPasskey (labServerID);
            }
            catch(Exception ex)
            {
                throw;
            }
            return outgoingKey;
        }
        */
        ///*********************** LAB CLIENTS **************************///
        /// <summary>
        /// Registers the client identified by ClientName with the Service Broker; after this call users can request the loading of this client to compose and execute experiments on the associated lab servers.
        /// </summary>
        /// <param name="guid">A string limited to 50 characters used for identification across domains, do not modifiy except at creation.</param>
        /// <param name="clientName">A name for the client application meaningful to humans; it is not required to be unique on the Service Broker.</param>
        /// <param name="version">The version number of the client software; each new version must receive a new clientID.</param>
        /// <param name="notes">An arbitrary piece of text that will be visible to students using the client.</param>
        /// <param name="loaderScript">An HTML fragment that will be embedded on a Service Broker generated page executed by the user's web browser to launch the client.</param>
        /// <param name="clientShortDescription">A brief description of the client suitable for listing in a GUI.</param>
        /// <param name="clientLongDescription">A longer more descriptive text explaining the purpose of the client.</param>
        /// <param name="clientType">A string identifying the client type.</param>
        /// <param name="labServerIDs">An array of labServerIDs specifying the ordered list of lab servers accessed by this client.</param>
        /// <param name="contactEmail">The email address of the party responsible for the maintenance of the client.</param>
        /// <param name="contactFirstName">The first name of the party responsible for the maintenance of the client.</param>
        /// <param name="contactLastName">The last name of the party responsible for the maintenance of the client.</param>
        ///<param name="clientInfos">An array of ClientInfo structures containing multiple instances of information associated with this clientID. Information such as the client name and the URL of an information page are maintained. It this value is NULL, the previous value will not be changed.</param>
        /// <returns>The unique clientID which identifies the client software internally to the Service Broker. >0 was successfully registered; -1 otherwise</returns>
        public static int AddLabClient(string guid, string clientName, string version, string clientShortDescription, string clientLongDescription, string notes, string loaderScript, string clientType, int[] labServerIDs, string contactEmail, string contactFirstName, string contactLastName, bool needsScheduling, bool needsESS, bool isReentrant, ClientInfo[] clientInfos)
        {
            LabClient lc = new LabClient ();
            lc.clientGuid = guid;
            lc.clientName = clientName;
            lc.version = version;
            lc.notes=notes;
            lc.clientShortDescription=clientShortDescription;
            lc.clientLongDescription=clientLongDescription;
            lc.loaderScript=loaderScript;
            lc.labServerIDs = labServerIDs;
            lc.contactEmail = contactEmail;
            lc.contactFirstName = contactFirstName;
            lc.contactLastName = contactLastName;
            lc.needsScheduling = needsScheduling;
            lc.needsESS = needsESS;
            lc.IsReentrant = isReentrant;
            lc.clientInfos=clientInfos;
            lc.clientType= clientType;

            try
            {
                //Insert the lab client into the database
                lc.clientID = InternalAdminDB.InsertLabClient (lc);

                try
                {
                    //Add the lab client to the Qualifiers & Qualifiers Hierarchy Table
                    Authorization.AuthorizationAPI .AddQualifier (lc.clientID, Authorization.Qualifier .labClientQualifierTypeID, lc.clientName, Qualifier.ROOT);
                }
                catch (Exception ex)
                {
                    // rollback lab client insertion
                    InternalAdminDB.DeleteLabClients(new int[]{lc.clientID});

                    throw;
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return lc.clientID;
        }