Source code for MSQuant: PILinOut.cs, MSQlib1/src/utility/PILinOut.cs.

Table of contents page.

Home page for MSQuant.

/****************************************************************************
 * Copyright (C) 2008 Peter Mortensen and Matthias Mann                     *
 * This file is part of MSQuant.                                            *
 *                                                                          *
 * MSQuant is distributed under the terms of                                *
 * the GNU General Public License. See src/COPYING.TXT or                   *
 * <http://www.gnu.org/licenses/gpl.txt> for details.                       *
 *                                                                          *
 * MSQuant is free software; you can redistribute it                        *
 * and/or modify it under the terms of the GNU                              *
 * General Public License as published by the Free                          *
 * Software Foundation; either version 2 of the                             *
 * License, or (at your option) any later version.                          *
 *                                                                          *
 * MSQuant is distributed in the hope that it will be                       *
 * useful, but WITHOUT ANY WARRANTY; without even the                       *
 * implied warranty of MERCHANTABILITY or FITNESS FOR                       *
 * A PARTICULAR PURPOSE.  See the GNU General Public                        *
 * License for more details.                                                *
 *                                                                          *
 * You should have received a copy of the GNU General                       *
 * Public License along with MSQuant; if not, write to                      *
 * the Free Software Foundation, Inc., 59 Temple                            *
 * Place, Suite 330, Boston, MA  02111-1307  USA                            *
 *                                                                          *
 * Purpose: Holds XYZ, see below for documentation.                         *
 *                                                                          *
 ****************************************************************************/

/****************************************************************************
 *                               CEBI                                       *
 *                    Software Development Group                            *
 *                         Peter Mortensen                                  *
 *                E-mail: NUKESPAMMERSdrmortensen@get2netZZZZZZ.dk          *
 *                 WWW: http://www.cebi.sdu.dk/                             *
 *                                                                          *
 *  Program for post-processing of result from search in mass               *
 *    spectrometric data.                                                   *
 *                                                                          *
 *    FILENAME:   PILinOut.cs                                               *
 *    TYPE:       CSHARP                                                    *
 *                                                                          *
 * CREATED: PM 2008-03-14   Vrs 1.0. Translated from PILinOut.vb            *
 * UPDATED: PM 2008-xx-xx                                                   *
 *                                                                          *
 *                                                                          *
 ****************************************************************************/

//Future:
// 1.


using System; //For Exception and others.
using System.Diagnostics; //For Trace.
using System.Collections; //For ArrayList.
using System.Collections.Generic; //For List.
using System.IO; //For FileStream and File.
using System.Text; //For StringBuilder


////Note: this will only work if a reference is added manually
//// in Visual Studio: menu Project/Add Reference/
//// System.Runtime.Serialization.Formatters.soap/Select/OK.
//Imports System.Runtime.Serialization.Formatters.soap
//Imports System.Runtime.Serialization 'For StreamingContext

using massSpectrometryBase; //For signalStructure

//Note: "Excel.Application" and "Excel.Worksheet" requires adding
//      reference to project:
//
// menu Project/Add Reference/tab COM/Select,
// select "Microsoft Excel 9.0 Object Library"
//
// or:
// menu Project/Add Reference/tab Browse/,
// D:\Program Files\Microsoft Office\Office\EXCEL8.OLB



//****************************************************************************
//d$ <summary>
//d$ Purpose: Namespace for application independent and domain independent
//d$ utility classes (that could be reused in any application,
//d$ not just mass spectrometric applications.)
//d$ <see cref="T:VBXMLDoc.CVBXMLDoc" />.
//d$ <isUnitTest></isUnitTest>
//d$ <applicationname>XYZ</applicationname>
//d$ <author>Peter Mortensen</author>
//d$ <seealso>http://www.cebi.sdu.dk/</seealso>
//d$ <codetype>PLATFORM independent</codetype>
//d$ </summary>
namespace SDUPutility
{

    //Changed PM_BROKENEXPORT 2008-05-28
    public enum targetEnum
    {

        //Note: do not change name of any these as XML serialisation
        //      use a direct ToString method and not an explicit 
        //      conversion from internal representation to 
        //      external representation.

        enumExportToOpenOffice = 439,
        enumExportToExcel,
        enumExportToUserSelectedApp,
        enumExportToFile,

        //Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
        enumExportUndefined
    } //targetEnum


