Esempio n. 1
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into MBF
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public string GetResult(
            string requestIdentifier,
            BlastParameters parameters)
        {
            WSFile[] resultTypes = _blastClient.getResults(requestIdentifier);

            if (resultTypes == null)
            {
                throw new Exception(Resource.EBIWURESULTTYPEFAILED);
            }

            string response = string.Empty;

            foreach (WSFile resultType in resultTypes)
            {
                if (resultType.type == "appxmlfile")
                {
                    byte[]        content = _blastClient.poll(requestIdentifier, resultType.type);
                    ASCIIEncoding enc     = new ASCIIEncoding();
                    response = enc.GetString(content);
                }
            }

            if (string.IsNullOrEmpty(response))
            {
                throw new Exception(
                          String.Format(
                              Resource.EMPTYRESPONSE,
                              requestIdentifier));
            }

            // we have XML results, parse them
            return(response);
        }
Esempio n. 2
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            List <ISequence> seqList = new List <ISequence>();

            seqList.Add(sequence);
            return(SubmitRequest(seqList, parameters));
        }
Esempio n. 3
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null == sequence)
            {
                throw new ArgumentNullException("sequence");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            string requestIdentifier;

            // Create blast client object if not created already or if connection string has changed.
            if (blastClient == null || blastClient.Endpoint.Address.Uri != configuration.Connection)
            {
                InitializeBlastClient();
            }

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // Submit the job to server
            BlastSerivceRequest blastRequest = GetRequestParameter(
                sequence,
                parameters);

            try
            {
                requestIdentifier = blastClient.SubmitJob(blastRequest).ToString();
            }
            catch (FaultException <BlastFault> fault)
            {
                throw new Exception(fault.Message);
            }

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                BlastThreadParameter threadParameter = new BlastThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                workerThread = new BackgroundWorker();
                workerThread.WorkerSupportsCancellation = true;
                workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into Bio
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public string GetResult(
            string requestIdentifier,
            BlastParameters parameters)
        {
            string resultUri = blastClient.GetJobResult(new Guid(requestIdentifier));

            WebAccessor         accessor            = new WebAccessor();
            WebAccessorResponse webAccessorResponse = null;

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }

            webAccessorResponse = accessor.SubmitHttpRequest(
                new Uri(resultUri),
                false,          // POST request
                new Dictionary <string, string>());
            if (!webAccessorResponse.IsSuccessful)
            {
                // failure
                accessor.Close();
                return(null);
            }

            accessor.Close();
            return(webAccessorResponse.ResponseString);
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into Bio
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public string GetResult(
            string requestIdentifier,
            BlastParameters parameters)
        {
            wsResultType[] resultTypes = blastClient.getResultTypes(requestIdentifier);

            if (resultTypes == null)
            {
                throw new Exception(Resources.EBIWURESULTTYPEFAILED);
            }

            string response = string.Empty;

            foreach (wsResultType resultType in resultTypes)
            {
                if (resultType.mediaType == "application/xml")
                {
                    byte[]        content = blastClient.getResult(requestIdentifier, resultType.identifier, null);
                    ASCIIEncoding enc     = new ASCIIEncoding();
                    response = enc.GetString(content);
                }
            }

            if (string.IsNullOrEmpty(response))
            {
                throw new Exception(
                          String.Format(CultureInfo.InvariantCulture,
                                        Resources.EMPTYRESPONSE,
                                        requestIdentifier));
            }

            // we have XML results, parse them
            return(response);
        }
Esempio n. 6
0
        /// <summary>
        /// Get the blast service request object with all the request parameter set
        /// </summary>
        /// <param name="sequence">Input sequece</param>
        /// <param name="parameters">Blast parameters</param>
        /// <returns>Blast service request object</returns>
        private static BlastSerivceRequest GetRequestParameter(
            ISequence sequence,
            BlastParameters parameters)
        {
            BlastSerivceRequest blastParameter = new BlastSerivceRequest();

            // Sets the format of output expected from Azure Blast service
            blastParameter.OptionM = OPTIONMVALUE;

            // Sets the name of Job owner
            blastParameter.Owner          = Resources.OWNERVALUE;
            blastParameter.ParitionNumber = PARTITIONVALUE;

            // Convert string to byte
            string        inputContent  = FastAFormatter.FormatString(sequence);
            ASCIIEncoding asciiEncoding = new ASCIIEncoding();

            blastParameter.InputContent = asciiEncoding.GetBytes(inputContent);

            // Other parameters
            // Set the Title of Job
            blastParameter.Title = sequence.ID;

            // Name of the database to be searched in
            blastParameter.DatabaseName = parameters.Settings[PARAMETERDATABASE];

            // Type of search program to be executed
            blastParameter.ProgramName = parameters.Settings[PARAMETERPROGRAM];

            return(blastParameter);
        }
Esempio n. 7
0
        /// <summary>
        /// Fetch the search results synchronously for the pertinent request identifier.
        /// This is a synchronous method and will not return until the results are
        /// available.
        /// Implementation should have dedicated parsers to format the received results into
        /// Bio
        /// </summary>
        /// <remarks>
        /// An exception is thrown if the request does not succeed.
        /// </remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public IList <BlastResult> FetchResultsSync(
            string requestIdentifier,
            BlastParameters parameters)
        {
            IList <BlastResult> result = null;

            ServiceRequestInformation requestInfo = new ServiceRequestInformation();

            requestInfo.Status = ServiceRequestStatus.Queued;
            int retryCount = 0;

            do
            {
                requestInfo = GetRequestStatus(requestIdentifier);

                if (requestInfo.Status == ServiceRequestStatus.Ready ||
                    requestInfo.Status == ServiceRequestStatus.Error)
                {
                    break;
                }

                retryCount++;
                Thread.Sleep(RetryInterval * retryCount);
            }while (retryCount < RetryCount);

            string message;

            if (requestInfo.Status == ServiceRequestStatus.Ready)
            {
                string output = GetResult(
                    requestIdentifier,
                    parameters);

                result = Parser.Parse(new StringReader(output));
            }
            else if (requestInfo.Status == ServiceRequestStatus.Error)
            {
                message = String.Format(CultureInfo.InvariantCulture,
                                        Resources.BLASTREQUESTFAILED,
                                        requestIdentifier,
                                        requestInfo.Status,
                                        requestInfo.StatusInformation);

                throw new Exception(message);
            }
            else
            {
                message = String.Format(CultureInfo.InvariantCulture,
                                        Resources.BLASTRETRIESEXCEEDED,
                                        requestIdentifier,
                                        requestInfo.Status,
                                        requestInfo.StatusInformation);

                throw new Exception(message);
            }

            return(result);
        }
