Exemplo n.º 1
0
        public bool DocumentEcho(string fileName)
        {
            string fileWithExt = Path.GetFileNameWithoutExtension(fileName);

            GICO.WriteLine(String.Format("{0}> {1} {2}:{3}", fileWithExt, DateTime.Now, "Download", fileName));
            return(true);
        }
    private static void SendMail(GridProteinFoldingEntities ctx, Guid guid, string message, string webServerName)
    {
        //Sent e-mail
        SmtpClient   smtpClient = new SmtpClient();
        Process      process    = ctx.Process.FirstOrDefault(p => p.guid == guid);
        aspnet_Users user       = new GridProteinFolding_MemberShipEntities().aspnet_Users.FirstOrDefault(u => u.UserId == process.userId);

        try
        {
            string key = string.Empty;

            System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(user.aspnet_Membership.LoweredEmail, user.UserName);
            string subject = "eFolding - Simulation";
            string body    = "Simulation " + process.guid.ToString() + message;

            body += "</br>Direct access: " + string.Format("http://" + webServerName + "/Pages/SimulationAddEdit.aspx?guId={0}", process.guid.ToString());

            smtpClient.Send(to, subject, body);
        }
        catch (Exception ex)
        {
            GICO.WriteLine(ex);
        }
        finally
        {
            smtpClient = null;
        }
    }
        void Upload(ServiceParamWcf paramWCF)
        {
            try
            {
                Guid guid = paramWCF.param.dataToProcess.Guid;

                //string path = ConfigurationManager.AppSettings["dirBaseClient"].ToString() + guid;
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\efolding.fcfrp.usp.br\Client\" + guid;
                //string destPath = ConfigurationManager.AppSettings["uploadFolder"].ToString();
                string destPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\efolding.fcfrp.usp.br\Client\_temp\" + guid;

                SIO.FileInfo sourceFile   = new File().FileInfos(path + ".zip");
                SIO.FileInfo destFileName = new File().FileInfos(destPath + ".zip");

                //Valida se arquivo não existe, de uma tentativa de enviado anterior
                if (previousSimulation == false) //!File.Exists(destFileName.FullName) &&
                {
                    //Compress FILE
                    //GICO.WriteLine(guid, rm.GetString("UploadCompression"));
                    GICO.WriteLine(guid, "UploadCompression");
                    Compression.Compress(guid, sourceFile, new ExtendedDirectoryInfo(path), true, string.Empty);

                    if (File.Exists(destFileName.FullName))
                    {
                        File.Delete(destFileName.FullName);
                    }

                    //GICO.WriteLine(guid, rm.GetString("UploadFileMove"));
                    GICO.WriteLine(guid, "UploadFileMove");
                    File.Move(sourceFile.FullName, destFileName.FullName);
                }

                GICO.WriteLine(guid, ExtendedString.Format("Upload file {0}..", destFileName.Name));

                ProxyDocumentManagmentClient.DocumentEcho(destFileName);
                using (System.IO.BinaryReader fs = new System.IO.BinaryReader(System.IO.File.Open(destFileName.FullName, System.IO.FileMode.Open)))
                {
                    int  pos    = 0;
                    bool append = false;
                    int  length = (int)fs.BaseStream.Length;

                    while (pos < length)
                    {
                        byte[] bytes = fs.ReadBytes(1024 * 1024);
                        ProxyDocumentManagmentClient.UploadDocument(destFileName, bytes, append);

                        append = true;
                        pos   += 1024 * 1024;
                    }
                }

                //Extract
                GICO.WriteLine(guid, ExtendedString.Format("Extract file {0}..", destFileName.Name));
                ProxyDocumentManagmentClient.ExtractDocument(destFileName);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 4
0
        public static Process GetOneProcess(RequestorInfo requestorInfo)
        {
            Process tempProcess = new Process();

            using (GridProteinFoldingEntities ctx = new GridProteinFoldingEntities())
            {
                tempProcess = ctx.Process.Include("DataToProcess").Include("DataToResult").Include("Model").Include("ConfigApp").Include("Output").FirstOrDefault(p => p.status_id == 1); // || p.status_id == 3 || p.status_id == 4);

                try
                {
                    if (tempProcess != null)
                    {
                        //TRATATIVA de INTEGRIDADE dos DADOS
                        ParseIntegration(ref tempProcess);
                        //SETA STATUS, se possível
                        SetStatus(ref tempProcess, ref requestorInfo);
                    }
                    return(tempProcess);
                }
                catch (Exception ex)
                {
                    GICO.WriteLine(String.Format("{0}> {1} ({2} {3})", tempProcess.guid.ToString(), DateTime.Now, "Exception:", ex.Message.ToString()));

                    BasicEnums.State newstatus = BasicEnums.State.Error;
                    SetOneProcess(tempProcess.guid, newstatus, requestorInfo);

                    return(null);
                }
            }
        }
Exemplo n.º 5
0
        private void OpenSheet(Param param)
        {
            try
            {
                String strWkName = "ScatterData";
                pWorksheet = pOrigin.FindWorksheet(strWkName);
                if (pWorksheet == null) //if check don't exist, create workbook
                {
                    strWkName = (String)pOrigin.CreatePage((int)Origin.PAGETYPES.OPT_WORKSHEET, strWkName, "Origin", 2);
                }
                pWorksheet = (Worksheet)pOrigin.WorksheetPages[strWkName].Layers[0];

                //prepare XYZ column for putting data
                pWorksheet.Cols = 3;

                Column colA = pWorksheet.Columns[0];
                colA.Type = COLTYPES.COLTYPE_X;

                Column colB = pWorksheet.Columns[1];
                colB.Type = COLTYPES.COLTYPE_Y;

                Column colC = pWorksheet.Columns[2];
                colC.Type = COLTYPES.COLTYPE_Z;

                //prepare graph layer for plotting
                String strGrName = "3DScatterPlot"; //if check don't exist, create it.
                pGraphLayer = pOrigin.FindGraphLayer(strGrName);
                if (pGraphLayer == null)
                {
                    strGrName = (String)pOrigin.CreatePage((int)Origin.PAGETYPES.OPT_GRAPH, strGrName, "3D", 2); //3D scatter need "3D" template
                }
                pGraphLayer = (GraphLayer)pOrigin.GraphPages[strGrName].Layers[0];

                //parepare XYZDataRange
                DataRange drXYZ = pWorksheet.NewDataRange(0, 0, -1, -1);

                //plot 3D scatter on GraphLayer
                String strPlotName = "ScatterData_C"; //if exists, don't add new plot, plot name is related to workbook name and column name.

                pDataPlot = pGraphLayer.DataPlots[strPlotName];
                if (pDataPlot == null)
                {
                    pDataPlot = pGraphLayer.DataPlots.Add(drXYZ, PLOTTYPES.IDM_PLOT_3D_SCATTER);
                }

                //force axis rescale as auto to make plot visible
                pGraphLayer.Execute("layer.x.rescale=3");
                pGraphLayer.Execute("layer.y.rescale=3");
                pGraphLayer.Execute("layer.z.rescale=3");

                SentData(param);
            }
            catch (System.Exception ex)
            {
                String strMsg = ResourceException.Origin_FailedPlotting;
                GICO.WriteLine(strMsg);
                GICO.WriteLine(ex);
                throw;
            }
        }
Exemplo n.º 6
0
        private void ModelForFile(ref double cont, ref int cadeiaIdeal, ref int cadeiaReal, ref int cadeiaSoft, ref int cadeiaError)
        {
            string[] lines = Regex.Split(AppConfigClient.Param.dataToProcess.file, "\r\n");

            //foreach (string line in lines)
            for (int i = 0; i < lines.Count(); i++)
            {
                string line = lines[i];
                try
                {
                    Structs.BasicStructs.Point tempCoord = new Structs.BasicStructs.Point();
                    string[] coord = line.Split(new char[] { '\t' });
                    tempCoord.x = Convert.ToInt32(coord[0]);
                    tempCoord.y = Convert.ToInt32(coord[1]);
                    tempCoord.z = Convert.ToInt32(coord[2]);
                    GCPS.chain.r.Add(tempCoord);
                }
                catch (FormatException ex)
                {
                    GICO.WriteLine(ex);
                }
            }

            ProcessMonomero(ref cont, ref cadeiaIdeal, ref cadeiaReal, ref cadeiaSoft, ref cadeiaError);

            //Prepara aplicação para gerar uma nova ISEM
            Protein.ClearAppToGenNewIsem();
        }
Exemplo n.º 7
0
        public void MoveFile()
        {
            try
            {
                string dirSouce   = dirBaseWeb.FullName() + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirDebug;
                string dirDestine = dirBaseWeb.FullName() + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirResult;


                GridProteinFolding.Middle.Helpers.IOHelpers.Directory.CreateDirIfNotExist(dirDestine);

                foreach (string tempFile in Directory.GetFilesOfDir(dirSouce))
                {
                    GridProteinFolding.Middle.Helpers.IOHelpers.File.Copy(tempFile, dirDestine + @"\\" + Path.GetFileName(tempFile), true);
                }

                GridProteinFolding.Middle.Helpers.IOHelpers.Directory.DeleteFileAndDirIfExists(dirSouce, null);
                GridProteinFolding.Middle.Helpers.IOHelpers.Directory.Delete(dirSouce);

                int posBar = dirSouce.LastIndexOf(@"\", StringComparison.Ordinal);
                GridProteinFolding.Middle.Helpers.IOHelpers.Directory.DeleteFileAndDirIfExists(dirSouce.Substring(0, dirSouce.Length - (dirSouce.Length - posBar)), null);
            }
            catch (Exception ex)
            {
                GICO.WriteLine(ex);
                throw;
            }
        }
Exemplo n.º 8
0
        private void Close(Param param)
        {
            GICO.WriteLine("OriginConnect: Closing Origin..");
            if (pOrigin != null)
            {
                pOrigin.Visible = MAINWND_VISIBLE.MAINWND_HIDE;
                pOrigin.Exit();


                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(pOrigin);

                pWorksheet  = null;
                pGraphLayer = null;
                pDataPlot   = null;
                pOrigin     = null;

                //int hWnd = pOrigin.Application.Hwnd;

                //Force KILL
                //uint processID;
                //GetWindowThreadProcessId((IntPtr)hWnd, out processID);
                System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("Origin~1");
                foreach (System.Diagnostics.Process p in procs)
                {
                    //if (p.Id == processID)
                    p.Kill();
                }
            }
        }
Exemplo n.º 9
0
        public static Process GetOneProcessGuiForETL(Guid gui, Services.DistributedService.RequestorInfo requestorInf)
        {
            Process tempProcess = new Process();

            using (GridProteinFoldingEntities ctx = new GridProteinFoldingEntities())
            {
                tempProcess = ctx.Process.Include("DataToProcess").Include("DataToResult").Include("Model").Include("ConfigApp").Include("Output").FirstOrDefault(p => p.guid == gui);

                try
                {
                    if (tempProcess != null)
                    {
                        //TRATATIVA de INTEGRIDADE dos DADOS
                        ParseIntegration(ref tempProcess);
                        GICO.WriteLine(gui, String.Format("{0} {1} @ {2}({3})", DateTime.Now, "Processing ETL", requestorInf.macAddr, requestorInf.machineName));
                    }
                    return(tempProcess);
                }
                catch (Exception ex)
                {
                    GICO.WriteLine(String.Format("{0} {1} ({2} {3})", tempProcess.guid.ToString(), DateTime.Now, "Exception:", ex.Message.ToString()));

                    BasicEnums.State newstatus = BasicEnums.State.ETLError;
                    SetOneProcess(tempProcess.guid, newstatus, requestorInf);

                    return(null);
                }
            }
        }
        private void Integrator(Param param, Helpers.ConfigurationHelpers.Output output)
        {
            //deleta arquivo, se existir
            if (File.Exists(dirServerExcel + @"\" + excelFileName))
            {
                File.Delete(dirServerExcel + @"\" + excelFileName);
            }

            GridProteinFolding.Middle.Helpers.IOHelpers.Directory.CreateDirIfNotExist(dirServerExcel);

            XLWorkbook workbook = new XLWorkbook();


            if (output.distribution)
            {
                GICO.WriteLine(String.Format("  Excel: SheetDistribution..."));
                SheetDistribution(ref workbook);
                Save(ref workbook);
            }

            if (param.output.evolution)
            {
                GICO.WriteLine(String.Format("  Excel: SheetEvolutionRadiusGyration..."));
                SheetEvolutionRadiusGyration(ref workbook);
                GICO.WriteLine(String.Format("  Excel: SheetEvolutionValueMediumOfEnergy..."));
                SheetEvolutionValueMediumOfEnergy(ref workbook);
                Save(ref workbook);
            }

            if (param.output.configuration)
            {
                GICO.WriteLine(String.Format("  Excel: SheetConfiguration..."));
                SheetConfiguration(ref workbook);
                Save(ref workbook);
            }

            if (output.histogram)
            {
                GICO.WriteLine(String.Format("  Excel: SheetsHistogram..."));
                SheetsHistogram(ref workbook);
                Save(ref workbook);
            }

            if (output.trajectory)
            {
                GICO.WriteLine(String.Format("  Excel: SheetTrajectory..."));
                SheetTrajectory(ref workbook);
                Save(ref workbook);
            }

            if (output.debug)
            {
                GICO.WriteLine(String.Format("  Excel: SheetDebug..."));
                SheetDebug(ref workbook);
                Save(ref workbook);
            }

            workbook = null;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Drop a table
        /// </summary>
        private static bool DropTable()
        {
            try
            {
                string        sql     = "DROP TABLE Process";
                SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                command.ExecuteNonQuery();

                return(true);
            }
            catch (SQLiteException ex)
            {
                new CustomLog().Exception(ex);
                GICO.WriteLine("TABLE Process not exist!");
                return(false);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Creates a table
        /// </summary>
        private static bool CreateTable()
        {
            try
            {
                string        sql     = "CREATE TABLE Process (guid VARCHAR(255) PRIMARY KEY, status INT, date VARCHAR(19) )";
                SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
                command.ExecuteNonQuery();

                return(true);
            }
            catch (SQLiteException ex)
            {
                new CustomLog().Exception(ex);
                GICO.WriteLine("TABLE Process exist!");
                return(false);
            }
        }
Exemplo n.º 13
0
        private static bool SendMail(GridProteinFoldingEntities ctx, Guid guid, string message, aspnet_Users user)
        {
            //Sent e-mail
            Middle.Helpers.NetworkHelpers.SmtpClient smtpClient = new Middle.Helpers.NetworkHelpers.SmtpClient();
            Process process = ctx.Process.FirstOrDefault(p => p.guid == guid);


            if (!(process.emailNotification == Convert.ToByte(BasicEnums.EmailNotification.Enviar)))
            {
                try
                {
                    System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(user.aspnet_Membership.LoweredEmail, user.UserName);
                    string subject = "eFolding - Simulation";
                    string body    = "Simulation " + process.guid.ToString() + message;
                    body += "Direct access: efolding.fcfrp.usp.br/Pages/GCPS.aspx?guid= " + process.guid.ToString();

                    if (smtpClient.Send(to, subject, body))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (SmtpException ex)
                {
                    new GridProteinFolding.Middle.Helpers.LoggingHelpers.Log().SmtpException(ex, Types.ErrorLevel.Warning);
                    return(false);
                }
                catch (Exception ex)
                {
                    GICO.WriteLine(ex);
                    throw;
                }
                finally
                {
                    smtpClient = null;
                }
            }
            else
            {
                return(true);
            }
        }
Exemplo n.º 14
0
        public void Decrypt()
        {
            try
            {
                dirDebug      = DirBaseServer + this.param.dataToProcess.Guid + @"\" + Resource.DirDebug + @"\" + Resource.DirDebug;
                dirTrajectory = DirBaseServer + this.param.dataToProcess.Guid + @"\" + Resource.DirResult + @"\" + Resource.SubDirTrajectory;
                string destination = DirBaseWeb + this.param.dataToProcess.Guid + @"\" + Resource.DirDebug + @"\";

                string[] diretories = { dirDebug, dirTrajectory };

                DecrypAllFiles(diretories, destination);
            }
            catch (Exception ex)
            {
                GICO.WriteLine(ex);
                throw;
            }
        }
Exemplo n.º 15
0
        private void Start(bool showDialogBox)
        {
            try
            {
                pOrigin = new ApplicationSI();
            }
            catch (System.Exception ex)
            {
                String strMsg = ResourceException.Origin_FailedPlotting;
                GICO.WriteLine(strMsg);
                GICO.WriteLine(ex);
                return;
            }

            //Show o DIALOG BOX do ORIGIN
            if (showDialogBox)
            {
                pOrigin.Visible = MAINWND_VISIBLE.MAINWND_SHOW;
            }
        }
Exemplo n.º 16
0
        private void Save(Param param)
        {
            GICO.WriteLine("OriginConnect: Salving fileReader..");
            if (pOrigin != null)
            {
                if (!Directory.Exists(dirOrigin))
                {
                    Directory.CreateDirectory(dirOrigin);
                }

                string pathFile = dirOrigin + @"\" + param.dataToProcess.Guid.ToString() + Resource.OriginProjectFile;

                if (File.Exists(pathFile))
                {
                    File.Delete(pathFile);
                }

                pOrigin.Save(pathFile);
            }
        }
        public void Execute(Helpers.ConfigurationHelpers.Output output)
        {
            //Config.CurrentGuid = param.dataToProcess.Guid;

            //try
            //{
            this.maxInterations = param.dataToProcess.maxInterations; //numero maximo de tentativas
            this.sites          = param.dataToProcess.totalSitio;     //número total de sítios do monomero

            this.dirServerExcel     = DirBaseServer + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirResult + @"\" + Resource.SubDirExcel;
            this.dirWebExcel        = DirBaseWeb + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirResult;// + @"\" + Resource.SubDirExcel;
            this.dirServerNeighbors = DirBaseServer + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirDebug + @"\" + Resource.SubDirNeighbors;
            this.dirServerHistogram = DirBaseServer + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirDebug + @"\" + Resource.SubDirHistogram;
            this.dirServerDebug     = DirBaseServer + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirDebug + @"\" + Resource.SubDirDebug;
            this.dirWebDebug        = DirBaseWeb + param.dataToProcess.Guid.ToString() + @"\" + Resource.DirDebug + @"\" + Resource.SubDirDebug;

            excelFileName  = param.dataToProcess.Guid.ToString() + ".xlsx";
            valueDivResult = param.dataToResults.valueDivResult;

            this.MCSteps = maxInterations * sites * 5;
            this.delta   = MCSteps / valueDivResult;

            //IF EXIST, EXECUTE INTEGRATOR
            if (Directory.Exists(dirServerDebug))
            {
                GICO.WriteLine(String.Format("  Excel: Integrator..."));
                Integrator(param, output);

                GICO.WriteLine(String.Format("  Excel: CopyFile..."));
                CopyFile(param);
            }
            else
            {
                GICO.WriteLine(AppConfigClient.CurrentGuid, String.Format("Directory not found: {0}  Integrator of Excel not executed...", dirServerDebug));
            }
            //}
            //catch (Exception ex)
            //{
            //    GICO.WriteLine(ex);
            //}
        }
Exemplo n.º 18
0
        private void SentData(Param param)
        {
            GICO.WriteLine("OriginConnect: Salving points of Seed {0}..", param.dataToProcess.Guid.ToString());
            //Protein.LoadSeedCoord(fileReader, true);
            using (GridProteinFoldingEntities ctx = new GridProteinFoldingEntities())
            {
                List <Entities.Internal.Configuration> configuration = ctx.Configuration.Where(c => c.process_guid == param.dataToProcess.Guid && c.mcStep == 0).ToList();

                foreach (Entities.Internal.Configuration coordinate in configuration)
                {
                    int nFactor = pWorksheet.Rows;
                    pointX = coordinate.x;
                    pointY = coordinate.y;
                    pointZ = coordinate.z;

                    double[,] Data = new double[1, 3];
                    Data[0, 0]     = pointX;
                    Data[0, 1]     = pointY;
                    Data[0, 2]     = pointZ;
                    pWorksheet.SetData(Data, -1, 0); //append
                }
            }
        }
        public static void PrintPercentCompleted(int actual, int max)
        {
            long maxInterations = max;

            if (actual != 0)
            {
                double percent = actual;
                percent = ((percent * 100) / maxInterations);

                int value = Convert.ToInt32(percent.ToString("00.##").Substring(0, 2));

                //switch (value)
                //{
                //    case 10:
                //    case 20:
                //    case 30:
                //    case 40:
                //    case 50:
                //    case 60:
                //    case 70:
                //    case 80:
                //    case 90:
                //    case 100:
                if (lastNumber < value)
                {
                    lastNumber = value;
                    GICO.WriteLine(lastNumber + "%.. ");
                }
                //        break;
                //}
            }
            else
            {
                GICO.WriteLine("0%.. ");
            }
        }
Exemplo n.º 20
0
        public static List <Structs.BasicStructs.Point> CreateTarget(List <TargetsCoordinates> lstTargetsCoordinates)
        {
            //Efetua a leitura do modelo da "Sequência X"
            string strucFull = string.Empty; // "1  2  3  6  5  4  7  8  9 18 17 16 13 10 11 12 15 14 23 20 21 24 27 26 25 22 19";

            //string[] struc = strucFull.Split(' '); //Quebra a linha em posições na array atravéz do espaço
            //struc = struc.Where(x => !string.IsNullOrEmpty(x)).ToArray(); //Remove os espaços em branco, deixa estrutura somente com posições válidas

            string[] struc = new string[lstTargetsCoordinates.Count];
            int      j     = 0;

            foreach (TargetsCoordinates item in lstTargetsCoordinates)
            {
                struc[j++] = item.value.ToString();
            }


            //Lê o arquivo sample de geração das coordenadas
            string line;
            List <Structs.BasicStructs.Point> coord = new List <Structs.BasicStructs.Point>();

            ExtendedStreamReader file = new ExtendedStreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\coord" + Directory.FileExtension, Config.CurrentGuid, false);

            while ((line = file.ReadLine()) != null)
            {
                string[] temp = line.Split(' ');
                temp = temp.Where(x => !string.IsNullOrEmpty(x)).ToArray();
                coord.Add(new Structs.BasicStructs.Point()
                {
                    x = Convert.ToInt16(temp[0]), y = Convert.ToInt16(temp[1]), z = Convert.ToInt16(temp[2])
                });
            }
            file.Close();


            //Incrimento inicial das posições do cubo x,y,z
            List <Point> points = new List <Point>(); //Uma lista encadeada do tipo PointCube

            for (int i = 0; i < coord.Count(); i++)
            {
                int   pos   = Convert.ToInt16(struc[i]) - 1;
                Point point = new Point()
                {
                    x = coord[pos].x, y = coord[pos].y, z = coord[pos].z
                };
                points.Add(point);

                GICO.WriteLine(Config.CurrentGuid, String.Format("{0},{1},{2}", points[i].x, points[i].y, points[i].z));
            }

            //Cria um cadeia de simulação
            GCPS.chain = new Structs.BasicStructs.Chain();
            foreach (Point item in points)
            {
                GCPS.chain.r.Add(new Structs.BasicStructs.Point()
                {
                    x             = item.x,
                    y             = item.y,
                    z             = item.z,
                    deadEnd       = 0,
                    deadEndPoints = string.Empty,
                    neighbors     = new Structs.BasicStructs.Neighbor[6],
                    e             = new List <TypeE>()
                });
            }

            return(GCPS.chain.r);
        }
Exemplo n.º 21
0
 public void Execute()
 {
     GICO.WriteLine("OriginConnect: Starting..");
     Init(true, param);
 }
Exemplo n.º 22
0
        public void LoadConfigurationOutPutForOrigin()
        {
            GICO.WriteLine(String.Format("  Output: LoadConfigurationOutPutToOrigin: Delete..."));
            ////Delete IF EXIST
            //using (GridProteinFoldingEntities ctx = new GridProteinFoldingEntities())
            //{
            //    ctx.Database.ExecuteSqlCommand("DELETE FROM OUTPUT WHERE guid= {0}", param.dataToProcess.Guid);
            //}

            string readerFile = dirBaseWeb.FullName() + this.param.dataToProcess.Guid + @"\Result\Configuration.dat";

            using (ExtendedStreamReader souceFile = new ExtendedStreamReader(readerFile,
                                                                             this.param.dataToProcess.Guid, false))
            {
                string line;
                int    i = 0;


                GICO.WriteLine(String.Format("  Output: LoadConfigurationOutPutToOrigin: Insert..."));
                while ((line = souceFile.ReadLine()) != null)
                {
                    if (String.IsNullOrEmpty(line))
                    {
                        break;
                    }

                    //pulas cabeçalho e o número de discartes
                    if (i == 0)
                    {
                        line = souceFile.ReadLine();
                    }

                    string[] data   = line.Split('\t').ToArray();
                    Int32    mcStep = 0;
                    int      order  = 0;
                    int      count  = 0;

                    using (TransactionScope scope = new TransactionScope())
                    {
                        GridProteinFoldingEntities ctx = null;

                        try
                        {
                            ctx = new GridProteinFoldingEntities();
                            Entities.Internal.Configuration configuration = null;

                            for (int j = 0; j < data.Length; j++)
                            {
                                if (j == 0)
                                {
                                    mcStep = Convert.ToInt32(data[j]); j++;
                                }

                                configuration = new Entities.Internal.Configuration();

                                configuration.process_guid = this.param.dataToProcess.Guid;
                                configuration.mcStep       = mcStep;
                                configuration.order        = order;
                                configuration.x            = Convert.ToInt32(data[j]); j++;
                                configuration.y            = Convert.ToInt32(data[j]); j++;
                                configuration.z            = Convert.ToInt32(data[j]);

                                order++;

                                ++count;
                                ctx = AddToContext(ctx, configuration, count, 100, true);
                                //ctx.Configuration.Add(configuration);
                            }

                            if (configuration != null)
                            {
                                ctx.SaveChanges();
                                configuration = null;
                            }
                        }
                        finally
                        {
                            if (ctx != null)
                            {
                                ctx.Dispose();
                            }
                        }
                        scope.Complete();
                    }
                    i++;
                }


                souceFile.Close();
                //souceFile = null;
                souceFile.Dispose();
            }
        }
Exemplo n.º 23
0
        public bool Process(ref Param param)
        {
            GridProteinFolding.Middle.Helpers.LoggingHelpers.Log.InformationLog("Process begin...");
            #region Set configuracao
            AppConfigClient.Param = param;
            Middle.Helpers.RandomHelpers.Randomic.magicNumber = param.configApp.MagicNumber;
            Middle.Helpers.RandomHelpers.Randomic.equal_one   = param.configApp.EqualOne;
            #endregion

            GICO.WriteLine(AppConfigClient.CurrentGuid, "Connected...");

            //PREPARA os DIRETORIOS

            //ConsoleOut.WriteLine(AppConfigClient.CurrentGuid, "Working in temp folder(PreperFolderForLocationsDebug)...");
            new GridProteinFolding.Core.eFolding.IO.Directory().PreperFolderForLocationsDebug();

            //posição do último monomero válido
            int lastValed = int.MinValue;
            GCPS.initialIsem = AppConfigClient.Param.dataToProcess.isem;

            //Inicializa o Monomero da simulação
            GCPS.chain = new Structs.BasicStructs.Chain();

            GCPS.modelType = AppConfigClient.Param.dataToProcess.modelType;
            //GCPS.model = new List<Structs.BasicStructs.Model>();

            //if (GCPS.model.Count > 0)
            //{
            //    foreach (String tempSplit in param.dataToProcess.model.Split(';'))
            //    {
            //        Structs.BasicStructs.Model tempModel = new Structs.BasicStructs.Model();
            //        string[] tempSubSplit = tempSplit.Split(',');
            //        tempModel.Monomero = Convert.ToByte(tempSubSplit[0]);
            //        tempModel.Value = float.Parse(tempSubSplit[1]);
            //        GCPS.model.Add(tempModel);
            //    }
            //}

            //Seleciona o tipo de formação de estrutura a ser utilizada
            //Geração Randomica?
            //Geração por arquivo?
            //Geração apartir de um modelo?
            double cont = 0;
            SelectTypeOfStruct(ref lastValed, ref cont, ref cadeiaIdeal, ref cadeiaReal, ref cadeiaSoft, ref cadeiaError);

            GICO.WriteLine(AppConfigClient.CurrentGuid, String.Format("Total Monomeros: {0}", AppConfigClient.Param.dataToProcess.maxInterations));
            GICO.WriteLine(AppConfigClient.CurrentGuid, String.Format("Cadeia ideal   : {0}", cadeiaIdeal));
            GICO.WriteLine(AppConfigClient.CurrentGuid, String.Format("Cadeia real    : {0}", cadeiaReal));
            GICO.WriteLine(AppConfigClient.CurrentGuid, String.Format("Cadeia soft    : {0}", cadeiaSoft + "(" + (AppConfigClient.Param.dataToProcess.maxInterations - cadeiaIdeal - cadeiaReal) + ")"));
            GICO.WriteLine(AppConfigClient.CurrentGuid, String.Format("Cadeia error   : {0}", cadeiaError));

            GICO.WriteLine(AppConfigClient.CurrentGuid, "Salving results...");
            GICOF.CalcOfFrequency.SaveData(BasicEnums.ChainTypes.Ideal, Structs.Queue <QueueType> .valuesCadeiaIdeal);
            GICOF.CalcOfFrequency.SaveData(BasicEnums.ChainTypes.Real, Structs.Queue <QueueType> .valuesCadeiaReal);
            GICOF.CalcOfFrequency.SaveData(BasicEnums.ChainTypes.Soft, Structs.Queue <QueueType> .valuesCadeiaSoft);

            ConsoleOut.WriteLine(AppConfigClient.CurrentGuid, "Creating histogram...");
            GICOF.CalcOfFrequency.WriteFrequencyPeerInterval(BasicEnums.HistTypes.RadiuosOfGyration, BasicEnums.ChainTypes.Ideal);
            GICOF.CalcOfFrequency.WriteFrequencyPeerInterval(BasicEnums.HistTypes.EndToEndDistance, BasicEnums.ChainTypes.Ideal);

            GICOF.CalcOfFrequency.WriteFrequencyPeerInterval(BasicEnums.HistTypes.RadiuosOfGyration, BasicEnums.ChainTypes.Real);
            GICOF.CalcOfFrequency.WriteFrequencyPeerInterval(BasicEnums.HistTypes.EndToEndDistance, BasicEnums.ChainTypes.Real);

            GICOF.CalcOfFrequency.WriteFrequencyPeerInterval(BasicEnums.HistTypes.RadiuosOfGyration, BasicEnums.ChainTypes.Soft);
            GICOF.CalcOfFrequency.WriteFrequencyPeerInterval(BasicEnums.HistTypes.EndToEndDistance, BasicEnums.ChainTypes.Soft);


            ConsoleOut.WriteLine(AppConfigClient.CurrentGuid, "MCSteps finished.");

            GC.GetTotalMemory(false);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            GridProteinFolding.Middle.Helpers.LoggingHelpers.Log.InformationLog("Process completed...");
            return(true);
        }
Exemplo n.º 24
0
        private bool Run(ServiceParamWcf paramWCF)
        {
            GridProteinFolding.Core.eFolding.Main objProcess = new GridProteinFolding.Core.eFolding.Main();

            //Executa REQUISICAO
            GridProteinFolding.Middle.Helpers.ConfigurationHelpers.Param newParam = new GridProteinFolding.Middle.Helpers.ConfigurationHelpers.Param();
            //Preparar os parametros para execução
            Param temp = paramWCF.param;

            GridProteinFolding.Middle.Helpers.ConfigurationHelpers.Param.PreperParams(ref temp, ref newParam);

            #region Atualiza Status local
            if (Status(paramWCF.param.dataToProcess.Guid) == (int)BasicEnums.State.Processing)
            {
                Sql.entityProcess = SetStatusProcessandoLocalDBToProcessing(newParam, BasicEnums.State.Processing);
            }
            #endregion

            try
            {
                //if (Status(paramWCF.param.dataToProcess.Guid) == (int)BasicEnums.State.Waiting)
                //{
                //    DisplayMessage(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, BasicEnums.State.Waiting.ToString()));
                //    Sql.entityProcess = SetStatusProcessando(newParam, BasicEnums.State.Processing);
                //}

                if (Status(paramWCF.param.dataToProcess.Guid) == (int)BasicEnums.State.Processing)
                {
                    DisplayMessage(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, BasicEnums.State.Processing.ToString()));

                    Processing(ref objProcess, ref newParam, ref paramWCF);

                    if (returnOfProcess)
                    {
                        UpdateStatus(newParam, BasicEnums.State.Processed);
                    }
                    else
                    {
                        UpdateStatus(newParam, BasicEnums.State.Error);
                        DisplayMessage(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, BasicEnums.State.Error.ToString()));
                    }
                }

                if (Status(paramWCF.param.dataToProcess.Guid) == (int)BasicEnums.State.Processed)
                {
                    DisplayMessage(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, BasicEnums.State.Processed.ToString()));
                    UpdateStatus(newParam, returnOfProcess == true ? BasicEnums.State.Upload : BasicEnums.State.Error);
                    //System.Threading.Thread.Sleep(1000);
                }

                if (Status(paramWCF.param.dataToProcess.Guid) == (int)BasicEnums.State.Upload)
                {
                    DisplayMessage(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, (BasicEnums.State.Upload.ToString())));
                    returnOfProcess = true;
                    //Upload dos resultados
                    Upload(paramWCF);
                    //Atualiza Status
                    UpdateStatus(newParam, returnOfProcess == true ? BasicEnums.State.BULK : BasicEnums.State.Error);
                    //System.Threading.Thread.Sleep(500);
                }

                if (Status(paramWCF.param.dataToProcess.Guid) == (int)BasicEnums.State.ClearTempClient)
                {
                    if (AppConfigClient.Param == null)
                    {
                        AppConfigClient.Param = newParam;
                    }
                    //Limpar folder cliente utilizado no processamento
                    new GridProteinFolding.Core.eFolding.IO.Directory().ClearProcessClientFolder();

                    //Atualiza Status
                    UpdateStatus(newParam, returnOfProcess == true ? BasicEnums.State.ClearTempServer : BasicEnums.State.Error);
                    DisplayMessage(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, returnOfProcess == true ? BasicEnums.State.ClearTempServer.ToString() : BasicEnums.State.Error.ToString()));
                }

                GICO.WriteLine(ExtendedString.Format("{0}> {1}...", paramWCF.param.dataToProcess.Guid, "Process of simulation finished!"));


                return(returnOfProcess);
            }
            catch (Exception ex)
            {
                new CustomLog().Exception(ex);

                UpdateStatus(newParam, BasicEnums.State.Error);

                return(false);
            }
            //finally
            //{
            //    GridProteinFolding.Data.SQLite.SQLite.CloseDatabase();
            //}
        }
Exemplo n.º 25
0
        private bool CallServer(GridProteinFolding.Data.XMLData.Entity.Process process)
        {
            bool retRun = false;

            try
            {
                ServiceParamWcf paramWCF;

                bool oneProcessPeerGuid = false;
                //Se não existir pendência no cliente
                if (process == null)
                {
                    paramWCF = ProxyServiceClient.GetOneProcess();
                }
                else
                {
                    paramWCF           = ProxyServiceClient.GetOneProcessGui(process.guid);
                    oneProcessPeerGuid = true;

                    //Implementar a mudança de STATUS - qdo ocorrer erro POS processamento = UPLOAD e etc
                    //variavel RET (estara dentro Run) tem q estar setada pra TRUE...senao dara ERRO 99...
                    //Proxy.SetStatus(paramWCF, BasicEnums.State.Upload);
                }

                if (paramWCF != null)
                {
                    ConsoleColor oldColour = Console.ForegroundColor;
                    GICO.ForegroundColor(ConsoleColor.Yellow);
                    DisplayMessage(string.Empty);
                    DisplayMessage(ExtendedString.Format("{0}> {1}", paramWCF.param.dataToProcess.Guid, Resource.Started));

                    GICO.ForegroundColor(oldColour);
                    if (oneProcessPeerGuid)
                    {
                        DisplayMessage(ExtendedString.Format("{0}> {1}", paramWCF.param.dataToProcess.Guid, Resource.GetOneProcess));
                    }
                    else
                    {
                        DisplayMessage(ExtendedString.Format("{0}> {1}", paramWCF.param.dataToProcess.Guid, Resource.GetOneProcessGui));
                    }

                    //Responde que esta sendo PROCESSADO
                    DisplayMessage(ExtendedString.Format("{0}> {1}", paramWCF.param.dataToProcess.Guid, Resource.Running));

                    retRun = Run(paramWCF);

                    DisplayMessage(ExtendedString.Format("{0}> {1}", paramWCF.param.dataToProcess.Guid, Resource.Finished));
                    DisplayMessage(string.Empty);
                }

                return(retRun);
            }
            catch (EndpointNotFoundException ex)
            {
                ConsoleColor oldColour = Console.ForegroundColor;
                GICO.ForegroundColor(ConsoleColor.Red);
                DisplayMessage(ex.Message);
                GICO.ForegroundColor(oldColour);

                new CustomLog().EndpointNotFoundException(ex);
            }

            return(false);
        }
Exemplo n.º 26
0
        public void Distribution()
        {
            try
            {
                string readerFile = dirBaseWeb.FullName() + this.param.dataToProcess.Guid + @"\Result\Debug.dat";
                string writerFile = dirBaseWeb.FullName() + this.param.dataToProcess.Guid + @"\Result\Distribution.dat";

                Guid guid   = param.dataToProcess.Guid;
                int  isem   = param.dataToProcess.isem;
                int  sitios = param.dataToProcess.totalSitio;

                //Data
                string line;
                List <ColsForDepedentModel> md = new List <ColsForDepedentModel>();

                using (ExtendedStreamReader souceFile = new ExtendedStreamReader(readerFile,
                                                                                 this.param.dataToProcess.Guid, false))
                {
                    ExtendedStreamWriter destinationFile = new ExtendedStreamWriter(writerFile, false,
                                                                                    this.param.dataToProcess.Guid, false);

                    string[] cols = null;
                    int      i    = 0;

                    while ((line = souceFile.ReadLine()) != null)
                    {
                        if (String.IsNullOrEmpty(line))
                        {
                            break;
                        }

                        //pulas cabeçalho &  faz o discarte o número de discartes
                        if (i == 0)
                        {
                            for (int k = 0; k < this.valueDiscard; k++)
                            {
                                line = souceFile.ReadLine();
                            }
                        }
                        else
                        {
                            cols = line.Split('\t').ToArray();
                            Int32  _mcSteps = Convert.ToInt32(cols[0]);
                            double _rg      = Convert.ToDouble(cols[3]);
                            double _e       = Convert.ToDouble(cols[2]);
                            double _U       = Convert.ToDouble(cols[8]);

                            md.Add(new ColsForDepedentModel()
                            {
                                mcSteps = _mcSteps, rg = _rg, e = _e, U = _U
                            });

                            //pula o Delta
                            for (int k = 0; k < this.delta; k++)
                            {
                                line = souceFile.ReadLine();
                            }
                        }

                        i++;
                    }

                    souceFile.Close();
                    //souceFile = null;



                    //Write result file
                    destinationFile.WriteLine("simulation id: {0}", guid.ToString());
                    destinationFile.WriteLine("isem: {0}", isem);
                    destinationFile.WriteLine("sitios: {0}", sitios);
                    destinationFile.WriteLine("model: {0}", TranslateModel(param.dataToProcess.modelType));
                    destinationFile.WriteLine("mcStep: {0}", this.mcSteps);
                    destinationFile.WriteLine("temperature: {0}", param.dataToProcess.temperature);
                    destinationFile.WriteLine("valueDiscard: {0}", this.valueDiscard);
                    destinationFile.WriteLine("delta: {0}", this.delta);

                    destinationFile.WriteLine("idx\t mcSteps\t rg2\t rg2(accumulated)\t <rg2>\t e\t e(accumulated)\t <e>\t U\t U(accumulated)\t <U>");

                    double aRG2, eRG2, previousRG2, actualRG2;
                    aRG2 = eRG2 = previousRG2 = actualRG2 = 0;
                    double aE, eE, previousE, actualE;
                    aE = eE = previousE = actualE = 0;
                    double aU, eU, previousU, actualU;
                    aU = eU = previousU = actualU = 0;

                    Int64 idx = 0;

                    for (int z = 0; z < md.Count(); z++)
                    {
                        idx = (z + 1);

                        //Acumulado
                        aRG2 += md[z].rg;
                        aE   += md[z].e;
                        aU   += md[z].U;

                        //Evolução do RAIO DE GIRAÇÃO
                        actualRG2   = md[z].rg;
                        eRG2        = aRG2 / idx;
                        previousRG2 = eRG2;

                        //Evolução do E
                        actualE   = md[z].e;
                        eE        = aE / idx;
                        previousE = eE;

                        //Evolução do U
                        actualU   = md[z].U;
                        eU        = aU / idx;
                        previousE = eU;


                        destinationFile.WriteLine(z + "\t" + md[z].mcSteps + "\t" + actualRG2 + "\t" + aRG2 + "\t" + eRG2 + "\t" + actualE + "\t" + aE + "\t" + eE + "\t" + actualU + "\t" + aU + "\t" + eU);
                    }

                    destinationFile.Flush();
                    destinationFile.Close();
                    souceFile.Dispose();
                }
            }
            catch (Exception ex)
            {
                GICO.WriteLine(ex);
                throw;
            }
        }
Exemplo n.º 27
0
        private static void Condicional(Guid guid, GridProteinFoldingEntities ctx, Process temp, ref BasicEnums.State state, ref RequestorInfo requestorInfo)
        {
            aspnet_Users user = new GridProteinFolding_MemberShipEntities().aspnet_Users.FirstOrDefault(u => u.UserId == temp.userId);

            if (state == BasicEnums.State.Processing)
            {
                GICO.WriteLine(guid, String.Format("{0} {1} @ {2}({3})", DateTime.Now, "Processing", temp.macAddr, temp.machineName));

                string message = " was started!";

                if (temp.emailNotification == Convert.ToByte(BasicEnums.EmailNotification.Enviar))
                {
                    SendMail(ctx, guid, message, user);
                }

                Expurg(guid, ctx);
            }
            if (state == BasicEnums.State.BULK)
            {
                #region BULK
                GICO.WriteLine(guid, String.Format("{0} {1} @ {2}({3})", DateTime.Now, "BULK", temp.macAddr, temp.machineName));
                //ExtendedDirectoryInfo dirBaseServer = new ExtendedDirectoryInfo(ConfigurationManager.AppSettings["dirBaseServer"].ToString());

                //object[] parameters = new object[2];
                //parameters[0] = dirBaseServer + @"\" + guid + @"\Seed";
                //parameters[1] = guid.ToString();

                //ctx.ExecuteStoreCommand("EXEC dbo.BunkFiles {0},{1}", parameters);

                state          = BasicEnums.State.ClearTempClient;
                temp.status_id = Convert.ToByte(state);
                ctx.SaveChanges();
                #endregion

                #region ClearTempServer
                GICO.WriteLine(guid, String.Format("{0} {1} @ {2}({3})", DateTime.Now, "ClearTempServer", temp.macAddr, temp.machineName));
                DeleteFileServer_temp(guid);

                state          = BasicEnums.State.Finalized;
                temp.status_id = Convert.ToByte(state);
                ctx.SaveChanges();
                #endregion
            }

            //if (state == Enums.BasicEnums.State.Excel)
            //{

            //    Applications objApplications = new Applications();

            //    GICO.Write("Excel..");
            //    objApplications.Excel(param);

            //    GICO.WriteLine("{0}:{1}", param.dataToProcess.Guid.ToString(), "DONE!");
            //    objApplications = null;

            //    state = Enums.BasicEnums.State.Origin;
            //    temp.status_id = Convert.ToByte(state);
            //    ctx.SaveChanges();
            //}

            //if (state == Enums.BasicEnums.State.Origin)
            //{
            //    ProcessData(param.dataToProcess.Guid);

            //    Applications objApplications = new Applications();

            //    GICO.Write("Origin..");
            //    objApplications.Origin(param.dataToProcess.Guid);

            //    GICO.WriteLine("{0}:{1}", param.dataToProcess.Guid.ToString(), "DONE!");
            //    objApplications = null;

            //    state = Enums.BasicEnums.State.ClearTempClient;
            //    temp.status_id = Convert.ToByte(state);
            //    ctx.SaveChanges();
            //}

            //if (state == BasicEnums.State.ClearTempServer)
            //{
            //    GICO.WriteLine(guid, String.Format("{0} {1}:", DateTime.Now, "ClearTempServer.."));
            //    DeleteFileServer_temp(guid);

            //    state = BasicEnums.State.Finalized;
            //    temp.status_id = Convert.ToByte(state);
            //    ctx.SaveChanges();
            //}

            //if (state == Enums.BasicEnums.State.Decrypt)
            //{
            //    Applications objApplications = new Applications();
            //    GICO.Write("Decrypt..");
            //    objApplications.Decrypt(param);
            //    GICO.WriteLine("{0}:{1}", param.dataToProcess.Guid.ToString(), "DONE!");
            //    objApplications = null;

            //    state = Enums.BasicEnums.State.Web;
            //    temp.status_id = Convert.ToByte(state);
            //    ctx.SaveChanges();
            //}

            //if (state == Enums.BasicEnums.State.Web)
            //{

            //    Applications objApplications = new Applications();
            //    GICO.Write("Web..");
            //    objApplications.Web(param);
            //    GICO.WriteLine("{0}:{1}", param.dataToProcess.Guid.ToString(), "DONE!");
            //    objApplications = null;

            //    state = Enums.BasicEnums.State.Finalized;
            //    temp.status_id = Convert.ToByte(state);
            //    ctx.SaveChanges();
            //}

            if (state == BasicEnums.State.Finalized)
            {
                GICO.WriteLine(guid, String.Format("{0} {1} @ {2}({3})", DateTime.Now, "Finalized", temp.macAddr, temp.machineName));

                if (temp.emailNotification == Convert.ToByte(BasicEnums.EmailNotification.Enviar))
                {
                    string message = "was completed!";
                    SendMail(ctx, guid, message, user);
                }
            }
        }