Example #1
0
        private PlyProperty ReadProperty()
        {
            var tokens = CurrentLine.Split(' ');

            if (tokens.Length != 3 && tokens.Length != 5)
            {
                throw new Exception(string.Format("Invalid number of tokens in property line: \"{0}\".", CurrentLine));
            }

            if (tokens[0] != "property")
            {
                throw new Exception(string.Format("Invalid property line: \"{0}\".", CurrentLine));
            }

            var property = new PlyProperty {
                Name   = tokens.Last(),
                IsList = tokens[1] == "list",
            };

            if (property.IsList)
            {
                property.ListCountTypeName = tokens[2];
                property.TypeName          = tokens[3];
                property.Name = tokens[4];
            }
            else
            {
                property.TypeName = tokens[1];
                property.Name     = tokens[2];
            }

            return(property);
        }
        public void AddTextSpan(EditableRun textRun)
        {
            if (CurrentLine.IsBlankLine)
            {
                CurrentLine.AddLast(textRun);
                SetCurrentTextRun(textRun);
                CurrentLine.TextLineReCalculateActualLineSize();
                CurrentLine.RefreshInlineArrange();

                SetCurrentCharIndex(CharIndex + textRun.CharacterCount);
            }
            else
            {
                if (CurrentTextRun != null)
                {
                    VisualPointInfo newPointInfo = CurrentLine.Split(GetCurrentPointInfo());
                    if (newPointInfo.IsOnTheBeginOfLine)
                    {
                        CurrentLine.AddBefore((EditableRun)newPointInfo.TextRun, textRun);
                    }
                    else
                    {
                        CurrentLine.AddAfter((EditableRun)newPointInfo.TextRun, textRun);
                    }
                    CurrentLine.TextLineReCalculateActualLineSize();
                    CurrentLine.RefreshInlineArrange();
                    EnsureCurrentTextRun(CharIndex + textRun.CharacterCount);
                }
                else
                {
                    throw new NotSupportedException();
                }
            }
        }
Example #3
0
        private PlyElement ReadElement(PlyElementType elementType)
        {
            var propertyValues = new object[elementType.Properties.Count];

            var tokens = new Queue <string>(CurrentLine.Split(' '));

            foreach (var property in elementType.Properties.Values.OrderBy(p => p.Index))
            {
                if (property.IsList)
                {
                    var listElementCount = int.Parse(tokens.Dequeue());
                    var list             = new object[listElementCount];

                    for (var i = 0; i < list.Length; i++)
                    {
                        list[i] = ParseValue(property.TypeName, tokens.Dequeue());
                    }

                    propertyValues[property.Index] = list;
                }
                else
                {
                    propertyValues[property.Index] = ParseValue(property.TypeName, tokens.Dequeue());
                }
            }

            NextLine();
            return(new PlyElement(elementType, propertyValues));
        }
        public void GetRecordsFromDataFile(string fileName)
        {
            using (StreamReader DataFile = new StreamReader(fileName))
            {
                string CurrentLine;
                Console.WriteLine("File Read: {0}", fileName);

                while (!DataFile.EndOfStream)
                {
                    CurrentLine = DataFile.ReadLine();
                    List <string> clientRecordFields  = new List <string>(CurrentLine.Split(','));
                    ClientRecord  currentClientRecord = new ClientRecord(clientRecordFields[0],
                                                                         clientRecordFields[1],
                                                                         clientRecordFields[2],
                                                                         clientRecordFields[3],
                                                                         clientRecordFields[4]);

                    if (!IsClientRecordValid(currentClientRecord))
                    {
                        Console.WriteLine("A record in the file failed validation. Processing has stopped.");
                        break;
                    }

                    string status = currentClientRecord.GetRecordAcceptedOrRejected();

                    Console.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}",
                                      status,
                                      currentClientRecord.GetFirstName(),
                                      currentClientRecord.GetLastName(),
                                      currentClientRecord.GetDOB(),
                                      currentClientRecord.GetPlanType(),
                                      currentClientRecord.GetEffectiveDate());
                }
            }
        }
Example #5
0
        public SelectionRangeInfo SplitSelectedText(VisualSelectionRange selectionRange)
        {
            SelectionRangeInfo newPoints = CurrentLine.Split(selectionRange);

            EnsureCurrentTextRun();
            return(newPoints);
        }
Example #6
0
        public static void readFromFile(ConfigStore Store)
        {
            string FileName = SERVER_CONFIG_FILENAME;

            Dictionary <string, string> ConfigStore = new Dictionary <string, string>();

            //Read the settings file into a dictionary before shoving the values in the setting store.
            try
            {
                if (!File.Exists(FileName))
                {
                    return;
                }
                using (StreamReader configReader = new StreamReader(FileName))
                {
                    string   CurrentLine;
                    string[] LineParts;

                    while (configReader.EndOfStream == false)
                    {
                        CurrentLine = configReader.ReadLine();

                        if (CurrentLine.StartsWith("#") || String.IsNullOrEmpty(CurrentLine))
                        {
                            continue;
                        }

                        LineParts = CurrentLine.Split(new char[] { '=' }, 2);
                        if (LineParts.Length < 2)
                        {
                            continue;
                        }

                        LineParts[0] = LineParts[0].ToLowerInvariant();

                        ConfigStore.Add(LineParts[0].Trim(), LineParts[1].Trim());
                    }

                    configReader.Close();
                }
            }
            catch (Exception)
            {
            }

            foreach (FieldInfo f in Store.GetType().GetFields())
            {
                string node = f.Name.ToLowerInvariant();

                if (ConfigStore.ContainsKey(node))
                {
                    SetFieldValue(ConfigStore, Store, f, node);
                }
                else
                {
                    //Missing a node, no matter - default value will remain.
                }
            }
        }
Example #7
0
        private void ReadSegment(string Name, Segment Parent, StreamReader Reader)
        {
            Segment Current = new Segment(Name, Parent);

            if (Parent != null)
            {
                Parent.Children.Add(Current);
            }
            Current.Index = this.Segments.Count;
            this.Segments.Add(Current);
            Reader.ReadLine(); // Opening Bracket
            object[] Tags = new object[2];
            string   CurrentLine;

            while (true)
            {
                CurrentLine = Reader.ReadLine();
                if (CurrentLine.Contains("OFFSET"))
                {
                    string[] Parts  = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    Vertex   Offset = new Vertex(Convert.ToSingle(Parts[1]) * 100, Convert.ToSingle(Parts[2]) * 100, Convert.ToSingle(Parts[3]) * 100);
                    if (Parent != null)
                    {
                        Parent.BoneLength = Operations.GetDistance(new Vertex(0, 0, 0), Offset);
                    }
                    Tags[0] = Offset;
                }
                else if (CurrentLine.Contains("CHANNELS"))
                {
                    string[]      Parts    = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    List <string> Channels = new List <string>();
                    for (int i = 2; i < Parts.Length; i++)
                    {
                        Channels.Add(Parts[i]);
                    }
                    Tags[1] = Channels;
                }
                else if (CurrentLine.Contains("JOINT"))
                {
                    string[] Parts = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    ReadSegment(Parts[1], Current, Reader);
                }
                else if (CurrentLine.Contains("End Site"))
                {
                    Reader.ReadLine();
                    CurrentLine = Reader.ReadLine();
                    string[] Parts  = CleanStringArray(CurrentLine.Split(_WhiteSpaces));
                    Vertex   Offset = new Vertex(Convert.ToSingle(Parts[1]), Convert.ToSingle(Parts[2]), Convert.ToSingle(Parts[3]));
                    Current.BoneLength = Operations.GetDistance(new Vertex(0, 0, 0), Offset);
                    Reader.ReadLine();
                }
                else if (CurrentLine.Contains("}"))
                {
                    break;
                }
            }
            Current.Tag = Tags;
        }