Esempio n. 8
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into Bio framework
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">not needed - included only for compatibility with the interface</param>
        /// <returns>The search results</returns>
        public string GetResult(string requestIdentifier, BlastParameters parameters)
        {
            string  response   = string.Empty;
            JobInfo jobidcntrl = ConvertRequestId(requestIdentifier);

            response = blastClient.GetOutputAsString(jobidcntrl.Jobid, jobidcntrl.Cntrl);

            return(response);
        }
Esempio n. 9
0
 /// <summary>
 /// Initializes a new instance of the ThreadParameter class.
 /// </summary>
 /// <param name="requestIdentifier">Job identifier</param>
 /// <param name="sequence">Sequence Object</param>
 /// <param name="parameter">Blast Parameters</param>
 public ThreadParameter(
     string requestIdentifier,
     ISequence sequence,
     BlastParameters parameter)
 {
     _requestIdentifier = requestIdentifier;
     _sequence          = sequence;
     _parameter         = parameter;
 }
Esempio n. 10
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null == sequence)
            {
                throw new ArgumentNullException("sequence");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // Submit the job to server
            inputParams blastRequest = GetRequestParameter(
                sequence,
                parameters);

            blastRequest.appxml = APPXMLYES;
            blastRequest.async  = true;

            data[] mydata = new data[1];
            mydata[0]         = new data();
            mydata[0].type    = SEQUENCETYPE;
            mydata[0].content = sequence.ToString();

            requestIdentifier = _blastClient.runWUBlast(blastRequest, mydata);

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                ThreadParameter threadParameter = new ThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                _workerThread = new BackgroundWorker();
                _workerThread.WorkerSupportsCancellation = true;
                _workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                _workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 11
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null == sequence)
            {
                throw new ArgumentNullException("sequence");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            string requestIdentifier;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // Submit the job to server
            BlastSerivceRequest blastRequest = GetRequestParameter(
                sequence,
                parameters);

            try
            {
                requestIdentifier = _blastClient.SubmitJob(blastRequest).ToString();
            }
            catch (FaultException <BlastFault> fault)
            {
                throw new Exception(fault.Detail.Detail);
            }

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                ThreadParameter threadParameter = new ThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                _workerThread = new BackgroundWorker();
                _workerThread.WorkerSupportsCancellation = true;
                _workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                _workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 12
0
        /// <summary>
        /// Check the currently set parameters for validity
        /// </summary>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Validation result</returns>
        private static ParameterValidationResult ValidateParameters(BlastParameters parameters)
        {
            ParameterValidationResult result = new ParameterValidationResult();

            result.IsValid = true;

            // check required parameters:
            if (!parameters.Settings.ContainsKey(PARAMETERDATABASE))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERDATABASEREQUIRED;
            }

            if (!parameters.Settings.ContainsKey(PARAMETERPROGRAM))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERPROGRAMREQUIRED;
            }

            // check disallowed parameters:
            if (parameters.Settings.ContainsKey(PARAMETERFORMATTYPE))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERFORMATTYPENOTALLOWED;
            }

            // Any other unknown parameters
            foreach (KeyValuePair <string, string> parameter in parameters.Settings)
            {
                switch (parameter.Key)
                {
                case PARAMETERDATABASE:
                case PARAMETERPROGRAM:
                case PARAMETERFORMATTYPE:
                    break;

                default:
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(CultureInfo.InvariantCulture,
                                                             Resources.PARAMETERUNKNOWNAZURE,
                                                             parameter.Key);
                    break;
                }
            }

            return(result);
        }
Esempio n. 13
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Unique Search ID generated by Bio</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null == sequence)
            {
                throw new ArgumentNullException("sequence");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            List <ISequence> seqlist = new List <ISequence> {
                sequence
            };

            return(SubmitRequest(seqlist, parameters));
        }