    //Changed PM_BROKENEXPORT 2008-05-28
    //This should moved to a general place as it is not specific to 
    //exporting protein/peptides. It is going to be or is already 
    //used for e.g. exporting spectrum datapoints in the Quantitation window.
    public struct exportTargetSettingsStruct
    {     
        public targetEnum target;
        public string userAppPath;
        public string filePath;
        public bool openFileAfterGeneration;
        
        //Perhaps later
        // helper field, list of common install locations for Excel and Open Office.
        
        //Place somewhere else?
        public static exportTargetSettingsStruct defaultExportTargetSettings()
        {
            
            exportTargetSettingsStruct toReturn;
            toReturn.filePath = "c:\\temp42.txt";
            toReturn.openFileAfterGeneration = false;

            //Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
            //toReturn.target = targetEnum.enumExportToOpenOffice;
            toReturn.target = targetEnum.enumExportUndefined;

            toReturn.userAppPath = "xyz";
            
            return toReturn;
        } //defaultExportTargetSettings
        
        
        //Place somewhere else?
        public static string exportTargetSettingsShortSummary(
          exportTargetSettingsStruct anInExportTargetSettings)
        {
            
            //Patterned on pepFilterShortSummary().
            
            string toReturn = null;
            StringBuilder summSB = new StringBuilder(80);
            
            switch (anInExportTargetSettings.target) 
            {
                case targetEnum.enumExportToOpenOffice:
                    summSB.Append("Calc (Open Office)");
                    break;
                
                case targetEnum.enumExportToExcel:
                    summSB.Append("Excel (M$ Office)");
                    break;
                
                case targetEnum.enumExportToUserSelectedApp:
                    
                    string fname = Path.GetFileName(
                      anInExportTargetSettings.userAppPath);
                    summSB.Append(fname);
                    break;
                
                case targetEnum.enumExportToFile:
                    
                    string fname2 = Path.GetFileName(
                      anInExportTargetSettings.filePath);
                    summSB.Append(fname2);

                    if (anInExportTargetSettings.openFileAfterGeneration)
                    {
                        summSB.Append(". Opening it.");
                    }
                    break;
                
                default:
                    Trace.Assert(false, "PIL ASSERT. Select Case never fall-through");
                    break;
            }
            
            toReturn = summSB.ToString();
            return toReturn;
        } //exportTargetSettingsShortSummary()
        
    } //exportTargetSettingsStruct


    //Move this class to an appropriate place, but still in Namespace SDUPutility.
    public class PILInputOutput
    {

        //Moved to somewhere else.
        //private struct datapointSeparationInfoStructure
        //{
        //    public double datapointSeparation;
        //    public double startX;
        //    public double endX;
        //}

        //Changed PM_CSHARP 2008-03-13
        //public static string LINEEND = Constants.vbCr + Constants.vbLf;
        public static string LINEEND = "\r\n";


        //****************************************************************************
        //* <placeholder for header>                                                 *
        //****************************************************************************
        public static void pushToFile(string aFileName, string aStr)
        {

            FileStream saveFile = File.OpenWrite(aFileName);

            //Changed PM_NO_APPENDTOFILE 2003-11-04
            saveFile.SetLength(0);
            //Delete existing content...

            saveFile.Seek(0, SeekOrigin.End);
            StreamWriter strWriter = new StreamWriter(saveFile);
            // strWriter.Write(txtProteinHits.Text)
            strWriter.Write(aStr);
            strWriter.Flush();
            //This is necessary.
            strWriter.Close();

            //Changed PM_CLOSE_FILE_BUG 2008-04-24. File could not be renamed
            //or deleted until the program was terminated!!!
            saveFile.Close();
        } //pushToFile()


        //****************************************************************************
        //* <placeholder for header>                                                 *
        //****************************************************************************
        private static string generateCmdStr(
          List<string> anInLocs, out string anOutappStr)
        {
            //No longer used:
            //  string anInFileToOpen

            string app = "";
            foreach (string someItem in anInLocs)
            {
                if (app.Length == 0)
                {
                    //If the application does not exist in
                    //any of the predefined location then drop
                    //the absolute path in order to let the
                    //PATH variable decide what should be
                    //opened. Or the other way around: if it
                    //does not exist in one of the predefined
                    //locations and not in the PATH then the
                    //user can add the application directory
                    //to the PATH so export works...
                    app = Path.GetFileName(someItem);
                }

                if (File.Exists(someItem))
                {
                    app = someItem;
                    break;
                }
            } //Through anInLocs

            anOutappStr = app;

            //Changed PM_EXPORT_TEMPFILES_IN_APPFOLDER 2008-09-15.
            // Process.Start wants single quotes...
            //string toReturn =
            //  @"""" + app + @""" """ + anInFileToOpen + @"""";
            //string toReturn =
            //  @"'" + app + @"' '" + anInFileToOpen + @"'";
            string toReturn =
              @"""" + app + @"""";

            return toReturn;
        } //generateCmdStr()