Example #8
0
        /// <summary>
        /// Process the current line and extract out values
        /// </summary>
        private void ProcessLine()
        {
            // Comment
            if (CurrentLine.StartsWith(";"))
            {
                KeyValuePair = null;
                RowType      = IniRowType.Comment;
            }

            // Section
            else if (CurrentLine.StartsWith("[") && CurrentLine.EndsWith("]"))
            {
                KeyValuePair = null;
                RowType      = IniRowType.SectionHeader;
                Section      = CurrentLine.TrimStart('[').TrimEnd(']');
            }

            // KeyValuePair
            else if (CurrentLine.Contains("="))
            {
                // Split the line by '=' for key-value pairs
                string[] data = CurrentLine.Split('=');

                // If the value field contains an '=', we need to put them back in
                string key   = data[0].Trim();
                string value = string.Join("=", data.Skip(1)).Trim();

                KeyValuePair = new KeyValuePair <string, string>(key, value);
                RowType      = IniRowType.KeyValue;
            }

            // Empty
            else if (string.IsNullOrEmpty(CurrentLine))
            {
                KeyValuePair = null;
                CurrentLine  = string.Empty;
                RowType      = IniRowType.None;
            }

            // Invalid
            else
            {
                KeyValuePair = null;
                RowType      = IniRowType.Invalid;

                if (ValidateRows)
                {
                    throw new InvalidDataException($"Invalid INI row found, cannot continue: {CurrentLine}");
                }
            }
        }
Example #9
0
        public bool ReadLine()
        {
            CurrentLine = Reader.ReadLine();

            if (CurrentLine == null)
            {
                CurrentLineParts = null;
                return(false);
            }
            else
            {
                CurrentLineParts = CurrentLine.Split(Parameters.Delimiters);
                return(true);
            }
        }
Example #10
0
 public string GetValueFromCommon(string ValueToGet)
 {
     using (StreamReader reader = new StreamReader(new FileStream(CommonFilePath, FileMode.Open)))
     {
         string CurrentLine;
         while ((CurrentLine = reader.ReadLine()) != null)
         {
             if (CurrentLine.Contains(ValueToGet))
             {
                 string[] CurrentLineSplit = CurrentLine.Split('\t');
                 return(CurrentLineSplit[1]);
             }
         }
     }
     return("ERROR");
 }
Example #11
0
        void AddCurrentLineParts(List <string> lines)
        {
            foreach (string line in CurrentLine.Split('\n'))
            {
                string lineCopy = line;
                while (BufferWidth <= lineCopy.Length)
                {
                    lines.Add(lineCopy.Substring(0, BufferWidth));
                    lineCopy = lineCopy.Substring(BufferWidth);
                }

                if (lineCopy != "" || line == "")
                {
                    lines.Add(lineCopy);
                }
            }
        }
Example #12
0
    public static void Load(string FileName)
    {
        try {
            StreamReader FileReader = new StreamReader(FileName, Encoding.Default); // used to read the file in
            string       CurrentLine;                                               //string used to hold the current line of the file
            //varables used for a counter
            int TimeNumber    = 0;
            int EnemiesNumber = 0;
            int DamageNumber  = 0;

            using (FileReader) {
                do
                {
                    CurrentLine = FileReader.ReadLine();                                                              // puts the current line of the file into the currentline string
                    if (CurrentLine != null)
                    {
                        string[] SplitLine = CurrentLine.Split(',');                                                          // splits the currentline up and places the contents in an array
                        if (SplitLine [0] == "Time")                                                                          // checks if the current line in the CSV has the label "Time"
                        {
                            CompletionTimeData.Add(new LeaderboardData(SplitLine [1], float.Parse(SplitLine [2])));           // adds the data to the completionTimeData list
                            TimeNumber++;
                        }

                        if (SplitLine [0] == "Killed")                                                                          // checks if the current line in the CSV has the label "Killed"
                        {
                            EnemiesKilledData.Add(new LeaderboardData(SplitLine [1], float.Parse(SplitLine [2])));              // adds the data to the EnemiesKilledData list
                            EnemiesNumber++;
                        }

                        if (SplitLine [0] == "Damage")                                                                          // checks if the current line in the CSV has the label "Damage"
                        {
                            LeastDamageData.Add(new LeaderboardData(SplitLine [1], float.Parse(SplitLine [2])));                // adds the data to the LeastDamageData list
                            DamageNumber++;
                        }
                    }
                } while (CurrentLine != null);                                       // makes sure its not the end of the file
                FileReader.Close();                                                  // close the StreamReader
            }
        } catch (FileNotFoundException) {
        }
    }
Example #13
0
        private PlyFormat ReadFormat()
        {
            var tokens = CurrentLine.Split(' ');

            if (tokens.Length != 3)
            {
                throw new Exception(
                          "Incorrect number of tokens in format line. Format lines should follow the format: \"format <format_type> <format_version>\".");
            }

            if (tokens[0] != "format")
            {
                throw new Exception("Invalid format line in PLY file. PLY format lines must begin with the word \"format\".");
            }

            PlyFormat format;

            if (tokens[1] == "ascii")
            {
                if (tokens[2] == "1.0")
                {
                    format = PlyFormat.Ascii;
                }
                else
                {
                    throw new Exception(
                              string.Format("Invalid PLY format version: \"{0}\". Expected \"1.0\".", tokens[2]));
                }
            }
            else
            {
                throw new Exception(
                          string.Format("Invalid PLY format: \"{0}\". Right now the PlyMeshLoader can only handle PLY files in the ascii format.", tokens[1]));
            }

            NextHeaderLine();
            return(format);
        }
Example #14
0
        private PlyElementType ReadElementType()
        {
            var tokens = CurrentLine.Split(' ');

            if (tokens.Length != 3)
            {
                throw new Exception(
                          string.Format(
                              "Incorrect number of tokens in element type line: \"{0}\". "
                              + "Element types should be in the format: \"element <element_type> <element_count>\".", CurrentLine));
            }

            if (tokens[0] != "element")
            {
                throw new Exception("Invalid element type line. Element types must start with the word \"element\".");
            }

            int count;

            if (!int.TryParse(tokens[2], out count))
            {
                throw new Exception(
                          string.Format("Invalid element count: \"{0}\"", tokens[2]));
            }

            var elementType = new PlyElementType {
                Name  = tokens[1],
                Count = count
            };

            while (NextHeaderLine().StartsWith("property"))
            {
                elementType.AddProperty(ReadProperty());
            }

            return(elementType);
        }
Example #15
0
        public static void LoadConfig()
        {
            StreamReader Reader = new StreamReader("Config.ini", Encoding.UTF8);

            Reader.ReadLine();
            string CurrentLine;

            while ((CurrentLine = Reader.ReadLine()) != null)
            {
                string[] Fragments = CurrentLine.Split(new char[] { '=' },
                                                       StringSplitOptions.RemoveEmptyEntries);
                switch (Fragments[0])
                {
                case "LanIpAddress":
                    App.LanIpAddress = IPAddress.Parse(Fragments[1]);
                    break;

                case "WanIpAddress":
                    App.WanIpAddress = IPAddress.Parse(Fragments[1]);
                    break;
                }
            }
            Reader.Close();
        }
 public EditableVisualPointInfo[] SplitSelectedText(VisualSelectionRange selectionRange)
 {
     EditableVisualPointInfo[] newPoints = CurrentLine.Split(selectionRange);
     EnsureCurrentTextRun();
     return(newPoints);
 }