Esempio n. 14
0
        /// <summary>
        /// Get the blast service request object with all the request parameter set
        /// </summary>
        /// <param name="sequence">Input sequece</param>
        /// <param name="parameters">Blast parameters</param>
        /// <returns>Blast service request object</returns>
        private static inputParams GetRequestParameter(
            ISequence sequence,
            BlastParameters parameters)
        {
            inputParams blastParameter = new inputParams();

            // check required parameters:
            blastParameter.database = parameters.Settings[PARAMETERDATABASE];

            // force program to uppercase, per EBI docs (though the service seems
            // to work fine regardless of the case of this parameter)
            blastParameter.program = parameters.Settings[PARAMETERPROGRAM].ToUpper();

            // note: query is not part of the inputParams class, so the caller will
            // need to handle it separately.
            blastParameter.email = parameters.Settings[PARAMETEREMAIL];

            // apply any addition validation logic and set remaining supported parameters:
            // validate filters here, since QBLAST uses a different set:
            if (parameters.Settings.ContainsKey(PARAMETERFILTER))
            {
                blastParameter.filter = parameters.Settings[PARAMETERFILTER];
            }

            if (parameters.Settings.ContainsKey(PARAMETERALIGNMENTS))
            {
                blastParameter.numal = (int?)int.Parse(parameters.Settings[PARAMETERALIGNMENTS]);
            }

            if (parameters.Settings.ContainsKey(PARAMETERMATRIXNAME))
            {
                blastParameter.matrix = parameters.Settings[PARAMETERMATRIXNAME];
            }

            if (parameters.Settings.ContainsKey(PARAMETEREXPECT))
            {
                blastParameter.exp = (float?)float.Parse(parameters.Settings[PARAMETEREXPECT]);
            }

            return(blastParameter);
        }
Esempio n. 15
0
        /// <summary>
        /// Get the blast service request object with all the request parameter set
        /// </summary>
        /// <param name="parameters">Blast parameters</param>
        /// <returns>Blast service request object</returns>
        private static inputParams GetRequestParameter(
            BlastParameters parameters)
        {
            inputParams blastParameter = new inputParams();

            // check required parameters:
            blastParameter.database = parameters.Settings[ParameterDatabase];

            // force program to uppercase, per EBI docs (though the service seems
            // to work fine regardless of the case of this parameter)
            blastParameter.program = parameters.Settings[ParameterProgram].ToUpperInvariant();

            // note: query is not part of the inputParams class, so the caller will
            // need to handle it separately.
            blastParameter.email = parameters.Settings[ParameterEmail];

            // apply any addition validation logic and set remaining supported parameters:
            // validate filters here, since QBLAST uses a different set:
            if (parameters.Settings.ContainsKey(ParameterFilter))
            {
                blastParameter.filter = parameters.Settings[ParameterFilter];
            }

            if (parameters.Settings.ContainsKey(ParameterAlignments))
            {
                blastParameter.numal = (int?)int.Parse(parameters.Settings[ParameterAlignments], CultureInfo.InvariantCulture);
            }

            if (parameters.Settings.ContainsKey(ParameterMatrixName))
            {
                blastParameter.matrix = parameters.Settings[ParameterMatrixName];
            }

            if (parameters.Settings.ContainsKey(ParameterExpect))
            {
                blastParameter.exp = (float?)float.Parse(parameters.Settings[ParameterExpect], CultureInfo.InvariantCulture);
            }

            return(blastParameter);
        }
Esempio n. 16
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into MBF
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public string GetResult(
            string requestIdentifier,
            BlastParameters parameters)
        {
            string resultUri = _blastClient.GetJobResult(new Guid(requestIdentifier));

            Stream      responseStream    = null;
            string      statusDescription = string.Empty;
            WebAccessor accessor          = new WebAccessor();

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }

            if (!accessor.SubmitHttpRequest(
                    resultUri,
                    false, // POST request
                    new Dictionary <string, string>(),
                    out statusDescription,
                    out responseStream))
            {
                // failure
                accessor.Close();
                return(null);
            }

            string response = string.Empty;

            using (StreamReader r = new StreamReader(responseStream))
            {
                response = r.ReadToEnd();
                r.Close();
            }

            accessor.Close();
            return(response);
        }
Esempio n. 17
0
 /// <summary>
 /// Submit the search request with the user supplied configuration parameters and sequence
 /// Implementation should make use of the Bio.IO formatters to convert the sequence into
 /// the web interface compliant sequence format
 /// </summary>
 /// <remarks>An exception is thrown if the request does not succeed.</remarks>
 /// <param name="sequences">List of sequence to search with</param>
 /// <param name="parameters">Blast input parameters</param>
 /// <returns>Request Identifier</returns>
 public string SubmitRequest(IList <ISequence> sequences, BlastParameters parameters)
 {
     throw new NotImplementedException();
 }
Esempio n. 18
0
        /// <summary>
        /// Check the currently set parameters for validity
        /// </summary>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Validation result</returns>
        private ParameterValidationResult ValidateParameters(BlastParameters parameters)
        {
            ParameterValidationResult result = new ParameterValidationResult();

            result.IsValid = true;

            // check required parameters:
            if (!parameters.Settings.ContainsKey(PARAMETERDATABASE))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resource.PARAMETERDATABASEREQUIRED;
            }

            if (!parameters.Settings.ContainsKey(PARAMETERPROGRAM))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resource.PARAMETERPROGRAMREQUIRED;
            }

            // note: query is not part of the inputParams class, so the caller will
            // need to handle it separately.
            if (!parameters.Settings.ContainsKey(PARAMETEREMAIL))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resource.PARAMETEREMAILREQUIRED;
            }

            if (parameters.Settings.ContainsKey(PARAMETERFILTER))
            {
                string filter = parameters.Settings[PARAMETERFILTER];
                if (!Helper.StringHasMatch(filter, "none", "seg", "xnu", "seg+xnu", "dust"))
                {
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(Resource.INVALIDBLASTFILTER, filter);
                }
            }

            // Any other unknown parameters
            foreach (KeyValuePair <string, string> parameter in parameters.Settings)
            {
                switch (parameter.Key)
                {
                case PARAMETERDATABASE:
                case PARAMETERPROGRAM:
                case PARAMETEREMAIL:
                case PARAMETERFILTER:
                case PARAMETERALIGNMENTS:
                case PARAMETERMATRIXNAME:
                case PARAMETEREXPECT:
                    // These are valid parameter, so allow them.
                    break;

                default:
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(
                        Resource.PARAMETERUNKNOWNEBIWU,
                        parameter.Key);
                    break;
                }
            }

            return(result);
        }