        //Changed PM_REFACTOR 2003-03-21
        //To be moved to an application object.
        //****************************************************************************
        //* <placeholder for header>                                                 *
        //****************************************************************************
        public static void pushToTarget(
          string aStr, exportTargetSettingsStruct anExportTargetSettings, 
          ref string aTempFolder)
        {
            //Moved from QuantWindow.vb.

            Trace.Assert(aStr != null,
                "PIL ASSERT. Could not export to excel. " + 
                "String passed pushToExcel() is undefined!. " + 
                "Contact a developer near you.");

            //Changed PM_ASKFOR_EXPORTTARGET_FIRSTTIME 2008-12-18
            //Clients must have checked and corrected/changed it...
            Trace.Assert(
              anExportTargetSettings.target != targetEnum.enumExportUndefined,
              "PIL ASSERT. Internal error. " +
              "The export target is undefined. " +
              "Contact a developer near you.");

            int len = aStr.Length;
            if (len > 0)
            {
                //Changed PM_BROKENEXPORT 2008-05-28
                //First save information off to temporary file.
                //string tempSaveName = @"c:\_exportTemp7.txt";
                string hms = PILInputOutput.timeAsHMS();

                //Simulate Excel problem with space in file name.
                ////Changed PM_EXPORT_TEMPFILES_IN_APPFOLDER 2008-09-14
                ////string folder = @"c:\_exportTemp";
                //string folder = aTempFolder + @"\_exportTemp";
                //string folder = aTempFolder + @"\_export Temp";
                
                //string filePrefix = @"_exportTemp"; //Change current directory when the process is started below...

                //Changed PM_WINDOWS_CLIPBOARD_TROUBLE 2008-10-16
                //  Try-out.
                //Temp!!!!!!!!!!!!!!!!!! 
                //string filePrefix = @"ZZZZZ_exportTemp"; //Change current directory when the process is started below...
                
                string filePrefix = @"_exportTemp";

                string tempSaveName2 = filePrefix + hms + ".txt";
                string fullTempSaveName =
                  aTempFolder + Path.DirectorySeparatorChar + tempSaveName2;
                string fullTempSaveNameEscaped =
                  @"""" + fullTempSaveName + @"""";
                

                string targetInfo = ""; //Used if an exception occurs.
                string appStr = "";

                string args = tempSaveName2;

                bool launchApp = true;

                //Ignore empty strings...
                try
                {
                    //Old way.
                    // //Changed PM_SAVEMEMORY_CLIPBOARD 2006-07-27. Disabled
                    // //to avoid possible out-of-memory exception during this
                    // //function.
                    // // Clipboard.SetDataObject(aStr) 'Possible work-around for people
                    // // 'where export to Excel does not work: at least put it into
                    // // 'the clipboard. However this seemed not to work.
                    //
                    // Excel.Application EXL = new Excel.Application();
                    //
                    // if ((EXL != null))
                    // {
                    //     //Dim WSheet As New Excel.Worksheet
                    //     //WSheet = _
                    //     //  CType(EXL.Workbooks.Add.Worksheets.Add, Excel.Worksheet)
                    //
                    //     //Need to raise an exception here.
                    //     Excel.Worksheet WSheet = new Excel.Worksheet();
                    //
                    //     //Changed PM_CSHARP 2008-03-13
                    //     //(Excel.Worksheet)
                    //     //WSheet = EXL.Workbooks.Add.Worksheets.Add();
                    //     //To use the paste function it has to go through the clipboard.
                    //     //EXL.Workbooks.Add(null).Worksheets.Add();
                    //     object sheet =
                    //         EXL.Workbooks.Add(null).Worksheets.Add(null, null, null, null);
                    //     WSheet = (Excel.Worksheet) sheet;
                    //
                    //
                    //
                    //     //Changed PM_REFACTOR 2007-11-30
                    //     //Why do we need to have the whole "path" after we moved
                    //     //this file to this project??? We do have a reference
                    //     //to System.Windows.Forms in the project.
                    //     System.Windows.Forms.Clipboard.SetDataObject(aStr);
                    //
                    //     WSheet.Paste(null,null);
                    //
                    //     EXL.Visible = true;
                    // }

                    PILInputOutput.pushToFile(fullTempSaveName, aStr);
                    string cmdStr = "";

                    switch (anExportTargetSettings.target) 
                    {
                        case targetEnum.enumExportToOpenOffice:
                            List<string> locs = new List<string>(5);
                            locs.Add(
                              @"C:\Program Files\OpenOffice.org 2.4\program\scalc.exe");

                            //Changed PM_OPENOFFICE3 2008-12-19
                            locs.Add(
                              @"C:\Program Files\OpenOffice.org 3\program\scalc.exe");
                            cmdStr = generateCmdStr(locs, out appStr);

                            targetInfo = "Export to Calc (Open Office)";
                            break;

                        case targetEnum.enumExportToExcel:
                            List<string> locs2 = new List<string>(5);
                            locs2.Add(
                              @"C:\Program Files\Microsoft Office\Office\EXCEL.EXE");
                            locs2.Add(
                              @"C:\Program Files\Microsoft Office\Office11\EXCEL.EXE");
                            cmdStr = generateCmdStr(locs2, out appStr);

                            targetInfo = "Export to Excel (M$ Office)";
                            break;

                        case targetEnum.enumExportToUserSelectedApp:

                            //Should we use single quotes as for Open Office and Excel???

                            cmdStr = 
                              @"""" + 
                              anExportTargetSettings.userAppPath +
                              @"""" +
                              " " +
                              fullTempSaveNameEscaped;
                            appStr = anExportTargetSettings.userAppPath;

                            targetInfo = 
                              "Export to user selected application, " +
                              appStr + ". ";
                            break;

                        case targetEnum.enumExportToFile:
                            string exportFile = anExportTargetSettings.filePath;
                            PILInputOutput.pushToFile( exportFile, aStr);

                            args = exportFile; //Overwrite...

                            targetInfo =
                              "Export to file " +
                              exportFile + ". ";
                            launchApp = false;

                            if (anExportTargetSettings.openFileAfterGeneration)
                            {
                                launchApp = true;

                                cmdStr = 
                                  // "%windir%\explorer.exe " + 
                                  @" """ +
                                  fullTempSaveName +
                                  @"""";

                                targetInfo =
                                  "Export to file " +
                                  exportFile + " and opening the Windows way ";

                                appStr = args; //Let Windows settings decide how
                                //  it is opened.
                                args = "";
                            }
                            break;

                        default:
                            Trace.Assert(
                              false, 
                              "PIL ASSERT. Select Case never fall-through");
                            break;
                    } //switch

                    //if (cmdStr.Length != 0)
                    if (launchApp)
                    {
                        //string finalCmdStr = 
                        //  //"%windir%\\explorer.exe " +
                        //  cmdStr;

                        // "StartInfo: sets the properties to pass to the Start
                        // method of the Process. StartInfo represents the set of
                        // parameters to use to start a process. When Start is
                        // called, the StartInfo is used to specify the process
                        // to start. The only necessary StartInfo member to set
                        // is the FileName property.
                        //
                        // Starting a process by specifying the FileName property
                        // is similar to typing the information in the Run dialog
                        // box of the Windows Start menu.
                        //
                        // Therefore, the FileName property does not need to
                        // represent an executable file. It can be of any file
                        // type for which the extension has been associated with
                        // an application installed on the system.
                        //
                        // For example the FileName can have a .txt extension if
                        // you have associated text files with an editor, such as
                        // Notepad, or it can have a .doc if you have
                        // associated.doc files with a word processing tool, such
                        // as Microsoft Word. Similarly, in the same way that the
                        // Run dialog box can accept an executable file name with
                        // or without the .exe extension, the .exe extension is
                        // optional in the FileName member. For example, you can
                        // set the FileName property to either "Notepad.exe" or
                        // "Notepad".

                        //Process myProcess = new Process();
                        //myProcess.StartInfo.FileName = finalCmdStr;


                        //Process.Start(appStr, args);
                        System.Diagnostics.ProcessStartInfo psInfo = 
                           new System.Diagnostics.ProcessStartInfo(appStr);

                        //Is it superfluous to set field FileName below when
                        //we also pass one argument to the ProcessStartInfo()?

                        //psInfo.WindowStyle = 
                        //  System.Diagnostics.ProcessWindowStyle.Normal;
                        psInfo.FileName = appStr; //Is a full path.
                        psInfo.Arguments = args;
                        psInfo.WorkingDirectory = aTempFolder; //OK, except 
                        //perhaps for saving to file and opening using Windows
                        //settings. In this case the saved file may be in a
                        //completely different directory.
                        
                        Process myProcess =
                          System.Diagnostics.Process.Start(psInfo);
                    }

                }
                catch (Exception exceptionObject)
                {
                    //Use information from exceptionObject in the error message?

                    string msgStr = 
                        //"An error happend while trying to export to Excel. " + 
                        //"On some systems it does not work (we have not yet found the reason). " + 
                        //"The work-around is to use the corresponding 'Save ...' menu " + 
                        //"command instead of the 'Export' menu command.";
                        "An error happend while trying to export to target. " +
                        "Information about target: " + targetInfo + 
                        " (" + appStr + "/ " + args + "). " +
                        "The application to use for export may not exist in " +
                        "typical install locations. " +
                        "You can make it work by \n\n" +
                        "1) Using the Target button in the export " +
                        "proteins/peptides dialog (Protein List window, " +
                        "menu File/Export Proteins and " +
                        "Peptides Information...). " +
                        "An actual export must be performed before the " +
                        "target setting is changed - this is also a way " +
                        "to test that it works before attempting other " +
                        "kinds of exports.\n" +
                        "or \n2) Adding the path (of " + 
                        "the application to export to) to the PATH environment " +
                        "variable (like it is done for the Analyst/QSTAR " +
                        "application - see " + AppConstants.LONG_APP + " home page)."
                        ;
                    System.Windows.Forms.MessageBox.Show(msgStr);
                } //Exception handler.
            } //Non-empty string
        } //pushToTarget()


        //****************************************************************************
        //* <placeholder for header>                                                 *
        //****************************************************************************
        public static string emptyForNothing(ref string anInStr)
        {
            string toReturn = anInStr;
            if (anInStr == null)
            {
                toReturn = "";
            }
            return toReturn;
        } //emptyForNothing


        //Moved to somewhere else.
        // //Move somewhere else
        // //****************************************************************************
        // //* <placeholder for header>                                                 *
        // //****************************************************************************
        // //* Real type for anInsignalToUse is signalStructure. *
        // public static string dumpXpointsInOneLine(ref ArrayList anInsignalToUse)
        // {
        //     StringBuilder strSB = new StringBuilder(1024);
        //     int lastIndex = anInsignalToUse.Count - 1;
        //     int index = 0;
        //     foreach (signalStructure someSignal in anInsignalToUse)
        //     {
        //         double curX = someSignal.Xsig;
        // 
        //         strSB.Append(someSignal.Xsig);
        // 
        //         if (index != lastIndex)
        //         {
        //             strSB.Append("\t");
        //         }
        //         index += 1;
        //     }
        //     return strSB.ToString();
        // } //dumpXpointsInOneLine


        //Moved to somewhere else.
        ////Move somewhere else
        // //****************************************************************************
        // //* <placeholder for header>                                                 *
        // //****************************************************************************
        // //* Real type for anInsignalToUse is signalStructure. *
        // public static string dumpXYSpectrumPoints(
        //     ref List<massSpectrometryBase.signalStructure> anInsignalToUse,
        //     string aDataTitle,
        //     ref string anInAAseq,
        //     ref string anInAccNum,
        //     ref string anInDatatypeStr,
        //     bool anInInsertZeros)
        // {
        //
        //     //Old:
        //     // ByRef anInsignalToUse As ArrayList, _
        //
        //     string toReturn = "";
        //
        //     StringBuilder strSB = new StringBuilder(30000);
        //     strSB.Append(anInDatatypeStr);
        //     strSB.Append(" for peptide ");
        //     strSB.Append(anInAAseq);
        //     strSB.Append(" in ");
        //     strSB.Append(anInAccNum);
        //     strSB.Append("\r\n");
        //
        //     string header = aDataTitle;
        //     strSB.Append("Spectrum header: ");
        //     strSB.Append(header);
        //     strSB.Append("\r\n");
        //     strSB.Append("\r\n");
        //
        //     strSB.Append("X");
        //     strSB.Append("\t");
        //     strSB.Append("Y");
        //     strSB.Append("\r\n");
        //
        //     //In order to get an appropriate display with tools that draw
        //     //lines between the datapoints we will insert some datapoints
        //     //with an intensity of 0.
        //
        //     //First iteration: find lowest datapoint separation. This will
        //     //be used as a default if no other value can found (e.g. only
        //     //one datapoint in a mass range.
        //     double prevX = -100;
        //     double globalSmallestXdistance = 10;
        //     foreach (signalStructure someSignal in anInsignalToUse)
        //     {
        //         double curX = someSignal.Xsig;
        //         double distance = curX - prevX;
        //         if (distance < globalSmallestXdistance)
        //         {
        //             globalSmallestXdistance = distance;
        //         }
        //         prevX = curX;
        //     }
        //
        //     //Second iteration: find typical data point separation.
        //     //This may depend on the mass.
        //
        //     //Changed PM_TYPESAFE 2008-03-13
        //     //ArrayList dataDistance = new ArrayList();
        //     int cap = 10; //Can we find .
        //     List<datapointSeparationInfoStructure> dataDistance2 =
        //       new List<datapointSeparationInfoStructure>(cap);
        //
        //     double rangeSize = 100.0;
        //     //100 Da
        //     double halfRangeSize = rangeSize / 2;
        //     double curStartX = -100.0;
        //     double curEndX = -100.0;
        //
        //     double currentSmallestXdistance = 1000.0;
        //
        //     prevX = -100;
        //     int signals = anInsignalToUse.Count;
        //     int count = 0;
        //     foreach (signalStructure someSignal in anInsignalToUse)
        //     {
        //         count += 1;
        //         double curX = someSignal.Xsig;
        //         double distance = curX - prevX;
        //
        //         if (curStartX < 0)
        //         {
        //             curStartX = curX;
        //             curEndX = curStartX + rangeSize;
        //         }
        //
        //         //This means we may use a distance to a datapoint into
        //         //the next mass segment.
        //         if (distance < currentSmallestXdistance)
        //         {
        //             currentSmallestXdistance = distance;
        //         }
        //
        //         bool lastSignal = count == signals;
        //         if (lastSignal)
        //         {
        //             int peter7 = 7;
        //         }
        //
        //         if (curX > curEndX || lastSignal)
        //         {
        //             //Last part is
        //             //to get the very last segment.
        //             if (lastSignal)
        //             {
        //                 currentSmallestXdistance = -10.0;
        //                 curEndX = curX + 5.0;
        //             }
        //
        //             if (currentSmallestXdistance > halfRangeSize)
        //             {
        //                 //No datapoints or only one or a few in range. Continue/extend range.
        //                 curEndX = curEndX + rangeSize;
        //             }
        //             else
        //             {
        //                 datapointSeparationInfoStructure datapointSeparationInfo;
        //                 datapointSeparationInfo.datapointSeparation = currentSmallestXdistance;
        //                 datapointSeparationInfo.startX = curStartX;
        //                 datapointSeparationInfo.endX = curEndX;
        //                 dataDistance2.Add(datapointSeparationInfo);
        //
        //                 currentSmallestXdistance = 1000.0;
        //                 //Reset for next mass range.
        //                 curStartX = curEndX;
        //                 curEndX += rangeSize;
        //             }
        //         }
        //         prevX = curX;
        //     }
        //
        //     int curSegmentIndex = 0;
        //     datapointSeparationInfoStructure curSegment;
        //     curSegment.endX = -10;
        //     curSegment.datapointSeparation = -44444.444;
        //
        //
        //     //So we will get started correct.
        //     prevX = -10.0;
        //     foreach (signalStructure someSignal in anInsignalToUse)
        //     {
        //         double curX = someSignal.Xsig;
        //         if (prevX < 0)
        //         {
        //             prevX = curX;
        //             //So we don't anything inserted to the
        //             // left of the first point...
        //         }
        //         double distance = curX - prevX;
        //
        //         if (curX >= curSegment.endX)
        //         {
        //             //Update to new segment
        //             while (
        //                 curX >=
        //                 dataDistance2[curSegmentIndex].endX)
        //             {
        //                 curSegmentIndex += 1;
        //             }
        //
        //             curSegment = dataDistance2[curSegmentIndex];
        //         }
        //
        //         //If the distance to the previous datapoint is too big then
        //         //we insert 2 datapoints with an intensity of zero, one a little
        //         //bit higher close to the previous data point and one
        //         //a little bit lower than the current datapoint.
        //
        //         double sep = curSegment.datapointSeparation;
        //
        //         Trace.Assert( sep >= -40000.0,
        //           "PIL ASSERT. curSegment.datapointSeparation is undefined: " +
        //           sep.ToString());
        //
        //         if (anInInsertZeros && distance > sep * 1.5)
        //         {
        //             double closeToPointDistance = 0.25 * curSegment.datapointSeparation;
        //
        //             strSB.Append(prevX + closeToPointDistance);
        //             strSB.Append("\t");
        //             strSB.Append(0);
        //             strSB.Append("\r\n");
        //
        //             strSB.Append(curX - closeToPointDistance);
        //             strSB.Append("\t");
        //             strSB.Append(0);
        //             strSB.Append("\r\n");
        //         }
        //
        //         strSB.Append(someSignal.Xsig.ToString("0.00000"));
        //         strSB.Append("\t");
        //         strSB.Append(someSignal.Ysig.ToString("0.00000"));
        //
        //         strSB.Append("\r\n");
        //
        //         prevX = curX;
        //     }
        //     toReturn = strSB.ToString();
        //
        //     return toReturn;
        // } //dumpXYSpectrumPoints


        //****************************************************************************
        //* <placeholder for header>                                                 *
        //****************************************************************************
        public static bool pushToUserSelectedFile2(
            string aStr,
            ref System.Windows.Forms.SaveFileDialog anInSaveFileDialog,
            //Note: System.Windows.Forms must be added as a reference to the project.

            ref string anOutInfoLabelTextRef,
            string aOKStatusStr,
            string aStartFileName)
        {
            bool wasSaved = false;

            int len = aStr.Length;
            if (len > 0)
            {
                //Ignore empty strings...
                try
                {
                    anInSaveFileDialog.AddExtension = true;
                    anInSaveFileDialog.Filter = "Plain Text (*.txt)|*.txt";
                    if (aStartFileName != "")
                    {
                        anInSaveFileDialog.FileName = aStartFileName;
                    }
                    if (anInSaveFileDialog.ShowDialog() == 
                        System.Windows.Forms.DialogResult.OK)
                    {
                        //Why isn't the file extension added??????????

                        PILInputOutput.pushToFile(anInSaveFileDialog.FileName, aStr);

                        wasSaved = true;

                        //lblProtInfo.Text = aOKStatusStr
                        anOutInfoLabelTextRef = aOKStatusStr;
                    }
                }
                catch (Exception exceptionObject)
                {
                    string errStr =
                        "Could not save to file " +
                        anInSaveFileDialog.FileName +
                        ". (" +
                        exceptionObject.ToString() +
                        ").";
                    //Interaction.MsgBox(errStr);
                    System.Windows.Forms.MessageBox.Show(errStr);

                    //lblProtInfo.Text = errStr
                    anOutInfoLabelTextRef = errStr;
                }
            } //Non-empty string

            return wasSaved;
        } //pushToUserSelectedFile2()


        //Changed PM_MB3_RELOCATION 2008-05-23
        //****************************************************************************
        //* <placeholder for header>                                                 *
        //****************************************************************************
        public static string newFolderBase(
            ref string anOldLocFile, ref string aNewFolderBase)
        {
            string fileName = Path.GetFileName(anOldLocFile);

            //Replace with new folder base.
            //string sep = ;
            string toReturn =
                aNewFolderBase + Path.DirectorySeparatorChar.ToString() + fileName;
            
            return toReturn;
        } //newFolderBase


        //Changed PM_REFACTOR 2008-05-29. Moved to somewhere else.
        //Should be moved to a more logical place...
        //****************************************************************************
        //* <placeholder for header> *
        //****************************************************************************
        public static string timeAsHMS()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(30);

            System.DateTime now = System.DateTime.Now;

            sb.Append(now.Hour.ToString("00"));
            sb.Append("h");
            sb.Append(now.Minute.ToString("00"));
            sb.Append("m");
            sb.Append(now.Second.ToString("00"));
            sb.Append("s");

            return sb.ToString();
        } //timeAsHMS()
        

    } //class PILInputOutput




} //SDUPutility

    

    

Generated by script codePublish.pl at 2009-01-05T15:20:59.