Example #17
0
        protected override IInputParameters Parse()
        {
            InputVar <string> landisData = new InputVar <string>("LandisData");

            ReadVar(landisData);
            if (landisData.Value.Actual != PlugIn.ExtensionName)
            {
                throw new InputValueException(landisData.Value.String, "The value " + landisData.Value.Actual + " not \"{0}\"" + dataFile, PlugIn.ExtensionName);
            }

            InputParameters parameters = new InputParameters();

            InputVar <int> timestep = new InputVar <int>(Names.Timestep);

            ReadVar(timestep);
            parameters.Timestep = timestep.Value;

            InputVar <int> StartYear = new InputVar <int>(Names.StartYear);

            ReadVar(StartYear);
            parameters.StartYear = StartYear.Value;

            InputVar <SeedingAlgorithms> seedAlg = new InputVar <SeedingAlgorithms>(Names.SeedingAlgorithm);

            ReadVar(seedAlg);
            parameters.SeedAlgorithm = seedAlg.Value;

            //---------------------------------------------------------------------------------

            InputVar <string> initCommunities = new InputVar <string>("InitialCommunities");

            ReadVar(initCommunities);
            parameters.InitialCommunities = initCommunities.Value;

            InputVar <string> communitiesMap = new InputVar <string>("InitialCommunitiesMap");

            ReadVar(communitiesMap);
            parameters.InitialCommunitiesMap = communitiesMap.Value;


            InputVar <int> Latitude = new InputVar <int>(Names.Latitude);

            ReadVar(Latitude);
            parameters.Latitude = Landis.Library.Biomass.Util.CheckBiomassParm(Latitude.Value, -90, 90);

            if (ReadOptionalName("CanopyLayerBiomassCategories"))
            {
                throw new System.Exception("CanopyLayerBiomassCategories are depreciated, use " + Names.CanopyLayersMax);
            }

            if (ReadOptionalName(Names.CanopyLayersMax))
            {
                while (!AtEndOfInput && CurrentName != Names.PNEToutputsites && CurrentName != Names.SpeciesParameterFile)
                {
                    StringReader currentLine = new StringReader(CurrentLine);

                    InputVar <string> age = new InputVar <string>("Output age");
                    ReadValue(age, currentLine);

                    int MyAge;

                    if (int.TryParse(age.Value, out MyAge))
                    {
                        parameters.CanopyLayerAges.Add(MyAge);
                    }
                    else if (age.Value == "MAX")
                    {
                        throw new System.Exception("MAX is no longer valid for CanopyLayerAges " + dataFile + " the model automatically uses the number of layers associated with the max entered age when age exceeds max age of the top layer.");
                    }
                    else
                    {
                        throw new System.Exception("Cannot add canopy age " + age.Value + " in " + dataFile + " expecting integer");
                    }

                    InputVar <string> numbers = new InputVar <string>("Max foliage layers");
                    ReadValue(numbers, currentLine);

                    int MyNumbers;
                    if (int.TryParse(numbers.Value, out MyNumbers))
                    {
                        parameters.CanopyLayerNumbers.Add(MyNumbers);
                    }

                    else
                    {
                        throw new System.Exception("Expected integers or for CanopyLayerAges in " + dataFile);
                    }


                    GetNextLine();
                }
            }



            if (ReadOptionalName(Names.PNEToutputsites) == true)
            {
                while (!AtEndOfInput && CurrentName != Names.SpeciesParameterFile)
                {
                    StringReader currentLine = new StringReader(CurrentLine);

                    InputVar <int> row = new InputVar <int>("Output row");
                    InputVar <int> col = new InputVar <int>("Output column");

                    ReadValue(row, currentLine);
                    ReadValue(col, currentLine);

                    foreach (ActiveSite site in PlugIn.ModelCore.Landscape)
                    {
                        if (site.Location.Row == row.Value && site.Location.Column == col.Value)
                        {
                            parameters.HasSiteOutput[site] = true;
                        }
                    }


                    GetNextLine();
                }
            }

            //-------------------------
            //  SpeciesParameters table

            InputVar <string> SpeciesParameterFile = new InputVar <string>(Names.SpeciesParameterFile);

            ReadVar(SpeciesParameterFile);
            parameters = ReadSpeciesParameters(SpeciesParameterFile.Value, parameters);


            ReadName(Names.EcoregionParameters);


            InputVar <string> ecoregionName   = new InputVar <string>("Ecoregion");
            InputVar <int>    aet             = new InputVar <int>("AET");
            InputVar <float>  whc             = new InputVar <float>("WHC");
            InputVar <float>  PrecipLossFrac  = new InputVar <float>("PrecipLossFrac");
            InputVar <float>  LeakageFraction = new InputVar <float>("LeakageFraction");
            InputVar <float>  Porosity        = new InputVar <float>("Porosity");
            InputVar <string> climateFileName = new InputVar <string>(Names.climateFileName);

            Dictionary <string, int> lineNumbers = new Dictionary <string, int>();

            string[] ReadHeaders = CurrentLine.Split(new char[] { ',', '\t', ' ' }, System.StringSplitOptions.RemoveEmptyEntries);

            if (ReadHeaders[0] != "Ecoregion")
            {
                throw new System.Exception("The first column header in ecoregion parameters in " + dataFile + " should be 'Ecoregion'. Note that the headerline should NOT be outcommented as in Biomass Succession");
            }

            string[] ExpectedHeaders = new string[] { "Ecoregion", "AET", "WHC", "PrecLossFrac", "LeakageFraction", "Porosity", Names.climateFileName };


            AssureAllHeadersAreProvided(ReadHeaders, ExpectedHeaders);

            GetNextLine();

            while (!AtEndOfInput)
            {
                StringReader currentLine = new StringReader(CurrentLine);

                ReadValue(ecoregionName, currentLine);

                IEcoregion ecoregion = GetEcoregion(ecoregionName.Value, lineNumbers);

                foreach (string label in ReadHeaders)
                {
                    if (label == "Ecoregion")
                    {
                        continue;
                    }

                    InputVar <string> var = new InputVar <string>(label);

                    ReadValue(var, currentLine);

                    if (TrySet(label, "AET", var.Value, 0, 1000, ecoregion, parameters.AET))
                    {
                        continue;
                    }
                    else if (TrySet(label, "WHC", var.Value, 0, 1000, ecoregion, parameters.WHC))
                    {
                        continue;
                    }
                    else if (TrySet(label, "PrecLossFrac", var.Value, 0, 1000, ecoregion, parameters.PrecipLossFrac))
                    {
                        continue;
                    }
                    else if (TrySet(label, "LeakageFraction", var.Value, 0, 1000, ecoregion, parameters.LeakageFrac))
                    {
                        continue;
                    }
                    else if (TrySet(label, "Porosity", var.Value, 0, 1000, ecoregion, parameters.Porosity))
                    {
                        continue;
                    }
                    else if (TrySet(label, Names.climateFileName, var.Value, ecoregion, parameters.climateFileName))
                    {
                        continue;
                    }
                    else
                    {
                        throw new System.Exception("Cannot assign parameter " + label);
                    }
                }
                GetNextLine();
            }


            foreach (IEcoregion ecoregion in PlugIn.modelCore.Ecoregions)
            {
                if (parameters.Porosity[ecoregion] < parameters.WHC[ecoregion])
                {
                    throw new System.Exception("Porosity for " + ecoregion + " cannot exceed water holding capacity in " + dataFile);
                }
            }

            return(parameters);
        }