Esempio n. 19
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null != sequence)
            {
                parameters.Add("Query", sequence.ToString());
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            parameters.Add(PARAMETERCOMMAND, COMMANDPUT);

            Stream      responseStream    = null;
            string      statusDescription = string.Empty;
            WebAccessor accessor          = new WebAccessor();

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }

            if (!accessor.SubmitHttpRequest(
                    ServiceUri,
                    true,                   // do POST
                    parameters.Settings,    // request parameters
                    out statusDescription,
                    out responseStream))
            {
                // failed
                accessor.Close();
                throw new Exception(String.Format(
                                        Resource.HTTPSUBMITFAILED,
                                        statusDescription));
            }

            string response = string.Empty;

            using (StreamReader r = new StreamReader(responseStream))
            {
                response = r.ReadToEnd();
                string info = ExtractInfoSection(response);
                if (!String.IsNullOrEmpty(info))
                {
                    int ridStart = info.IndexOf("RID = ");
                    if (ridStart >= 0)
                    {
                        ridStart += "RID = ".Length;
                        int ridEnd = info.IndexOf('\n', ridStart);
                        if (ridEnd >= 0)
                        {
                            requestIdentifier = info.Substring(ridStart, ridEnd - ridStart);
                        }
                    }
                }

                r.Close();
            }

            accessor.Close();
            if (string.IsNullOrEmpty(requestIdentifier))
            {
                string message = String.Format(
                    Resource.RIDEXTRACTFAILED,
                    ExtractError(response));
                throw new Exception(message);
            }

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                ThreadParameter threadParameter = new ThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                _workerThread = new BackgroundWorker();
                _workerThread.WorkerSupportsCancellation = true;
                _workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                _workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 20
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into MBF
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public string GetResult(
            string requestIdentifier,
            BlastParameters parameters)
        {
            Stream      responseStream    = null;
            string      status            = string.Empty;
            string      response          = string.Empty;
            string      information       = string.Empty;
            string      statusDescription = string.Empty;
            WebAccessor accessor          = new WebAccessor();

            parameters.Add(PARAMETERCOMMAND, COMMANDGET);
            parameters.Add(PARAMETERJOBID, requestIdentifier);
            parameters.Add(PARAMETERFORMAT, FORMATXML);

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }
            if (!accessor.SubmitHttpRequest(
                    ServiceUri,
                    true, // POST request
                    parameters.Settings,
                    out statusDescription,
                    out responseStream))
            {
                // failure
                accessor.Close();
                return(null);
            }

            using (StreamReader r = new StreamReader(responseStream))
            {
                response = r.ReadToEnd();
                r.Close();
            }

            accessor.Close();

            information = ExtractInfoSection(response);

            if (!String.IsNullOrEmpty(information))
            {
                int statusStart = information.IndexOf("Status=");
                if (statusStart >= 0)
                {
                    statusStart += "Status=".Length;
                    int statusEnd = information.IndexOf('\n', statusStart);
                    if (statusEnd >= 0)
                    {
                        status = information.Substring(statusStart, statusEnd - statusStart);
                    }
                }
            }

            if (status != string.Empty)
            {
                if (status == STATUSWAITING)
                {
                    return(null);
                }
                else
                {
                    string message = String.Format(
                        Resource.INVALIDNCBISTATUS,
                        status);
                    throw new Exception(message);
                }
            }

            return(response);
        }
Esempio n. 21
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters and sequence
        /// Implementation should make use of the Bio.IO formatters to convert the sequence into
        /// the web interface compliant sequence format
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequences">List of sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(IList <ISequence> sequences, BlastParameters parameters)
        {
            string emailAddress = string.Empty;

            if (null == sequences)
            {
                throw new ArgumentNullException("sequences");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            string tempEmail;

            if (parameters.Settings.TryGetValue(ParameterEmail, out tempEmail) &&
                !string.IsNullOrEmpty(tempEmail))
            {
                emailAddress = tempEmail;
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // Submit the job to server
            InputParameters blastRequest = GetRequestParameter(parameters);

            StringBuilder seqBuilder = new StringBuilder();

            foreach (ISequence sequence in sequences)
            {
                byte[] buffer = new byte[80];
                int    bufferIndex = 0, maxLineSize = 80;

                seqBuilder.AppendLine(">" + sequence.ID);

                for (long index = 0; index < sequence.Count; index += maxLineSize)
                {
                    for (bufferIndex = 0; bufferIndex < maxLineSize && index + bufferIndex < sequence.Count; bufferIndex++)
                    {
                        buffer[bufferIndex] = sequence[index + bufferIndex];
                    }

                    string line = ASCIIEncoding.ASCII.GetString(buffer, 0, bufferIndex);
                    seqBuilder.AppendLine(line);
                }
            }

            blastRequest.sequence = seqBuilder.ToString();

            requestIdentifier = blastClient.run(emailAddress, string.Empty, blastRequest);

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                BlastThreadParameter threadParameter = new BlastThreadParameter(
                    requestIdentifier,
                    null,
                    parameters);

                // Start the BackGroundThread to check the status of job
                workerThread = new BackgroundWorker();
                workerThread.WorkerSupportsCancellation = true;
                workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 22
0
        /// <summary>
        /// Check the currently set parameters for validity
        /// </summary>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Validation result</returns>
        public static ParameterValidationResult ValidateParameters(BlastParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            ParameterValidationResult result = new ParameterValidationResult();

            result.IsValid = true;

            // check required parameters:
            if (!parameters.Settings.ContainsKey(ParameterDatabase))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERDATABASEREQUIRED;
            }

            if (!parameters.Settings.ContainsKey(ParameterProgram))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERPROGRAMREQUIRED;
            }

            if (!parameters.Settings.ContainsKey(ParameterSequenceType))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERSEQUENCETYPEREQUIRED;
            }

            //// note: query is not part of the inputParams class, so the caller will
            //// need to handle it separately.
            //if (!parameters.Settings.ContainsKey(ParameterEmail))
            //{
            //    result.IsValid = false;
            //    result.ValidationErrors += Resources.PARAMETEREMAILREQUIRED;
            //}

            if (parameters.Settings.ContainsKey(ParameterFilter))
            {
                string filter = parameters.Settings[ParameterFilter];
                if (!Helper.StringHasMatch(filter, "none", "seg", "xnu", "seg+xnu", "dust"))
                {
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(CultureInfo.InvariantCulture, Resources.INVALIDBLASTFILTER, filter, "'none, 'seg', 'xnu', 'seg+xnu', 'dust'");
                }
            }

            // Any other unknown parameters
            foreach (KeyValuePair <string, string> parameter in parameters.Settings)
            {
                switch (parameter.Key)
                {
                case ParameterDatabase:
                case ParameterProgram:
                case ParameterSequenceType:
                case ParameterEmail:
                case ParameterFilter:
                case ParameterAlignments:
                case ParameterMatrixName:
                case ParameterExpect:
                case ParameterAlignmentView:
                    // These are valid parameter, so allow them.
                    break;

                default:
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(CultureInfo.InvariantCulture,
                                                             Resources.PARAMETERUNKNOWNEBIWU,
                                                             parameter.Key);
                    break;
                }
            }

            return(result);
        }
Esempio n. 23
0
        /// <summary>
        /// Get the blast service request object with all the request parameter set
        /// </summary>
        /// <param name="parameters">Blast parameters</param>
        /// <returns>Blast service request object</returns>
        private static InputParameters GetRequestParameter(
            BlastParameters parameters)
        {
            InputParameters blastParameter = new InputParameters();

            // check required parameters:
            if (parameters.Settings[ParameterDatabase].Contains(","))
            {
                blastParameter.database = parameters.Settings[ParameterDatabase].Split(",".ToCharArray());
            }
            else
            {
                blastParameter.database    = new string[1];
                blastParameter.database[0] = parameters.Settings[ParameterDatabase];
            }

            // force program to lowercase, per EBI docs (though the service seems
            // to work fine regardless of the case of this parameter)
            blastParameter.program = parameters.Settings[ParameterProgram].ToLower(CultureInfo.CurrentCulture);

            // set the sequence Type.
            blastParameter.stype = parameters.Settings[ParameterSequenceType].ToLower(CultureInfo.CurrentCulture);

            // Set the Alignment View property.
            if (parameters.Settings.ContainsKey(ParameterAlignmentView))
            {
                blastParameter.align          = (int?)int.Parse(parameters.Settings[ParameterAlignmentView]);
                blastParameter.alignSpecified = true;
            }
            else
            {
                blastParameter.align          = int.Parse(BlastParameters.Parameters[ParameterKeyAlignmentView].DefaultValue);
                blastParameter.alignSpecified = true;
            }

            //// note: query is not part of the inputParams class, so the caller will
            //// need to handle it separately.
            //blastParameter.email = parameters.Settings[ParameterEmail];

            // apply any addition validation logic and set remaining supported parameters:
            // validate filters here, since QBLAST uses a different set:
            if (parameters.Settings.ContainsKey(ParameterFilter))
            {
                blastParameter.filter = parameters.Settings[ParameterFilter];
            }

            if (parameters.Settings.ContainsKey(ParameterAlignments))
            {
                blastParameter.alignments = (int?)int.Parse(parameters.Settings[ParameterAlignments], CultureInfo.InvariantCulture);
            }

            if (parameters.Settings.ContainsKey(ParameterMatrixName))
            {
                blastParameter.matrix = parameters.Settings[ParameterMatrixName];
            }

            if (parameters.Settings.ContainsKey(ParameterExpect))
            {
                blastParameter.exp = parameters.Settings[ParameterExpect];
            }

            return(blastParameter);
        }