Example #18
0
        public IActionResult LoadSeasonStats()
        {
            StreamReader sr = new StreamReader("CSVPlayerFile.txt");

            string CurrentLine;
            while((CurrentLine = sr.ReadLine()) != null)
            {
                List<string> LineValues = CurrentLine.Split(',').ToList<string>();
                try
                {
                    double PlayerRank = Convert.ToDouble(LineValues[0]);
                    string PlayerName;
                    if (LineValues[1].Contains('*'))
                    {
                        int index = LineValues[1].IndexOf('*');
                        string result = LineValues[1].Substring(0, index);
                        PlayerName = result;
                    } else {
                        int index = LineValues[1].IndexOf('\\');
                        string result = LineValues[1].Substring(0, index);
                        PlayerName = result;
                    }
                    List<double> Result = new List<double>();
                    foreach(string item in LineValues.Skip(4)){
                        if(item != ""){
                            Result.Add(double.Parse(item));
                        } else {
                            Result.Add(0.0);
                        }
                    }

                    Player ThisPlayer = new Player()
                    {
                        Rank = PlayerRank,
                        TeamName = LineValues[2],
                        Position = LineValues[3],
                        Age = Result[0],
                        Games = Result[1],
                        GamesStarted = Result[2],
                        PassCompleted = Result[3],
                        PassAttempted = Result[4],
                        PassYards = Result[5],
                        PassTouchdowns = Result[6],
                        PassInterfered = Result[7],
                        RushAttempts = Result[8],
                        RushYards = Result[9],
                        RushYA = Result[10],
                        RushTouchdowns = Result[11],
                        RecTargets = Result[12],
                        RecReceptions = Result[13],
                        RecYards = Result[14],
                        RecYR = Result[15],
                        RecTD = Result[16],
                        TwoPtConvMade = Result[17],
                        TwoPtConvPass = Result[18],
                        FPointsNFL = Result[19],
                        FPointsPPR = Result[20],
                        FPointsDraftKing = Result[21],
                        FPointsFanDuel = Result[22],
                        FPointsVBD = Result[23],
                        PosRank = Result[24],
                        OvRank = Result[25],
                        FantasyTeamId = -1,
                    };
                    if(_context.Players.Where(p => p.Name == PlayerName).FirstOrDefault() != null){
                        PlayerName += '2';
                        ThisPlayer.Name = PlayerName;
                        _context.Add(ThisPlayer);
                    } else {
                        ThisPlayer.Name = PlayerName;
                    }
                    Team TeamOfPlayer = _context.Teams.SingleOrDefault(t => t.Abbr == LineValues[2]);
                    TeamOfPlayer.Players.Add(ThisPlayer);
                    _context.SaveChanges();
                } catch(Exception e) {
                    System.Console.WriteLine("An error occurred: '{0}'", e);
                }
            }
            return RedirectToAction("DisplayPlayers");
        }
        //RECOPILAR LA INFORMACIÓN DEL ARCHIVO
        public void ReadFileC(string UserDeveloper, bool PM)
        {
            //ELIMINAR INFORMACIÓN DE LA COLA DE PRIORIDAD
            int counting = Singleton.Instance.PriorityHomeworkDate.CountObj();

            for (int i = 0; i < counting; i++)
            {
                HeapNode <PriorityHomework> TitlePriority = Singleton.Instance.PriorityHomeworkDate.HeapDelete();
            }

            //RECOPILAR INFORMACIÓN ANTERIOR
            string       filePath     = bingPathToAppDir();
            StreamReader streamReader = new StreamReader(filePath);
            string       CurrentLine;
            string       Concatenando = "";
            bool         First        = true;
            bool         Repeat       = true;

            while (!streamReader.EndOfStream)
            {
                CurrentLine = streamReader.ReadLine();
                string[] FileInformationList = CurrentLine.Split(',');
                int      pos = 0;

                //VARIABLES
                string FileTitle       = "";
                string FileDescription = "";
                string FileProject     = "";
                string FilePriority    = "";
                string FileDate        = "";
                string FileDeveloper   = "";

                if (Singleton.Instance.HelpFile.Count() == 0)
                {
                    Singleton.Instance.HelpFile.InsertAtStart(1);
                }

                //TITULO
                //Titulo con " "
                if (FileInformationList[pos].Substring(0, 1) == "\"")
                {
                    while (Repeat == true)
                    {
                        if (First == true)
                        {
                            Concatenando += FileInformationList[pos];
                            First         = false;
                        }
                        else
                        {
                            Concatenando += "," + FileInformationList[pos];
                        }

                        string FileLength = FileInformationList[pos];
                        if (FileInformationList[pos].Substring(FileLength.Length - 1, 1) == "\"")
                        {
                            Repeat = false;
                        }
                        pos++;
                    }
                }
                else
                {
                    //Titulo sin " "
                    Concatenando = FileInformationList[pos];
                    pos++;
                }
                //GUARDAR TÍTULO
                FileTitle = Concatenando;

                //DESCRIPCIÓN
                Repeat       = true;
                First        = true;
                Concatenando = "";
                //Descripción con " "
                if (FileInformationList[pos].Substring(0, 1) == "\"")
                {
                    while (Repeat == true)
                    {
                        if (First == true)
                        {
                            Concatenando += FileInformationList[pos];
                            First         = false;
                        }
                        else
                        {
                            Concatenando += "," + FileInformationList[pos];
                        }

                        string FileLength = FileInformationList[pos];
                        if (FileInformationList[pos].Substring(FileLength.Length - 1, 1) == "\"")
                        {
                            Repeat = false;
                        }
                        pos++;
                    }
                }
                else
                {
                    //Descripción sin " "
                    Concatenando = FileInformationList[pos];
                    pos++;
                }
                FileDescription = Concatenando;

                //PROYECTO
                FileProject = FileInformationList[pos];
                pos++;

                //PRIORIDAD
                FilePriority = FileInformationList[pos];
                pos++;

                //FECHA
                FileDate = FileInformationList[pos];
                pos++;

                //NOMBRE DEL DEVELOPER
                FileDeveloper = FileInformationList[pos];

                //AGREGAR
                var CollectHomework = new Models.Homework
                {
                    Title        = FileTitle,
                    Description  = FileDescription,
                    Project      = FileProject,
                    Priority     = Convert.ToInt32(FilePriority),
                    DeliveryDate = Convert.ToDateTime(FileDate),
                    Developer    = FileDeveloper
                };

                if (Singleton.Instance.HashTableHomework.ValueRepeat(CollectHomework) == false)
                {
                    //AGREGAR A LA TABLA DE HASH
                    Singleton.Instance.HashTableHomework.AddHashTable(CollectHomework);
                }

                if (PM == false)
                {
                    //AGREGAR A LA COLA DE PRIORIDAD SI ES DEL DEVELOPER QUE INICIO SESIÓN
                    if (FileDeveloper == UserDeveloper)
                    {
                        //OBJETO DE PRIORIDAD
                        var NewPriority = new Models.PriorityHomework
                        {
                            Title       = FileTitle,
                            DeliverDate = Convert.ToDateTime(FileDate),
                            priority    = Convert.ToInt32(FilePriority)
                        };

                        //AGREGAR A LA COLA DE PRIORIODAD
                        Singleton.Instance.PriorityHomeworkDate.HeapInsert(NewPriority, NewPriority);
                    }
                }
            }
            //CERRAR LA LECTURA DEL ARCHIVO
            streamReader.Close();
        }
        //RECUPERANDO DATOS ANTERIORES
        public void ReadFileC()
        {
            //RECOPILAR INFORMACIÓN ANTERIOR
            string       filePath     = bingPathToAppDir();
            StreamReader streamReader = new StreamReader(filePath);
            string       CurrentLine;

            while (!streamReader.EndOfStream)
            {
                CurrentLine = streamReader.ReadLine();

                if (CurrentLine != "")
                {
                    string[] FileInformationList = CurrentLine.Split(',');
                    int      pos     = 0;
                    string   NombreF = FileInformationList[pos];
                    pos++;
                    string ApellidoF = FileInformationList[pos];
                    pos++;
                    long DPIF = Convert.ToInt64(FileInformationList[pos]);
                    pos++;
                    int EdadF = Convert.ToInt16(FileInformationList[pos]);
                    pos++;
                    string DepartamentoF = FileInformationList[pos];
                    pos++;
                    string MunicipioF = FileInformationList[pos];
                    pos++;
                    string DirecciónF = FileInformationList[pos];
                    pos++;
                    int TelefonoF = Convert.ToInt32(FileInformationList[pos]);
                    pos++;
                    string EmailF = FileInformationList[pos];
                    pos++;
                    string TrabajoF = FileInformationList[pos];
                    pos++;
                    string EnfermedadF = FileInformationList[pos];
                    pos++;
                    int GrupoF = Convert.ToInt32(FileInformationList[pos]);
                    pos++;
                    int NRF = Convert.ToInt32(FileInformationList[pos]);

                    if (MunicipioF == Singleton.Instance.LocationData.ElementAt(0).Municipio)
                    {
                        var NewUser = new Models.UserInformation
                        {
                            Nombre       = NombreF,
                            Apellido     = ApellidoF,
                            DPI          = DPIF,
                            Edad         = EdadF,
                            Departamento = DepartamentoF,
                            Municipio    = MunicipioF,
                            Dirección    = DirecciónF,
                            Teléfono     = TelefonoF,
                            Email        = EmailF,
                            Trabajo      = TrabajoF,
                            Enfermedad   = EnfermedadF,
                            Grupo        = GrupoF,
                            N_Registro   = NRF
                        };

                        //REVISAR QUE NO SEA UN DATO REPETIDO
                        if (Singleton.Instance.HashTableUserInformation.ValueRepeat(NewUser) == false)
                        {
                            //INGRESAR A LA TABLA HASH
                            Singleton.Instance.HashTableUserInformation.AddHashTable(NewUser);

                            //INGRESAR A LA LISTA DE PRIORIDAD
                            var NewPriority = new Models.PriorityInformation
                            {
                                Priority = GrupoF,
                                DPI      = DPIF,
                                N_order  = NRF
                            };
                            Singleton.Instance.PriorityUsers.HeapInsert(NewPriority, NewPriority);

                            //INGRESAR AL ÁRBOL AVL POR NOMBRE
                            var NewUserName = new Models.Data.NameUser
                            {
                                Name    = NombreF,
                                DPI_AVL = DPIF
                            };
                            Singleton.Instance.IndexName.Insert(NewUserName);

                            //INGRESAR AL ÁRBOL AVL POR APELLIDO
                            var NewUserLastName = new Models.Data.LastNameUser
                            {
                                LastName = ApellidoF,
                                DPI_AVL  = DPIF
                            };
                            Singleton.Instance.IndexLastName.Insert(NewUserLastName);

                            //INGRESAR AL ÁRBOL AVL POR DPI
                            var NewDPI = new Models.Data.DPIUser
                            {
                                DPI = DPIF
                            };
                            Singleton.Instance.IndexDPI.Insert(NewDPI);

                            var NewUserExtra = new Models.UserInformation
                            {
                                Nombre   = NombreF,
                                Apellido = ApellidoF,
                                DPI      = DPIF
                            };

                            //ORDEN DE LLEGADA
                            if (Singleton.Instance.Order.Count() == 0)
                            {
                                Singleton.Instance.Order.InsertAtStart(1);
                            }
                            else
                            {
                                Singleton.Instance.Order.InsertAtEnd(1);
                            }

                            if (Singleton.Instance.OrderNum.Count() == 0)
                            {
                                Singleton.Instance.OrderNum.InsertAtStart(NewUserExtra);
                            }
                            else
                            {
                                Singleton.Instance.OrderNum.InsertAtEnd(NewUserExtra);
                            }
                        }
                    }
                    else
                    {
                        if (Singleton.Instance.Order.Count() == 0)
                        {
                            Singleton.Instance.Order.InsertAtStart(1);
                        }
                    }
                }
            }
            //CERRAR LA LECTURA DEL ARCHIVO
            streamReader.Close();
        }
Example #21
0
        /// <summary>
        /// Returns a new FuzzySystem of the appropriate sub-type.
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static FuzzySystem GetFuzzySystemFromFile(string FileName)
        {
            // Open the file
            StreamReader file;
            string       CurrentLine;

            try
            {
                file = new StreamReader(FileName);
            }
            catch (FileNotFoundException exc)
            {
                throw exc;
            }

            FuzzySystem fuzzy = null;

            // Find the type and create the fuzzy system accordingly
            while ((CurrentLine = file.ReadLine()) != null)
            {
                if (CurrentLine.StartsWith("Type="))
                {
                    FuzzyType type = FuzzySystem.StringToFuzzyType(CurrentLine.Replace("Type=", "").Replace("'", ""));
                    switch (type)
                    {
                    case FuzzyType.Mamdani:
                        fuzzy = new MamdaniFS();
                        break;

                    case FuzzyType.Larsen:
                        fuzzy = new LarsenFS();
                        break;

                    case FuzzyType.Sugeno:
                        fuzzy = new SugenoFS();
                        break;

                    case FuzzyType.Sparse:
                    default:
                        throw new NotImplementedException();
                    }
                    file = new StreamReader(FileName);
                    break;
                }
            }

            bool FoundSystem = false;
            bool FoundIn     = false;
            bool FoundOut    = false;
            bool FoundRules  = false;

            while ((CurrentLine = file.ReadLine()) != null)
            {
                // When we reach the [System] tag, we read the system setting from the following lines until we hit an empty line or the end of the file
                if (CurrentLine == "[System]")
                {
                    FoundSystem = true;
                    while ((CurrentLine = file.ReadLine()) != null && CurrentLine != "")
                    {
                        if (CurrentLine.StartsWith("Name="))
                        {
                            fuzzy.Name = CurrentLine.Replace("Name=", "").Replace("'", "");
                        }
                        //else if (CurrentLine.StartsWith("Type="))
                        //fuzzy.Type = StringToFuzzyType(CurrentLine.Replace("Type=", "").Replace("'", ""));
                        else if (CurrentLine.StartsWith("Version="))
                        {
                            fuzzy.Version = CurrentLine.Replace("Version=", "");
                        }
                        else if (CurrentLine.StartsWith("NumInputs="))
                        {
                            fuzzy.NumInputs = int.Parse(CurrentLine.Replace("NumInputs=", ""));
                        }
                        else if (CurrentLine.StartsWith("NumOutputs="))
                        {
                            fuzzy.NumOutputs = int.Parse(CurrentLine.Replace("NumOutputs=", ""));
                        }
                        else if (CurrentLine.StartsWith("NumRules="))
                        {
                            fuzzy.NumRules = int.Parse(CurrentLine.Replace("NumRules=", ""));
                        }
                        // Method types
                        else if (CurrentLine.StartsWith("AndMethod="))
                        {
                            fuzzy.AndMethod = FuzzySystem.StringToAndMethod(CurrentLine.Split('\'')[1]);
                        }
                        else if (CurrentLine.StartsWith("OrMethod="))
                        {
                            fuzzy.OrMethod = FuzzySystem.StringToOrMethod(CurrentLine.Split('\'')[1]);
                        }
                        else if (CurrentLine.StartsWith("ImpMethod="))
                        {
                            fuzzy.ImpMethod = FuzzySystem.StringToImpMethod(CurrentLine.Split('\'')[1]);
                        }
                        else if (CurrentLine.StartsWith("AggMethod="))
                        {
                            fuzzy.AggMethod = FuzzySystem.StringToAggMethod(CurrentLine.Split('\'')[1]);
                        }
                        else if (CurrentLine.StartsWith("DefuzzMethod="))
                        {
                            fuzzy.DefuzzMethod = FuzzySystem.StringToDefuzzMethod(CurrentLine.Split('\'')[1]);
                        }
                    }
                }
                // When we reach an [Input_] tag, we read the setting from the following lines until we hit an empty line or the end of the file
                if (CurrentLine.StartsWith("[Input") && CurrentLine.EndsWith("]"))
                {
                    FoundIn = true;
                    int index = int.Parse(CurrentLine.Replace("[Input", "").Replace("]", "")) - 1;
                    fuzzy.Inputs[index] = new InputOutput
                    {
                        IsInput = true,
                        Index   = index + 1
                    };
                    while ((CurrentLine = file.ReadLine()) != null && CurrentLine != "")
                    {
                        if (CurrentLine.StartsWith("Name="))
                        {
                            fuzzy.Inputs[index].Name = CurrentLine.Replace("Name=", "").Replace("'", "");
                        }
                        else if (CurrentLine.StartsWith("Range="))
                        {
                            fuzzy.Inputs[index].Range[0] = float.Parse(CurrentLine.Replace("Range=[", "").Split(' ')[0], System.Globalization.CultureInfo.InvariantCulture);
                            fuzzy.Inputs[index].Range[1] = float.Parse(CurrentLine.Replace("]", "").Split(' ')[1], System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (CurrentLine.StartsWith("NumMFs="))
                        {
                            fuzzy.Inputs[index].NumMFs = int.Parse(CurrentLine.Replace("NumMFs=", ""));
                        }
                        else if (CurrentLine.StartsWith("MF"))
                        {
                            try
                            {
                                fuzzy.Inputs[index].MFs[int.Parse(CurrentLine.Split('=')[0].Remove(0, 2)) - 1] = new MembershipFunction(CurrentLine.Split('=')[1]);
                            }
                            catch (Exception exc)
                            {
                                throw exc;
                            }
                        }
                    }
                }
                // When we reach an [Output_] tag, we read the setting from the following lines until we hit an empty line or the end of the file
                if (CurrentLine.StartsWith("[Output") && CurrentLine.EndsWith("]"))
                {
                    FoundOut = true;
                    int index = int.Parse(CurrentLine.Replace("[Output", "").Replace("]", "")) - 1;
                    fuzzy.Outputs[index] = new InputOutput
                    {
                        IsInput = false,
                        Index   = index + 1
                    };
                    while ((CurrentLine = file.ReadLine()) != null && CurrentLine != "")
                    {
                        if (CurrentLine.StartsWith("Name="))
                        {
                            fuzzy.Outputs[index].Name = CurrentLine.Replace("Name=", "").Replace("'", "");
                        }
                        else if (CurrentLine.StartsWith("Range="))
                        {
                            fuzzy.Outputs[index].Range[0] = float.Parse(CurrentLine.Replace("Range=[", "").Split(' ')[0], System.Globalization.CultureInfo.InvariantCulture);
                            fuzzy.Outputs[index].Range[1] = float.Parse(CurrentLine.Replace("]", "").Split(' ')[1], System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (CurrentLine.StartsWith("NumMFs="))
                        {
                            fuzzy.Outputs[index].NumMFs = int.Parse(CurrentLine.Replace("NumMFs=", ""));
                        }
                        else if (CurrentLine.StartsWith("MF"))
                        {
                            fuzzy.Outputs[index].MFs[int.Parse(CurrentLine.Split('=')[0].Remove(0, 2)) - 1] = new MembershipFunction(CurrentLine.Split('=')[1]);
                        }
                    }
                }
                // When we reach the [Rules] tag, we read the setting from the following lines until we hit an empty line or the end of the file
                if (CurrentLine.StartsWith("[Rules") && CurrentLine.EndsWith("]"))
                {
                    FoundRules = true;
                    int index = 0;
                    while ((CurrentLine = file.ReadLine()) != null && CurrentLine != "")
                    {
                        fuzzy.Rules[index] = new Rule(CurrentLine);
                        index++;
                    }
                }
            }

            // Check if we found all relevant data
            if (!(FoundSystem && FoundIn && FoundOut && FoundRules))
            {
                string missing = "Could not find the following tags:";
                if (!FoundSystem)
                {
                    missing += " [System]";
                }
                if (!FoundIn)
                {
                    missing += " [Input]";
                }
                if (!FoundSystem)
                {
                    missing += " [Output]";
                }
                if (!FoundSystem)
                {
                    missing += " [Rules]";
                }
                throw new Exception(missing);
            }

            if (fuzzy != null)
            {
                return(fuzzy);
            }

            throw new Exception("Couldn't read fuzzy system.");
        }
Example #22
0
        public void Insert(String Path, ARM9 Arm9)
        {
            ASMHackInfo Info = ASMHackInfo.FromByteArray(File.ReadAllBytes(Path + "\\config.xml"));

            UInt32 ArenaLoOffset = Info.ArenaLo;            //UInt32.Parse(File.ReadAllText(CodeDir + "\\arenaoffs.txt"), System.Globalization.NumberStyles.HexNumber);
            UInt32 ArenaLo       = Arm9.ReadU32LE(ArenaLoOffset);

            Compile(Path, ArenaLo);
            if (!File.Exists(Path + "\\newcode.bin"))
            {
                MessageBox.Show("An compile error occurred!");
                return;
            }
            byte[] NewCode = File.ReadAllBytes(Path + "\\newcode.bin");

            StreamReader r = new StreamReader(Path + "\\newcode.sym");
            string       CurrentLine;

            while ((CurrentLine = r.ReadLine()) != null)
            {
                string[] Line = CurrentLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (Line.Length == 4)
                {
                    if (Line[3].Length < 7)
                    {
                        continue;
                    }
                    switch (Line[3].Remove(6))
                    {
                    case "arepl_":
                    {
                        String ReplaceOffsetString       = Line[3].Replace("arepl_", "");
                        UInt32 ReplaceOffset             = UInt32.Parse(ReplaceOffsetString, System.Globalization.NumberStyles.HexNumber);
                        UInt32 Replace                   = 0xEB000000;                      //BL Instruction
                        UInt32 DestinationOffset         = UInt32.Parse(Line[0], System.Globalization.NumberStyles.HexNumber);
                        UInt32 RelativeDestinationOffset = (DestinationOffset / 4) - (ReplaceOffset / 4) - 2;
                        RelativeDestinationOffset &= 0x00FFFFFF;
                        Replace |= RelativeDestinationOffset;
                        if (!Arm9.WriteU32LE(ReplaceOffset, Replace))
                        {
                            System.Windows.Forms.MessageBox.Show("The offset of function " + Line[3] + " is invalid. Maybe your code is inside an overlay or you wrote the wrong offset.");
                        }
                        break;
                    }

                    case "ansub_":
                    {
                        String ReplaceOffsetString       = Line[3].Replace("ansub_", "");
                        UInt32 ReplaceOffset             = UInt32.Parse(ReplaceOffsetString, System.Globalization.NumberStyles.HexNumber);
                        UInt32 Replace                   = 0xEA000000;                      //B Instruction
                        UInt32 DestinationOffset         = UInt32.Parse(Line[0], System.Globalization.NumberStyles.HexNumber);
                        UInt32 RelativeDestinationOffset = (DestinationOffset / 4) - (ReplaceOffset / 4) - 2;
                        RelativeDestinationOffset &= 0x00FFFFFF;
                        Replace |= RelativeDestinationOffset;
                        if (!Arm9.WriteU32LE(ReplaceOffset, Replace))
                        {
                            System.Windows.Forms.MessageBox.Show("The offset of function " + Line[3] + " is invalid. Maybe your code is inside an overlay or you wrote the wrong offset.");
                        }
                        break;
                    }

                    case "trepl_":
                    {
                        String ReplaceOffsetString       = Line[3].Replace("trepl_", "");
                        UInt32 ReplaceOffset             = UInt32.Parse(ReplaceOffsetString, System.Globalization.NumberStyles.HexNumber);
                        UInt16 Replace1                  = 0xF000;                       //BLX Instruction (Part 1)
                        UInt16 Replace2                  = 0xE800;                       //BLX Instruction (Part 2)
                        UInt32 DestinationOffset         = UInt32.Parse(Line[0], System.Globalization.NumberStyles.HexNumber);
                        UInt32 RelativeDestinationOffset = DestinationOffset - ReplaceOffset - 2;
                        RelativeDestinationOffset >>= 1;
                        RelativeDestinationOffset  &= 0x003FFFFF;
                        Replace1 |= (UInt16)((RelativeDestinationOffset >> 11) & 0x7FF);
                        Replace2 |= (UInt16)((RelativeDestinationOffset >> 0) & 0x7FE);
                        if (!Arm9.WriteU16LE(ReplaceOffset, Replace1))
                        {
                            MessageBox.Show("The offset of function " + Line[3] + " is invalid. Maybe your code is inside an overlay or you wrote the wrong offset.\r\nIf your code is inside an overlay, this is an action replay code to let your asm hack still work:\r\n1" + string.Format("{0:X7}", ReplaceOffset) + " 0000" + string.Format("{0:X4}", Replace1) + "\r\n1" + string.Format("{0:X7}", ReplaceOffset + 2) + " 0000" + string.Format("{0:X4}", Replace2)); break;
                        }
                        else
                        {
                            Arm9.WriteU16LE(ReplaceOffset + 2, Replace2);
                        }
                        break;
                    }
                    }
                }
            }
            r.Close();
            Arm9.WriteU32LE(ArenaLoOffset, ArenaLo + (uint)NewCode.Length);
            Arm9.AddAutoLoadEntry(ArenaLo, NewCode);
            File.Delete(Path + "\\newcode.bin");
            File.Delete(Path + "\\newcode.elf");
            File.Delete(Path + "\\newcode.sym");
            Directory.Delete(Path + "\\build", true);
        }
        /// <summary>
        /// Splits out the translated file into seperate files based off the store number
        /// </summary>
        /// <param name="FileName">FileName to split</param>
        /// <param name="ColDelimeter">The column in the file to use as the distinc seperator of files</param>
        private void SplitTranslatedFile(string FileName, int ColDelimeter)
        {
            string CurrentLine;

            string[]      splitLine;
            int           StoreLine;
            StringBuilder sbFile = new StringBuilder();
            StreamWriter  writer;
            string        DirToSave  = PluginConfig.GetValue("TranslatedFileLocation");
            string        FileToSave = "";
            int           TotalFiles = 0;

            using (FileStream stream = File.OpenRead(FileName))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    int CurrentStore = -1;
                    while (reader.Peek() != -1)
                    {
                        CurrentLine = reader.ReadLine();
                        if (String.IsNullOrEmpty(CurrentLine))
                        {
                            continue;
                        }

                        splitLine = CurrentLine.Split('\t');
                        StoreLine = Convert.ToInt32(splitLine[ColDelimeter]);
                        if (CurrentStore == -1)
                        {
                            CurrentStore = StoreLine;
                        }

                        if (StoreLine == CurrentStore)
                        {
                            sbFile.Append(CurrentLine + "\r\n");
                        }
                        else
                        {
                            LogMessage(String.Format("Saving Tlog for store {0} to polling server ({1})", CurrentStore.ToString(), DirToSave));
                            FileToSave = "TLog" + CurrentStore.ToString().PadLeft(5, '0');
                            TotalFiles = Directory.GetFiles(DirToSave, FileToSave + "*").Length;
                            if (TotalFiles > 0)
                            {
                                FileToSave = FileToSave + "." + TotalFiles.ToString().PadLeft(4, '0');
                            }

                            writer = new StreamWriter(DirToSave + "\\" + FileToSave);
                            writer.WriteLine(sbFile.ToString().TrimEnd("\r\n".ToCharArray()));
                            writer.Close();
                            sbFile = new StringBuilder();
                            sbFile.Append(CurrentLine + "\r\n");
                            CurrentStore = StoreLine;
                        }
                    }
                    LogMessage(String.Format("Saving Tlog for store {0} to polling server ({1})", CurrentStore.ToString(), DirToSave));
                    FileToSave = "TLog" + CurrentStore.ToString().PadLeft(5, '0');
                    TotalFiles = Directory.GetFiles(DirToSave, FileToSave + "*").Length;
                    if (TotalFiles > 0)
                    {
                        FileToSave = FileToSave + "." + TotalFiles.ToString().PadLeft(4, '0');
                    }

                    //writer = new StreamWriter(PluginConfig.GetValue("TranslatedFileLocation") + "\\TLog" + CurrentStore.ToString().PadLeft(5, '0'));
                    writer = new StreamWriter(DirToSave + "\\" + FileToSave);
                    writer.WriteLine(sbFile.ToString().TrimEnd("\r\n".ToCharArray()));
                    writer.Close();
                }
            }
        }
Example #24
0
        public static void Update()
        {
            if (InputManager.ScrolledDown())
            {
                ScrollPosition -= 1;
            }
            if (InputManager.ScrolledUp())
            {
                ScrollPosition += 1;
            }

            ScrollPosition = MathHelper.Clamp(ScrollPosition, 0, ConsoleMessages.Count - 9);

            if (InputManager.PressingMouseLeft())
            {
                if (InputManager.MouseBoxScreen.Intersects(new Rectangle(ConsoleWindowPosition.ToPoint(), ConsoleWindowSize.ToPoint())))
                {
                    Vector2 offset = ConsoleWindowPosition - InputManager.MousePositionScreen;

                    ConsoleWindowPosition = InputManager.MousePositionScreen + offset;

                    ConsoleWindowPosition += InputManager.MouseVelocityScreen;
                }
            }

            Keys[] pressedKeys = InputManager.GetAllPressedKeys();

            if (pressedKeys.Contains(Keys.Enter))
            {
                if (CurrentLine == "")
                {
                    return;
                }
                else
                {
                    if (CurrentLine[0] == char.Parse("/"))
                    {
                        // BEGIN PARSING

                        string[] splitIntoWords = CurrentLine.Split(char.Parse(" "));

                        string key = splitIntoWords[0].Remove(0, 1);
                        //key = key.Remove(key.Length - 1, 1);

                        string[] args = new string[splitIntoWords.Length - 1];

                        for (int i = 1; i < splitIntoWords.Length; i++)
                        {
                            args[i - 1] = splitIntoWords[i];
                        }

                        foreach (Command command in ConsoleCommands)
                        {
                            if (command.Key == key)
                            {
                                command.SimulateExecution(args);
                                CurrentLine = "";

                                return;
                            }
                        }

                        SendMessage(new Message("Invalid Command: " + key, Message.MessageType.Error));
                    }
                    else
                    {
                        SendMessage(new Message("Must write a command.", Message.MessageType.Warning));
                    }
                }

                CurrentLine = "";
            }
        }
Example #25
0
        /// <summary>
        /// Runs a desktop file.
        /// </summary>
        /// <param name="path">Path to the desktop file.</param>
        /// <param name="verbose"></param>
        /// <returns></returns>
        public static ErrorCode Run(string path, bool verbose = false)
        {
            if (string.IsNullOrEmpty(path))
            {
                if (verbose)
                {
                    WriteLine($"Path is {(path == null ? "null" : "empty")}.");
                }

                return(path == null ?
                       ErrorCode.NullPath : ErrorCode.EmptyPath);
            }

            FileInfo file = new FileInfo(path);

            if (!file.Exists)
            {
                if (verbose)
                {
                    WriteLine($"Error: \"{path}\" does not exist.");
                }

                return(ErrorCode.FileNotFound);
            }
            else if (verbose)
            {
                WriteLine("File found.");
            }

            // Defaults
            DesktopFileType type = default(DesktopFileType);
            string          CurrentLine;
            ushort          CurrentLineIndex = 0;

            string[] LineValues;
            // User set
            string value    = string.Empty;
            bool   terminal = false;

            char[] SPLITTER = new char[] { DELIMITER };

            if (verbose)
            {
                WriteLine($"Reading {file.Name}...");
            }

            using (StreamReader sr = file.OpenText())
            {
                if (sr.ReadLine() != "[Desktop Entry]")
                {
                    return(ErrorCode.FileNoSignature);
                }

                while (!sr.EndOfStream)
                {
                    CurrentLine = sr.ReadLine();

                    // line[0] == '[' // Group header (Soon?)
                    if (CurrentLine[0] != '#') // Avoid comments.
                    {
                        if (!CurrentLine.Contains("="))
                        {
                            if (verbose)
                            {
                                WriteLine($"Error: Line {CurrentLineIndex + 1} missing the '=' delimiter.");
                            }

                            return(ErrorCode.FileMissingDelimiter);
                        }

                        LineValues = CurrentLine.Split(SPLITTER,
                                                       StringSplitOptions.RemoveEmptyEntries);

                        switch (LineValues[0])
                        {
                        case "Type":
                            switch (LineValues[1])
                            {
                            case "Application":
                                type = DesktopFileType.Application;
                                break;

                            case "Link":
                                type = DesktopFileType.Link;
                                break;

                            case "Directory":
                                type = DesktopFileType.Directory;
                                break;

                            default:
                                return(ErrorCode.FileMissingType);
                            }

                            if (verbose)
                            {
                                WriteLine($"TYPE SET AS {type}");
                            }
                            break;

                        case "Exec":
                        case "TryExec":
                            value = LineValues[1];

                            if (verbose)
                            {
                                WriteLine($"EXEC SET {value}");
                            }
                            break;

                        case "Url":
                        case "URL":
                            value = LineValues[1];

                            if (verbose)
                            {
                                WriteLine($"URL SET {value}");
                            }
                            break;

                        case "Path":
                            value = LineValues[1];

                            if (verbose)
                            {
                                WriteLine($"PATH SET {value}");
                            }
                            break;

                        case "Terminal":
                            terminal = LineValues[1].ToUpper() == "TRUE";

                            if (terminal && verbose)
                            {
                                WriteLine("TERMINAL SET TRUE");
                            }
                            break;
                        }
                    }

                    ++CurrentLineIndex;
                } // End while
            }     // End using

            if (verbose)
            {
                WriteLine($"Starting...");
            }

            if (string.IsNullOrWhiteSpace(value))
            {
                switch (type)
                {
                case DesktopFileType.Application: return(ErrorCode.FileMissingExecValue);

                case DesktopFileType.Link: return(ErrorCode.FileMissingUrlValue);

                case DesktopFileType.Directory: return(ErrorCode.FileMissingPathValue);
                }
            }

            if (value.Contains("%") || value.Contains("$"))
            {
                ReplaceVars(ref value, verbose);
            }

            if (value.Contains("~"))
            {
                ReplaceHome(ref value, verbose);
            }

            switch (type)
            {
                #region Application
            // Launch an application.
            case DesktopFileType.Application:
                try
                {
                    if (terminal)
                    {
                        Process.Start("cmd", $"/c {value}");
                    }
                    else
                    {
                        Process.Start(value);
                    }
                }
                catch (InvalidOperationException)
                {
                    return(ErrorCode.ExecInvalidOperation);
                }
                catch (System.ComponentModel.Win32Exception ex)
                {
                    if (verbose)
                    {
                        WriteLine($"Exception: {Ex(ex.InnerException ?? ex)}");
                    }

                    return(ErrorCode.ExecWin32Error);
                }
                catch (Exception ex)
                {
                    if (verbose)
                    {
                        WriteLine($"Exception: {Ex(ex)}");
                    }

                    return(ErrorCode.ExecError);
                }
                break;
                #endregion App

                #region Link
            // Launch the user's default application that handles URLs.
            case DesktopFileType.Link:
                try
                {
                    Process.Start(value);
                }
                catch (Exception ex)
                {
                    if (verbose)
                    {
                        WriteLine($"Exception: {Ex(ex)}");
                    }

                    return(ErrorCode.LinkError);
                }
                break;
                #endregion Link

                #region Directory
            // Open File Explorer with a specific path/directory with File Explorer.
            case DesktopFileType.Directory:
                if (Directory.Exists(value))
                {
                    try
                    {
                        Process.Start(
                            $"{GetFolderPath(SpecialFolder.Windows)}\\explorer",
                            value);     // .Replace("/", @"\")
                    }
                    catch (Exception ex)
                    {
                        if (verbose)
                        {
                            WriteLine($"{Ex(ex)}");
                        }

                        return(ErrorCode.DirectoryError);
                    }
                }
                else
                {
                    if (verbose)
                    {
                        WriteLine($"Error: Directory \"{value}\" could not be found.");
                    }

                    return(ErrorCode.DirectoryNotFound);
                }
                break;
                #endregion Directory
            } // End switch

            if (verbose)
            {
                WriteLine("Started successfully.");
            }

            return(0); // 0 is ErrorCode.Success
        }