Esempio n. 24
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters and sequence
        /// Implementation should make use of the Bio.IO formatters to convert the sequence into
        /// the web interface compliant sequence format
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequences">List of sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(IList <ISequence> sequences, BlastParameters parameters)
        {
            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            if (null != sequences)
            {
                StringBuilder sb = new StringBuilder();
                foreach (ISequence seq in sequences)
                {
                    sb.Append(FastAFormatter.FormatString(seq));
                    sb.Append("\n");
                }
                parameters.Add("Query", sb.ToString());
            }

            if (!string.IsNullOrEmpty(Configuration.EmailAddress))
            {
                if (!parameters.Settings.ContainsKey(PARAMETEREMAIL))
                {
                    parameters.Add(PARAMETEREMAIL, Configuration.EmailAddress);
                }
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            parameters.Add(PARAMETERCOMMAND, COMMANDPUT);

            WebAccessor         accessor = new WebAccessor();
            WebAccessorResponse webAccessorResponse;

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }

            webAccessorResponse = accessor.SubmitHttpRequest(
                ServiceUri,
                true,                       // do POST
                parameters.Settings);       // request parameters
            if (!webAccessorResponse.IsSuccessful)
            {
                // failed
                accessor.Close();
                throw new Exception(String.Format(CultureInfo.InvariantCulture,
                                                  Resources.HTTPSUBMITFAILED,
                                                  webAccessorResponse.StatusDescription));
            }

            string info = ExtractInfoSection(webAccessorResponse.ResponseString);

            if (!String.IsNullOrEmpty(info))
            {
                int ridStart = info.IndexOf("RID = ", StringComparison.OrdinalIgnoreCase);
                if (ridStart >= 0)
                {
                    ridStart += "RID = ".Length;
                    int ridEnd = info.IndexOf('\n', ridStart);
                    if (ridEnd >= 0)
                    {
                        requestIdentifier = info.Substring(ridStart, ridEnd - ridStart);
                    }
                }
            }

            accessor.Close();
            if (string.IsNullOrEmpty(requestIdentifier))
            {
                string message = String.Format(CultureInfo.InvariantCulture,
                                               Resources.RIDEXTRACTFAILED,
                                               ExtractError(webAccessorResponse.ResponseString));
                throw new Exception(message);
            }

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                BlastThreadParameter threadParameter = new BlastThreadParameter(
                    requestIdentifier,
                    null,     // Sequence parameter is not used any where, hence passing null.
                    parameters);

                // Start the BackGroundThread to check the status of job
                workerThread = new BackgroundWorker();
                workerThread.WorkerSupportsCancellation = true;
                workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 25
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters and sequence list.
        /// Implementation should make use of the Bio.IO formatters to convert the sequence into
        /// the web interface compliant sequence format
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequences">List of sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Unique Search ID generated by Bio</returns>
        public string SubmitRequest(IList <ISequence> sequences, BlastParameters parameters)
        {
            if (sequences == null)
            {
                throw new Exception(Resources.BIOHPCNOSEQUENCE);
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            string requestIdentifier;

            // Start of BioHPC-specific code

            // we are submitting BLAST and give the job a name
            tAppId appID   = tAppId.P_BLAST;
            string jobname = BlastParameters.Parameters["JobName"].DefaultValue;

            if (parameters.Settings.ContainsKey(PARAMETERJOBNAME))
            {
                if (!String.IsNullOrEmpty(parameters.Settings[PARAMETERJOBNAME]))
                {
                    jobname = parameters.Settings[PARAMETERJOBNAME];
                }
            }

            if (parameters.Settings.ContainsKey(PARAMETEREMAIL))
            {
                if (string.IsNullOrEmpty(Configuration.EmailAddress))
                {
                    Configuration.EmailAddress = parameters.Settings[PARAMETEREMAIL];
                }
            }

            // initialize input parameters with defaults
            AppInputData pars = blastClient.InitializeApplicationParams(appID, jobname);

            // Retrieve database names for easy access by parameter validator
            dnaDatabases  = GetServiceMetadata(MetadataDatabasesDna);
            protDatabases = GetServiceMetadata(MetadataDatabasesProt);

            // Validate the parameter
            ParameterValidationResult valid = ValidateParameters(parameters, pars);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // ValidateParameters updated some of the entries in pars and put them
            // into its ParametersObject - we need to fetch the updated pars
            pars = valid.ParametersObject as AppInputData;

            // Set some remaining parameters...
            pars.blast.querysource = QuerySrcType.paste;

            // We request XML as format, since this is what we can parse...
            pars.blast.options.format = OutputFormat.XML;

            // Query sequence should be in full Fasta format.
            // We concatenate all the sequences from the list into a single string.
            pars.blast.query = String.Empty;
            foreach (ISequence auxseq in sequences)
            {
                pars.blast.query += FastAFormatter.FormatString(auxseq) + "\n";
            }

            pars.blast.query = pars.blast.query.Substring(0, pars.blast.query.Length - 1); // remobe trailing newline...

            // Run parameters and query string are ready. Submit the job to server:
            // Create a new BLAST job.
            string jobid = String.Empty;
            string cntrl = String.Empty;

            try
            {
                string[] outtab = blastClient.CreateJob(appID, jobname, "1", Configuration.EmailAddress, Configuration.Password, "Auto");
                if (outtab[0].IndexOf(MsgError, StringComparison.Ordinal) != -1)
                {
                    throw new Exception(String.Format(CultureInfo.InvariantCulture, Resources.BIOHPCJOBNOTCREATED, outtab[0]));
                }

                jobid             = outtab[1];
                cntrl             = outtab[2];
                requestIdentifier = jobid + "_" + cntrl;
            }
            catch
            {
                throw new Exception(Resources.BIOHPCSERVERABSENT);
            }

            // Finally, we can submit the job
            try
            {
                string result = blastClient.SubmitJob(jobid, cntrl, pars);
                if (result.IndexOf(MsgError, StringComparison.Ordinal) != -1)
                {
                    throw new Exception(String.Format(CultureInfo.InvariantCulture, Resources.BIOHPCJOBNOTSUBMITTED, jobid, result));
                }
            }
            catch
            {
                throw new Exception(Resources.BIOHPCSERVERABSENT);
            }

            // end of BioHPC-specific code

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                // ThreadParameter wants a single sequence - nor sure what this is for.
                // We'll give it the first sequence from the list, i.e., sequence[0]
                BlastThreadParameter threadParameter = new BlastThreadParameter(
                    requestIdentifier,
                    sequences[0],
                    parameters);

                // Start the BackGroundThread to check the status of job
                workerThread = new BackgroundWorker();
                workerThread.WorkerSupportsCancellation = true;
                workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Esempio n. 26
0
        /// <summary>
        /// Gets the search results for the pertinent request identifier.
        /// Implementation should have dedicated parsers to format the received results into Bio
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="requestIdentifier">Identifier for the request of interest.</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>The search results</returns>
        public string GetResult(
            string requestIdentifier,
            BlastParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            string              status              = string.Empty;
            string              information         = string.Empty;
            WebAccessor         accessor            = new WebAccessor();
            WebAccessorResponse webAccessorResponse = null;

            parameters.Add(PARAMETERCOMMAND, COMMANDGET);
            parameters.Add(PARAMETERJOBID, requestIdentifier);
            parameters.Add(PARAMETERFORMAT, FORMATXML);

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }

            webAccessorResponse = accessor.SubmitHttpRequest(
                ServiceUri,
                true,           // POST request
                parameters.Settings);
            if (!webAccessorResponse.IsSuccessful)
            {
                // failure
                accessor.Close();
                return(null);
            }

            accessor.Close();

            information = ExtractInfoSection(webAccessorResponse.ResponseString);

            if (!String.IsNullOrEmpty(information))
            {
                int statusStart = information.IndexOf("Status=", StringComparison.OrdinalIgnoreCase);
                if (statusStart >= 0)
                {
                    statusStart += "Status=".Length;
                    int statusEnd = information.IndexOf('\n', statusStart);
                    if (statusEnd >= 0)
                    {
                        status = information.Substring(statusStart, statusEnd - statusStart);
                    }
                }
            }

            if (!string.IsNullOrEmpty(status))
            {
                if (status == STATUSWAITING)
                {
                    return(null);
                }
                else
                {
                    string message = String.Format(CultureInfo.InvariantCulture,
                                                   Resources.INVALIDNCBISTATUS,
                                                   status);
                    throw new Exception(message);
                }
            }

            return(webAccessorResponse.ResponseString);
        }
Esempio n. 27
0
        /// <summary>
        /// Check the currently set parameters for validity
        /// </summary>
        /// <param name="parameters">Blast input parameters</param>
        /// <param name="pars">BLAST parameters in the BioHPC service format</param>
        /// <returns>Validation result</returns>
        private ParameterValidationResult ValidateParameters(BlastParameters parameters, AppInputData pars)
        {
            ParameterValidationResult result = new ParameterValidationResult();

            result.IsValid = true;

            // Make sure e-mail address is configured
            if (string.IsNullOrEmpty(Configuration.EmailAddress))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETEREMAILREQUIRED;
            }

            // check required BLAST parameters
            if (!parameters.Settings.ContainsKey(PARAMETERPROGRAM))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERPROGRAMREQUIRED;
            }
            else
            {
                string prgm = parameters.Settings[PARAMETERPROGRAM].ToLower(CultureInfo.InvariantCulture);
                if (Helper.StringHasMatch(prgm, Enum.GetNames(typeof(BLASTprogram))))
                {
                    pars.blast.program = (BLASTprogram)Enum.Parse(typeof(BLASTprogram), prgm);
                }
                else
                {
                    result.IsValid           = false;
                    result.ValidationErrors += Resources.PARAMETERPROGRAMREQUIRED;
                }
            }

            if (!parameters.Settings.ContainsKey(PARAMETERDATABASE))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERDATABASEREQUIRED;
            }
            else
            {
                string dbname = parameters.Settings[PARAMETERDATABASE];
                if (IsProgramDna(pars.blast.program))
                {
                    if (IsDbstringDNA(dbname))
                    {
                        pars.blast.database.database = dbname;
                    }
                    else
                    {
                        result.IsValid           = false;
                        result.ValidationErrors += Resources.BIOHPCNODNADB;
                    }
                }
                else
                {
                    if (IsDbstringProt(dbname))
                    {
                        pars.blast.database.database = dbname;
                    }
                    else
                    {
                        result.IsValid           = false;
                        result.ValidationErrors += Resources.BIOHPCNOPROTDB;
                    }
                }
            }

            // Allowed parameters
            if (parameters.Settings.ContainsKey(PARAMETERFILTER))
            {
                // If the supplied filter parameter makes sense, use it; otherwise the default will be used.
                string fltr = parameters.Settings[PARAMETERFILTER];
                if (Helper.StringHasMatch(fltr, Enum.GetNames(typeof(LowCompFilter))))
                {
                    pars.blast.options.lcompfilter = (LowCompFilter)Enum.Parse(typeof(LowCompFilter), fltr);
                }
            }

            if (parameters.Settings.ContainsKey(PARAMETERALIGNMENTS))
            {
                pars.blast.options.maxtargets = int.Parse(parameters.Settings[PARAMETERALIGNMENTS], CultureInfo.InvariantCulture);
            }

            if (parameters.Settings.ContainsKey(PARAMETERMATRIXNAME))
            {
                // If the supplied matrix parameter makes sense, use it; otherwise the default will be used.
                string mtrx = parameters.Settings[PARAMETERMATRIXNAME].ToUpper(CultureInfo.InvariantCulture);
                if (Helper.StringHasMatch(mtrx, Enum.GetNames(typeof(Bio.Web.BioHPC.Matrix))))
                {
                    pars.blast.options.matrix = (Bio.Web.BioHPC.Matrix)Enum.Parse(typeof(Bio.Web.BioHPC.Matrix), mtrx);
                }
            }

            if (parameters.Settings.ContainsKey(PARAMETEREXPECT))
            {
                pars.blast.options.ecut = double.Parse(parameters.Settings[PARAMETEREXPECT], CultureInfo.InvariantCulture);
            }

            if (parameters.Settings.ContainsKey(PARAMETERMINQUERYLENGTH))
            {
                pars.blast.options.minquerylength = int.Parse(parameters.Settings[PARAMETERMINQUERYLENGTH], CultureInfo.InvariantCulture);
            }

            if (parameters.Settings.ContainsKey(PARAMETEREMAILNOTIFY))
            {
                pars.blast.runparams.email_notify = parameters.Settings[PARAMETEREMAILNOTIFY] == "yes";
            }

            // Any other unknown parameters
            foreach (KeyValuePair <string, string> parameter in parameters.Settings)
            {
                switch (parameter.Key)
                {
                // These are either handled above, or allowed
                case PARAMETERDATABASE:
                case PARAMETERPROGRAM:
                case PARAMETERFORMATTYPE:
                case PARAMETERFILTER:
                case PARAMETERALIGNMENTS:
                case PARAMETERMATRIXNAME:
                case PARAMETEREXPECT:
                case PARAMETERMINQUERYLENGTH:
                case PARAMETEREMAILNOTIFY:
                case PARAMETERJOBNAME:
                case PARAMETEREMAIL:
                    // Allow PARAMETEREMAIL so that if Configuration.EmailAddress is empty
                    // then this parameter can be set to Configuration.EmailAddress
                    break;

                default:
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(
                        CultureInfo.InvariantCulture,
                        Resources.PARAMETRUNKNOWNBIOHPC,
                        parameter.Key);
                    break;
                }
            }

            if (result.IsValid)
            {
                result.ParametersObject = pars;
            }

            return(result);
        }
Esempio n. 28
0
        /// <summary>
        /// Check the currently set parameters for validity
        /// </summary>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Validation result</returns>
        private static ParameterValidationResult ValidateParameters(BlastParameters parameters)
        {
            ParameterValidationResult result = new ParameterValidationResult();

            result.IsValid = true;

            // check required parameters:
            if (!parameters.Settings.ContainsKey(PARAMETERDATABASE))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERDATABASEREQUIRED;
            }

            if (!parameters.Settings.ContainsKey(PARAMETERPROGRAM))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERPROGRAMREQUIRED;
            }
            else
            {
                // force program to lowercase (NCBI QBlast does require this)
                parameters.Settings[PARAMETERPROGRAM] =
                    parameters.Settings[PARAMETERPROGRAM].ToLowerInvariant();
            }

            // verify that we have a valid query
            if (parameters.Settings.ContainsKey(PARAMETERQUERY))
            {
                if (string.IsNullOrEmpty(parameters.Settings[PARAMETERQUERY]))
                {
                    result.IsValid           = false;
                    result.ValidationErrors += Resources.PARAMETERSEQUENCEEMPTY;
                }
            }
            else
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERSEQUENCEREQUIRED;
            }

            // apply any addition validation logic to the set of parameters:
            // validate filters here, since EBI BLAST uses a different set:
            if (parameters.Settings.ContainsKey(PARAMETERFILTER))
            {
                string filter = parameters.Settings[PARAMETERFILTER];
                if (!Helper.StringHasMatch(filter, "T", "F", "m", "L", "R", "S", "D"))
                {
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(CultureInfo.InvariantCulture,
                                                             Resources.INVALIDBLASTFILTER,
                                                             filter,
                                                             "'T', 'F', 'm', 'L', 'R', 'S', 'D'");
                }
            }

            if (parameters.Settings.ContainsKey(PARAMETERGENETICCODE))
            {
                int geneticCode = int.Parse(parameters.Settings[PARAMETERGENETICCODE], CultureInfo.InvariantCulture);
                if (geneticCode < 1 || geneticCode > 22 ||
                    (geneticCode > 16 && geneticCode < 21))
                {
                    result.IsValid           = false;
                    result.ValidationErrors += Resources.INVALIDGENETICCODE;
                }
            }

            int queryFrom = 0;

            if (parameters.Settings.ContainsKey(PARAMETERQUERYFROM))
            {
                if (!int.TryParse(parameters.Settings[PARAMETERQUERYFROM], out queryFrom))
                {
                    result.IsValid = false;
                }
            }

            int queryTo = 0;

            if (parameters.Settings.ContainsKey(PARAMETERQUERYTO))
            {
                if (!int.TryParse(parameters.Settings[PARAMETERQUERYTO], out queryTo))
                {
                    result.IsValid = false;
                }
            }

            if (((queryFrom == queryTo) && (queryFrom != 0)) ||
                (queryFrom > queryTo))
            {
                result.IsValid           = false;
                result.ValidationErrors += Resources.PARAMETERQUERYTOINVALID;
            }

            // check disallowed parameters:
            foreach (KeyValuePair <string, string> parameter in parameters.Settings)
            {
                switch (parameter.Key)
                {
                case PARAMETERCMD:
                case PARAMETERRID:
                case PARAMETEREMAIL:
                case PARAMETERSTRAND:
                case PARAMETERSENSITIVITY:
                case PARAMETERFORMATTYPE:
                    result.IsValid           = false;
                    result.ValidationErrors += string.Format(CultureInfo.InvariantCulture,
                                                             Resources.PARAMETERUNKNOWNNCBI,
                                                             parameter.Key);
                    break;

                default:
                    break;
                }
            }

            return(result);
        }
Esempio n. 29
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the Bio.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null == sequence)
            {
                throw new ArgumentNullException("sequence");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            if (!string.IsNullOrEmpty(Configuration.EmailAddress))
            {
                if (!parameters.Settings.ContainsKey(ParameterEmail))
                {
                    parameters.Add(ParameterEmail, Configuration.EmailAddress);
                }
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // Submit the job to server
            inputParams blastRequest = GetRequestParameter(parameters);

            blastRequest.appxml = AppXmlYes;
            blastRequest.async  = true;

            data[] mydata = new data[1];
            mydata[0]      = new data();
            mydata[0].type = SequenceType;

            mydata[0].content = FastAFormatter.FormatString(sequence);

            requestIdentifier = blastClient.runWUBlast(blastRequest, mydata);

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                BlastThreadParameter threadParameter = new BlastThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                workerThread = new BackgroundWorker();
                workerThread.WorkerSupportsCancellation = true;
                workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }