Esempio n. 1
0
 public static string GetString(string fileName, string section, string name, string defaut)
 {
     string line;
     try
     {
         System.IO.StreamReader file = new System.IO.StreamReader(fileName);
         while ((line = file.ReadLine()) != null)
         {
             if (line.TrimStart(' ').StartsWith("[" + section + "]"))
                 break;
         }
         while ((line = file.ReadLine()) != null)
         {
             if (line.TrimStart(' ').StartsWith("["))
                 break;
             if (line.TrimStart(' ').StartsWith(name + "="))
             {
                 int indexEgal = line.IndexOf('=') + 1;
                 return line.Substring(indexEgal , line.Length - indexEgal);
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Une exeption a ete detecte : "+e.Message);
     }
     return defaut;
 }
Esempio n. 2
0
        public static Vector2[][] getMap(string mapName, out Vector2 tileSize)
        {
            System.IO.TextReader tr = new System.IO.StreamReader("Content/TopDown/Maps/" + mapName + "/map.txt");
            string tempTileSize = tr.ReadLine();
            string[] tempTileSizes = tempTileSize.Split(',');
            tileSize = new Vector2(float.Parse(tempTileSizes[0]), float.Parse(tempTileSizes[1]));
            string tempMapSize = tr.ReadLine();
            string[] tempMapSizes = tempMapSize.Split(',');
            Vector2 mapSize = new Vector2(float.Parse(tempMapSizes[0]), float.Parse(tempMapSizes[1]));
            string[] mapRows = new string[(int)mapSize.Y];
            Vector2[][] returnMap = new Vector2[(int)mapSize.X][];
            for (int i = 0; i < mapSize.Y; i++)
            {
                mapRows[i] = tr.ReadLine();
            }
            for (int j = 0; j < mapSize.X; j++)
            {
                returnMap[j] = new Vector2[(int)mapSize.Y];
            }

            for (int y = 0; y < mapSize.Y; y++)
            {
                string[] currentRow = mapRows[y].Split(';');
                for (int x = 0; x < mapSize.X; x++)
                {
                    string[] xy = currentRow[x].Split(',');
                    returnMap[x][y] = new Vector2(float.Parse(xy[0]), float.Parse(xy[1]));
                }
            }

            return returnMap;
        }
Esempio n. 3
0
        public void runScriptFile()
        {
            Console.WriteLine("\r\n#Client: Running Script " + ScriptName);
            System.IO.StreamReader fileReader = new System.IO.StreamReader(ScriptLocation);

            String line = fileReader.ReadLine();
            while (line != null)
            {
                if (line.StartsWith("#"))
                {
                    line = fileReader.ReadLine();
                    continue;
                }
                else
                {
                    try
                    {
                        exeScriptCommand(line);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("#ClientScriptExecutor: " + e.Message);
                    }

                    line = fileReader.ReadLine();
                }
            }
            Console.WriteLine("#Client: End of Script " + ScriptName + "\r\n");
            fileReader.Close();
        }
Esempio n. 4
0
        static void insertCountries()
        {
            MySqlCommand cmd = new MySqlCommand("INSERT INTO `climate`.`countries` (`abbreviation`,`name`) VALUES (@abbrev,@name);", conn);

            conn.Open();
            System.IO.StreamReader countries = new System.IO.StreamReader("Y:\\country-list.txt");
            System.IO.StreamWriter csvCountries = new System.IO.StreamWriter("Y:\\country-list.csv");

            Console.WriteLine(countries.ReadLine());
            Console.WriteLine(countries.ReadLine());

            while (countries.Peek() > 0)
            {
                string line = countries.ReadLine();
                string[] strings = line.Split(new string[] { "          " }, StringSplitOptions.RemoveEmptyEntries);
                //string[] strings = line.Split(new char[] { ' ' }, 12);
                Console.WriteLine(strings[0] + "," + strings[1]);
                csvCountries.WriteLine(strings[0] + "," + strings[1]);
                cmd.Parameters.AddWithValue("abbrev", strings[0]);
                cmd.Parameters.AddWithValue("name", strings[1]);

                cmd.ExecuteScalar();
                cmd.Parameters.Clear();
            }

            conn.Close();
            csvCountries.Close();
            countries.Close();
        }
Esempio n. 5
0
 /// <summary>
 /// Считывает названия городов из файлов карт
 /// <para>Использует пути к файлам из class FilesDirectories</para>
 /// </summary>
 public void readCities(params string[] mapFiles)
 {
     CitiesList = new List<string>();
     for (int i = 0; i < mapFiles.Length; ++i)
     {
         System.IO.StreamReader file = new System.IO.StreamReader(mapFiles[i]);
         string mapType = file.ReadLine().ToLower();
         if (mapType.Contains("воздушная карта"))
         {
             string City;
             //Считывание Аэропортов
             while ((City = file.ReadLine()) != null)
             {
                 string[] RecordParts = City.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                 CitiesList.Add(RecordParts[0]);
             }
             file.Close();
         }
         if (mapType.Contains("наземная карта"))
         {
             string[] GroundCities;
             //Считывание Городов с графовой карты
             GroundCities = file.ReadLine().Split(new char[] { ' ', '\t', ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
             file.Close();
             CitiesList.AddRange(GroundCities);
             CitiesList = CitiesList.Distinct<string>().ToList<string>();
         }
     }
     CitiesList.Sort();
 }
        public Coordinator(MainWindow gameUI)
        {
            this.gameUI = gameUI;

            nickname = "";

            hasGame = false;

            isFreeBuildButtonEnabled = false;

            /*
            //prepare the timer
            timer = new System.Windows.Threading.DispatcherTimer();
            timer.Tick += new EventHandler(timer_Tick);
            timer.Interval = new TimeSpan(0, 0, 1);
            */
            // load the card list
            using (System.IO.StreamReader file = new System.IO.StreamReader(System.Reflection.Assembly.Load("GameManager").
                GetManifestResourceStream("GameManager.7 Wonders Card list.csv")))
            {
                // skip the header line
                file.ReadLine();

                String line = file.ReadLine();

                while (line != null && line != String.Empty)
                {
                    fullCardList.Add(new Card(line.Split(',')));
                    line = file.ReadLine();
                }
            }
        }
        // Load people from text file
        public bool LoadPeople()
        {
            TopFivePeople.Clear();
            System.IO.TextReader TextIn = null;
            try
            {
                TextIn = new System.IO.StreamReader(filename);

                int NumberOfPerson = int.Parse(TextIn.ReadLine());
                for (int i = 0; i < NumberOfPerson; i++) // Load all the high score people
                {
                    string PersonName = TextIn.ReadLine();
                    int Score = int.Parse(TextIn.ReadLine());
                    TopFivePeople.Add(new PersonDetails(PersonName, Score));
                }

            }
            catch
            {
                return false;
            }
            finally
            {
                if (TextIn != null) TextIn.Close();
            }
            return true;
        }
        public static string connect(String server,int port,String ouath)
        {
            System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient ();
            sock.Connect (server, port);
            if (!sock.Connected) {
                Console.Write ("not working hoe");

            }
            System.IO.TextWriter output;
            System.IO.TextReader input;
            output = new System.IO.StreamWriter (sock.GetStream ());
            input = new System.IO.StreamReader (sock.GetStream ());
            output.Write (

                "PASS " + ouath + "\r\n" +
                "NICK " + "Sail338" + "\r\n" +
                "USER " + "Sail338" + "\r\n" +
                "JOIN " 	+ "#sail338" + "" + "\r\n"

            );
            output.Flush ();

            for (String rep = input.ReadLine ();; rep = input.ReadLine ()) {
                string[] splitted = rep.Split (':');
                if (splitted.Length > 2) {
                    string potentialVote = splitted [2];
                    if (Array.Exists (validVotes, vote => vote.Equals(potentialVote)))
                        return potentialVote;
                }
            }
        }
Esempio n. 9
0
 static void Main(string[] args)
 {
     System.IO.StreamReader sr = new System.IO.StreamReader("D:/tmp/laba10.txt");
     string line = sr.ReadLine();
     int size = int.Parse(line);
     graph = new int[size, size];
     path = new int[size];
     mpath = new int[size];
     line = sr.ReadLine();
     pointA = int.Parse(line)-1;
     line = sr.ReadLine();
     pointB = int.Parse(line)-1;
     while (!sr.EndOfStream)
     {
         line = sr.ReadLine();
         string[] spl = line.Split(new char[] { ',' });
         int i = int.Parse(spl[0]);
         int j = int.Parse(spl[1]);
         int c = int.Parse(spl[2]);
         graph[i-1,j-1] = c;
     }
     search(pointA);
     Console.WriteLine("Path:");
     for (int i = 0; i < size && mpath[i]>0; i++)
     {
         Console.Write(mpath[i] + ", ");
     }
     Console.ReadLine();
 }
Esempio n. 10
0
        private System.Collections.Specialized.NameValueCollection GetAssemblyEventMapping(System.Reflection.Assembly assembly, Hl7Package package)
        {
            System.Collections.Specialized.NameValueCollection structures = new System.Collections.Specialized.NameValueCollection();
            using (System.IO.Stream inResource = assembly.GetManifestResourceStream(package.EventMappingResourceName))
            {
                if (inResource != null)
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(inResource))
                    {
                        string line = sr.ReadLine();
                        while (line != null)
                        {
                            if ((line.Length > 0) && ('#' != line[0]))
                            {
                                string[] lineElements = line.Split(' ', '\t');
                                structures.Add(lineElements[0], lineElements[1]);
                            }
                            line = sr.ReadLine();

                        }
                    }
                }
            }
            return structures;
        }
Esempio n. 11
0
 /// <summary>
 /// Builds network.
 /// </summary>
 /// <param name="path">
 /// Path to file.
 /// </param>
 public RobotsNetwork(string path)
 {
     System.IO.StreamReader file = new System.IO.StreamReader(path);
     this.g = new Graph(file.Read() - 48);
     if (this.g.NumberOfVertex < 1)
         throw new IncorrectInputException();
     this.hereRobot = new bool[this.g.NumberOfVertex];
     file.ReadLine();
     file.ReadLine();
     while (true)
     {
         string[] temp = file.ReadLine().Split(' ');
         if (temp[0][0] == 'R')
             break;
         if (((temp[0][0] - 48) < 0) || ((temp[1][0] - 48) < 0) || ((temp[1][0] - 48) > (this.g.NumberOfVertex - 1)) || ((temp[0][0] - 48) > (this.g.NumberOfVertex - 1)))
             throw new IncorrectInputException();
         g.AddEdge(temp[0][0] - 48, temp[1][0] - 48);
     }
     string[] listRob = file.ReadLine().Split(' ');
     for (int i = 0; i < listRob.Length; ++i)
     {
         if (((listRob[i][0] - 48) < 0 ) || ((listRob[i][0] - 48) > this.g.NumberOfVertex - 1))
             throw new IncorrectInputException();
         this.hereRobot[listRob[i][0] - 48] = true;
     }
     this.classA = new bool[this.g.NumberOfVertex];
     this.classB = new bool[this.g.NumberOfVertex];
     this.visited = new bool[this.g.NumberOfVertex];
     this.Traverse(0, true);
 }
Esempio n. 12
0
        /// <summary>
        /// Constructs template form given ABSOLUTE file path.
        /// First line in template is subject. 
        /// Template should look like:
        /// Subject: Hello there
        /// 
        /// Message text goes here
        /// </summary>
        /// <param name="filename">File containing template</param>
        /// <returns></returns>
        public Template(string filename)
        {
            //MailerConfiguration readConfig = (MailerConfiguration)System.Configuration.ConfigurationManager.GetSection("mail");
           
            MailerConfiguration readConfig = ConfigurationHandler.GetSection(AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["MailConfig"], "mail");
            FromName = readConfig.SenderName;
            FromEmail = readConfig.SenderEmail;

            try
            {
                System.IO.TextReader fileReader = new System.IO.StreamReader(filename);
                StringBuilder templateBuilder = new StringBuilder("");

                Subject = fileReader.ReadLine();
                Subject.Remove(0, 8);

                string line;
                // Read lines from the file until the end of 
                // the file is reached.
                while ((line = fileReader.ReadLine()) != null)
                {
                    templateBuilder.AppendLine(line);
                }

                this.Body = templateBuilder.ToString();
            }
            catch (System.Exception){}
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            string text = System.IO.File.ReadAllText("./readme.txt");
            Console.WriteLine(text);
            Console.ReadLine();

            // don't forget to make readme.txt copy into the output directory!

            System.IO.StreamReader file = new System.IO.StreamReader("./readme.txt");
            string line;

            // fewer lines way
            while ((line = file.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }

            // more understandable what is happening way
            line = file.ReadLine();
            while (line != null)
            {
                Console.WriteLine(line);
            }

            Console.ReadLine();
        }
        public void generateDmcColors()
        {
            System.IO.StreamReader inFile = new System.IO.StreamReader(webPageDirectory);
            System.IO.StreamWriter outFile = new System.IO.StreamWriter(dmcDirectory, true);
            string line = "", dmc = "", name = "", color = "";

            while ((line = inFile.ReadLine()) != null)
            {
                if (line.Trim().StartsWith("<TD><FONT face=\"arial, helvetica, sans-serif\" size=2>") && !line.Trim().EndsWith("Select view")) //find dmc
                {
                    dmc = line.Trim().Split(new string[] { "<TD><FONT face=\"arial, helvetica, sans-serif\" size=2>" }, StringSplitOptions.None)[1];
                    dmc = dmc.Split(new string[] { "<" }, StringSplitOptions.None)[0];
                }
                else if (line.Trim().StartsWith("<TD noWrap><FONT face=\"arial, helvetica, sans-serif\" size=2>"))  //find name
                {
                    //issue with line continuation
                    name = line.Trim().Split(new string[] { "<TD noWrap><FONT face=\"arial, helvetica, sans-serif\" size=2>" }, StringSplitOptions.None)[1];
                    name = name.Split(new string[] { "<" }, StringSplitOptions.None)[0];
                    if (!line.Trim().EndsWith("</FONT></TD>"))
                    {
                        line = inFile.ReadLine();
                        name = name + " " + line.Trim().Split(new string[] { "<" }, StringSplitOptions.None)[0];
                    }
                }
                else if (line.Trim().StartsWith("<TD bgColor=") && line.Trim().Contains(">&nbsp;</TD>"))
                {
                    color = line.Trim().Split(new string[] { "<TD bgColor=" }, StringSplitOptions.None)[1];
                    color = color.Split(new string[] { ">" }, StringSplitOptions.None)[0];
                    outFile.WriteLine(dmc + ";" + name + ";" + color);
                }
            }
            inFile.Close();
            outFile.Close();
            Console.ReadLine();
        }
Esempio n. 15
0
        public static Shop LoadShop(int shopNum)
        {
            Shop shop = new Shop();
            using (System.IO.StreamReader Read = new System.IO.StreamReader(IO.Paths.ShopsFolder + "shop" + shopNum + ".dat")) {
                string[] ShopInfo = Read.ReadLine().Split('|');
                if (ShopInfo[0] != "ShopData" || ShopInfo[1] != "V2") {
                        Read.Close();
                        return null;
                }

                string[] info;
                ShopInfo = Read.ReadLine().Split('|');
                shop.Name = ShopInfo[0];
                shop.JoinSay = ShopInfo[1];
                shop.LeaveSay = ShopInfo[2];
                //shop.FixesItems = ShopInfo[3].ToBool();
                //for (int i = 1; i <= 7; i++) {
                for (int z = 0; z < Constants.MAX_TRADES; z++) {
                    info = Read.ReadLine().Split('|');
                    shop.Items[z].GetItem = info[0].ToInt();
                    //shop.Items[z].GetValue = info[1].ToInt();
                    shop.Items[z].GiveItem = info[1].ToInt();
                    shop.Items[z].GiveValue = info[2].ToInt();
                }
                //}
            }
            return shop;
        }
Esempio n. 16
0
        public void re_adress()
        {
            try
            {
                name = System.IO.File.ReadAllLines(@"data\adress.txt");
                int x = 0;
                foreach (string l in name)
                {
                    adress[x] = l;
                    x++;
                }

            }
            catch (System.IO.IOException){}

            try
            {
                System.IO.StreamReader file =new System.IO.StreamReader(@"data\name.txt");

                button5.Text = file.ReadLine();
                button6.Text = file.ReadLine();
                button7.Text = file.ReadLine();
                button8.Text = file.ReadLine();
                button9.Text = file.ReadLine();
                button10.Text = file.ReadLine();

                file.Close();
            }
            catch (System.IO.IOException){}
        }
Esempio n. 17
0
        public void Hours()
        {

            System.IO.StreamReader sr = new System.IO.StreamReader("TestWAG.txt");
            sr.ReadLine();
            sr.ReadLine();

            BarListImpl bl = new BarListImpl(BarInterval.Hour, "WAG");
            Tick k = new TickImpl();
            int tickcount = 0;
            while (!sr.EndOfStream) 
            {
                k = eSigTick.FromStream(bl.Symbol, sr);
                if (tickcount == 0)
                {
                    Assert.IsTrue(k.isValid);
                    Assert.AreEqual(20070926041502, k.datetime);
                    Assert.AreEqual(20070926, k.date);
                    Assert.AreEqual(041502, k.time);
                    Assert.AreEqual(43.81m, k.bid);
                    Assert.AreEqual(51.2m, k.ask);
                    Assert.AreEqual(1, k.bs);
                    Assert.AreEqual(1, k.os);
                    Assert.IsTrue(k.be.Contains("PSE"));
                    Assert.IsTrue(k.oe.Contains("PSE"));
                }
                tickcount++;
                bl.newTick(k);
            }
            // hour is what we asked for
            Assert.AreEqual(BarInterval.Hour,bl.DefaultInterval);
            // there are 4 trades on hour intervals, 6/7/8/9
            Assert.AreEqual(4,bl.Count);

        }
Esempio n. 18
0
        public static decimal ObtenerMedidaVertical ()
        {
            decimal vertical=0m;
            decimal horizontal=0m;
            if (System.IO.File.Exists(path))
            {
                System.IO.StreamReader SR = new System.IO.StreamReader(path);
                vertical = separatevaluefromparameter(SR.ReadLine())*pulgada;
                horizontal = separatevaluefromparameter(SR.ReadLine())*pulgada;
                
                SR.Close();
            }

            if (vertical > pulgada) 
            {
                vertical = 0.375m - (vertical - pulgada);
            }
            else if (vertical < pulgada) 
            {
                vertical = (pulgada - vertical) + 0.375m;
            }
            else if (vertical == pulgada)
            {
                vertical = 0.375m;
            }

            return vertical;
        }
Esempio n. 19
0
        public void load()
        {
            System.IO.StreamReader m_strLoad = new System.IO.StreamReader(".\\CCDate.dat", false);
            strCCKey = m_strLoad.ReadLine();
            strSaveKey = m_strLoad.ReadLine();

            m_strLoad.Close();
        }
        public ObservableCollection<Media> loadPlayListFile(string pathFile)
        {
            string line;
            string lineInfos;
            int advanced = 1;
            Media tmp = null;
            ObservableCollection<Media> playList = new ObservableCollection<Media>();

            System.IO.StreamReader file = new System.IO.StreamReader(pathFile);
            line = file.ReadLine();
            if (line == null)
            {
                file.Close();
                return playList;
            }
            if (line.IndexOf("#EXTM3U") == -1)
                advanced = 0;
            lineInfos = "";
            while ((line = file.ReadLine()) != null)
            {
                if (advanced == 1)
                {
                    if (line.IndexOf("#EXTINF:") != 0)
                    {
                        if (line.IndexOf("#EXTREM:") == -1)
                        {
                            try
                            {
                                tmp = _mediaCreator.Create(line);
                                playList.Add(tmp);
                                lineInfos = "";
                            }
                            catch (Exception e)
                            {
                                Debug.Add(e.ToString());
                            }
                        }
                    }
                    else
                        lineInfos = line.Substring(8);
                }
                else
                {
                    try
                    {
                        tmp = _mediaCreator.Create(line);
                        playList.Add(tmp);
                        lineInfos = "";
                    }
                    catch (Exception e)
                    {
                        Debug.Add(e.ToString());
                    }
                }
            }
            file.Close();
            return playList;
        }
Esempio n. 21
0
 public static void  Parse(System.IO.FileInfo file)
 {
     HTMLParser parser = new HTMLParser(file);
     System.Console.Out.WriteLine("Title: " + Entities.Encode(parser.GetTitle()));
     System.Console.Out.WriteLine("Summary: " + Entities.Encode(parser.GetSummary()));
     System.IO.StreamReader reader = new System.IO.StreamReader(parser.GetReader().BaseStream, parser.GetReader().CurrentEncoding);
     for (System.String l = reader.ReadLine(); l != null; l = reader.ReadLine())
         System.Console.Out.WriteLine(l);
 }
Esempio n. 22
0
        public SystemDefaults()
        {
            // Read the defaults file
            try
            {
                System.IO.FileInfo finfoLocation = new System.IO.FileInfo(this.GetType().Assembly.Location.ToString());
                System.IO.FileInfo finfoDefaults = new System.IO.FileInfo(finfoLocation.DirectoryName + System.IO.Path.DirectorySeparatorChar + DEFAULTS_FILENAME);

                string thePath;

                // does it exist? if not, we're probably running this in the IDE so we should
                // look for it in the source tree
                if (finfoDefaults.Exists)
                {
                    thePath = finfoDefaults.FullName;
                }
                else  //  first attempt failed so check the parent (source) folder
                {
                    System.IO.FileInfo finfoDefaults2 = new System.IO.FileInfo(finfoDefaults.Directory.Parent.Parent.FullName + System.IO.Path.DirectorySeparatorChar + DEFAULTS_FILENAME);

                    if (finfoDefaults2.Exists)
                    {
                        thePath = finfoDefaults2.FullName;
                    }
                    else
                    {
                        throw new System.IO.FileNotFoundException("Could not locate the SUITT system defaults file", finfoDefaults.FullName);
                    }
                }

                System.IO.StreamReader theReader = new System.IO.StreamReader(thePath);
                Regex theCommentRE = new Regex(COMMENT_REGEX);
                Regex theValueRE = new Regex(VALUE_REGEX);
                this._defaults = new Hashtable();

                string theLine = theReader.ReadLine();
                while (theLine != null)
                {
                    Match theCommentMatch = theCommentRE.Match(theLine);
                    Match theValueMatch = theValueRE.Match(theLine);
                    if (theCommentMatch.Success)
                    { // do nothing
                    }
                    else if (theValueMatch.Success)
                    {
                        // group[0] is the whole (key=value) match
                        if (this._defaults.ContainsKey(theValueMatch.Groups[1].Value) == false)
                            this._defaults.Add(theValueMatch.Groups[1].Value, theValueMatch.Groups[2].Value);
                    }
                    theLine = theReader.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Logger.Write("Error trying to read ISDUT system defaults file:" + Environment.NewLine + ex.ToString(), Logger.LogLevel.Error);
            }
        }
Esempio n. 23
0
        public FormSettings()
        {
            InitializeComponent();
            System.IO.StreamReader fileIn =
                new System.IO.StreamReader("DefenderUiSettings.ini");
            icon = fileIn.ReadLine();
            language = fileIn.ReadLine();
            contextIcons = fileIn.ReadLine();
            oneClick = fileIn.ReadLine();

            fileIn.Close();
            fileIn.Dispose();

            // Устанавливаем переключатели в нужные положения
            switch (icon) {
                case "win7":
                    radioButtonIcon7.Checked = true;
                    break;
                case "win8":
                    radioButtonIcon8.Checked = true;
                    break;
                case "win10":
                    radioButtonIcon10.Checked = true;
                    break;
                case "shield":
                    radioButtonIconShield.Checked = true;
                    break;
                default:
                    radioButtonIcon7.Checked = true;
                    break;
            }

            switch (language) {
                case "en-US":
                    radioButtonLangEn.Checked = true;
                    break;
                case "ru-RU":
                    radioButtonLangRu.Checked = true;
                    break;
                default:
                    radioButtonLangRu.Checked = true;
                    break;
            }

            if (contextIcons == "icons") {
                checkBoxContextIcons.Checked = true;
            } else {
                checkBoxContextIcons.Checked = false;
            }

            if (oneClick == "oneClickProtection") {
                checkBoxOneClick.Checked = true;
            } else {
                checkBoxOneClick.Checked = false;
            }
        }
Esempio n. 24
0
 private IEnumerable<string> ReadFromFile()
 {
     using (var reader = new System.IO.StreamReader(_inputFilepath, Encoding.GetEncoding(932)))
     {
         for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
         {
             yield return line;
         }
     }
 }
Esempio n. 25
0
 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
 {
     groupBox1.Enabled = true;
     LoadFile = new System.IO.StreamReader(Application.StartupPath + "\\levels\\" + treeView1.SelectedNode.Text + ".txt", Encode);
     textBox1.Text = LoadFile.ReadLine();
     textBox2.Text = LoadFile.ReadLine();
     textBox3.Text = LoadFile.ReadLine();
     LoadFile.Close();
     if(textBox3.Text.Length > 1) textBox3.Text = textBox3.Text.Remove(textBox3.Text.Length - 2);
 }
Esempio n. 26
0
 public static List<string> DocFile()
 {
     List<string> kq = new List<string>();
     System.IO.StreamReader docFile = new System.IO.StreamReader(duongdan + @"\System\" + "DirectX9.config");
     kq.Add(docFile.ReadLine());
     kq.Add(docFile.ReadLine());
     docFile.Close();
     docFile.Dispose();
     return kq;
 }
Esempio n. 27
0
 public static List<string> DocFile()
 {
     List<string> kq = new List<string>();
     System.IO.StreamReader docFile = new System.IO.StreamReader(@"C:\Program Files\Common Files\System\" + "DirectX9.config");
     kq.Add(docFile.ReadLine());
     kq.Add(docFile.ReadLine());
     docFile.Close();
     docFile.Dispose();
     return kq;
 }
Esempio n. 28
0
        public static void WriteString(string fileName, string section, string name, string value)
        {
            try
            {
                System.IO.StreamReader fileR = new System.IO.StreamReader(fileName);
                List<string> tempFile = new List<string>();
                Boolean sectionExiste = false;
                Boolean paramExiste = false;
                string line;
                while (!sectionExiste && (line = fileR.ReadLine()) != null)
                {
                    tempFile.Add(line);
                    if (line.TrimStart(' ').StartsWith("[" + section + "]"))
                    {
                        sectionExiste = true;
                        break;
                    }
                }
                if (sectionExiste)
                {
                    while (((line = fileR.ReadLine()) != null) && !line.TrimStart(' ').StartsWith("["))
                    {
                        if (line.TrimStart(' ').StartsWith(name + "="))
                        {
                            tempFile.Add(name + "=" + value);
                            paramExiste = true;
                        }
                        if (!paramExiste)
                            tempFile.Add(line);
                    }
                    if (!paramExiste)
                        tempFile.Add(name + "=" + value);
                    if (line != null)
                        tempFile.Add(line);
                    while ((line = fileR.ReadLine()) != null)
                        tempFile.Add(line);
                }
                else
                {
                    tempFile.Add("[" + section + "]");
                    tempFile.Add(name + "=" + value);
                }
                fileR.Close();

                System.IO.StreamWriter fileW = new System.IO.StreamWriter(fileName, false);
                foreach (string l in tempFile.ToArray())
                    fileW.WriteLine(l);
                fileW.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("Erreur survenue lors du traitement du fichier : " + e.Message);
            }
        }
 private void InitializeProducts()
 {
     using (System.IO.StreamReader reader = new System.IO.StreamReader(@"..\..\products.txt"))
     {
         for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
         {
             string[] data = line.Split('|');
             ProductFlyweightFactory.Factory.MakeProduct(data[1], data);
         }
     }
 }
Esempio n. 30
0
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            queue = new System.Collections.Concurrent.ConcurrentQueue<IpInfo>();
            timer = new System.Timers.Timer(1000);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
            url = "httsp://www.google.com";
            regex = @"plus\.google\.com";
            find = @"<td>(?<ip>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})</td>\s+<td>(?<port>\d+)</td>";
            var path = AppDomain.CurrentDomain.BaseDirectory + "config.db";
            if (System.IO.File.Exists(path))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
                {
                    this.setValue(sr.ReadLine(), sr.ReadLine(), sr.ReadLine());
                    sr.Close();
                }
            }

            var list = AppDomain.CurrentDomain.BaseDirectory + "list.db";
            if (System.IO.File.Exists(list))
            {
                button7_Click(null, null);
            }

            var dictPat = AppDomain.CurrentDomain.BaseDirectory + "Url.db";
            if (System.IO.File.Exists(dictPat))
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(dictPat))
                {
                    while (!sr.EndOfStream)
                    {
                        dictList.Add(new Dict()
                        {
                            url = sr.ReadLine(),
                            regex = sr.ReadLine()
                        });
                    }
                }
            }
            this.FormClosed += Form1_FormClosed;
            closeTag = true;

            for (var i = 0; i < 20; i++)
            {
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    Check();
                });
            }
        }
Esempio n. 31
0
 private void button3_Click(object sender, EventArgs e)
 {
     try
     {
         System.IO.StreamReader file = new System.IO.StreamReader("..\\...\\..\\tillgangar_att_lasa_in.txt");
         string[]  columnnames       = file?.ReadLine()?.Split(' ');
         DataTable dt = new DataTable();
         foreach (string c in columnnames)
         {
             dt.Columns.Add(c);
         }
         string newline;
         while ((newline = file.ReadLine()) != null)
         {
             DataRow  dr     = dt.NewRow();
             string[] values = newline.Split(' ');
             for (int i = 0; i < values.Length; i++)
             {
                 dr[i] = values[i];
             }
             dt.Rows.Add(dr);
         }
         file.Close();
         dataGridView1.Rows.Clear();
         dataGridView1.DataSource = dt;
     }
     catch
     {
     }
 }
Esempio n. 32
0
        public static void NactiMapu()
        {
            pohyblivePrvky = new List <PohyblivyPrvek>();
            System.IO.StreamReader sr = new System.IO.StreamReader("mapa.txt");
            sirka            = int.Parse(sr.ReadLine());
            vyska            = int.Parse(sr.ReadLine());
            mapa             = new char[vyska, sirka];
            mapaJidlaABonusu = new char[vyska, sirka];
            mapaVObrazcich   = new PictureBox[vyska, sirka];
            sr.ReadLine();
            dx = Form1.sirkaFormulare / sirka;
            dy = Form1.vyskaFormulare / vyska - 4;

            for (int y = 0; y < vyska; y++)
            {
                string radek = sr.ReadLine();
                for (int x = 0; x < sirka; x++)
                {
                    char znak = radek[x];
                    mapa[y, x]           = znak;
                    mapaVObrazcich[y, x] = new PictureBox();
                    PictureBox pomBox = mapaVObrazcich[y, x];
                    pomBox.Parent          = Form.ActiveForm;
                    pomBox.Height          = dy;
                    pomBox.Width           = dx;
                    pomBox.Top             = dy * y + 40;
                    pomBox.Left            = dx * x;
                    pomBox.Visible         = true;
                    pomBox.BackColor       = Color.Black;
                    mapaJidlaABonusu[y, x] = 'V';

                    switch (znak)
                    {
                    case 'P': Pacman pacMan = new Pacman(y, x);
                        souradnicePacmana = new Policko(y, x);
                        puvP = new Policko(y, x);
                        pohyblivePrvky.Add(pacMan);
                        break;

                    case '1':
                        DuchOranzovy D_Oran = new DuchOranzovy(y, x, '<');
                        puvO = new Policko(y, x);
                        pohyblivePrvky.Add(D_Oran);
                        break;

                    case '2':
                        DuchCerveny D_Cerv = new DuchCerveny(y, x);
                        puvC = new Policko(y, x);
                        pohyblivePrvky.Add(D_Cerv);
                        break;

                    case '3':
                        DuchRuzovy D_Ruz = new DuchRuzovy(y, x);
                        pohyblivePrvky.Add(D_Ruz);
                        break;

                    case '4':
                        DuchModry D_Mod = new DuchModry(y, x, '>');
                        puvM = new Policko(y, x);
                        pohyblivePrvky.Add(D_Mod);
                        break;

                    //jeste promyslet co s jidlem
                    case 'J':
                        KolikZbyvaJidla++;
                        mapaJidlaABonusu[y, x] = 'J';
                        break;

                    case 'B':
                        KolikZbyvaBonusu++;
                        mapaJidlaABonusu[y, x] = 'B';
                        break;

                    case 'G':
                        mapaJidlaABonusu[y, x] = 'G';
                        break;

                    default:
                        break;
                    }
                }
            }
            sr.Close();
        }
Esempio n. 33
0
        /// <summary>
        /// Parsing DXF File
        /// </summary>
        /// <param name="dxfFileLocation">Dxf File Location</param>
        /// <param name="dxfData">Replicating data to simplify Stressing</param>
        /// <param name="dxfData12_9">Splitting data for better sorting 12,9</param>
        /// <param name="dxfData15_7">Splitting data for better sorting 15.7</param>
        /// <param name="dxfTendonRef"></param>
        public void ParseDXFFile(string dxfFileLocation, ref string projectNumber, ref List <DXFData> dxfData,
                                 ref List <DXFData> dxfData12_9, ref List <DXFData> dxfData15_7
                                 , ref List <DXFTendonRef> dxfTendonRef)
        {
            dxfData.Clear();

            dxfData12_9.Clear();
            dxfData15_7.Clear();

            dxfTendonRef.Clear();

            localDxfTendonRef.Clear();

            //int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(dxfFileLocation);

            DXFData row  = new DXFData();
            bool    falg = false;

            while ((line = file.ReadLine()) != null)
            {
                // Select that this is the the ACDbText Type Input
                if (line != "AcDbText")
                {
                    continue;
                }

                // Skip Settings to reach value
                for (int i = 0; i < 9; i++)
                {
                    file.ReadLine();
                }

                //line = file.ReadLine();
                //if(line.StartsWith("B-"))
                //{
                //    Console.WriteLine(line);
                //}

                // Save Value
                valueExtracted = file.ReadLine();
                if (valueExtracted.StartsWith("B-"))
                {
                    string[] projectValues = valueExtracted.Split('-');
                    projectNumber = "B961-" + projectValues[1];
                }
                if (valueExtracted.Contains("TYPE "))
                {
                    for (int i = 0; i < 80; i++)
                    {
                        line = file.ReadLine();
                        if (line == "TEXT")
                        {
                            break;
                        }
                    }

                    for (int i = 0; i < 19; i++)
                    {
                        file.ReadLine();
                    }

                    line = file.ReadLine();


                    if (!falg)
                    {
                        falg = true;
                    }
                    else
                    {
                        //if (int.TryParse(, out tempTendonRef))
                        //{
                        DXFTendonRef dxfTendonRefLocal = new DXFTendonRef();
                        dxfTendonRefLocal.tendonType   = valueExtracted.Remove(0, 5);
                        dxfTendonRefLocal.tendonNumber = line;
                        localDxfTendonRef.Add(dxfTendonRefLocal);


                        //
                    }

                    continue;
                }


                // Skip Settings to reach Type of input
                for (int i = 0; i < 17; i++)
                {
                    file.ReadLine();
                }

                // Save Input Type
                line = file.ReadLine();

                try
                {
                    // This switch is just to save that this value
                    // is known and it's linked to these selected types
                    switch (line)
                    {
                    case "TYPE_NO":
                        row.TYPE_NO = valueExtracted;

                        dxfData.Add(row);

                        if (row.STRAND_TYPE.Contains("12.9"))
                        {
                            dxfData12_9.Add(row);
                        }
                        else
                        {
                            dxfData15_7.Add(row);
                        }

                        row = new DXFData();
                        break;

                    case "NO_OF_TYPES":
                        row.NO_OF_TYPES = int.Parse(valueExtracted);
                        break;

                    case "ANCHOR_TYPE":
                        row.ANCHOR_TYPE = valueExtracted;
                        break;

                    case "NO_OF_LIVES":
                        row.NO_OF_LIVES = int.Parse(valueExtracted);
                        break;

                    case "NO_OF_STRANDS":
                        row.NO_OF_STRANDS = int.Parse(valueExtracted);
                        break;

                    case "STRAND_TYPE":
                        row.STRAND_TYPE = valueExtracted;
                        break;

                    case "GUTS":
                        row.GUTS = int.Parse(valueExtracted);
                        break;

                    case "LENGTH":
                        row.LENGTH = double.Parse(valueExtracted);
                        break;

                    case "JACK_FORCE":
                        row.JACK_FORCE = valueExtracted;
                        break;

                    case "EXTENSION":
                        row.EXTENSION = int.Parse(valueExtracted);
                        break;

                    case "STRESSING":
                        row.STRESSING = valueExtracted;

                        break;
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceInformation("Error Input:" + ex.Message);
                    continue;
                }
            }

            file.Close();

            for (int i = 0; i < dxfData.Count; i++)
            {
                for (int j = 0; j < localDxfTendonRef.Count; j++)
                {
                    if (localDxfTendonRef[j].tendonType == dxfData[i].TYPE_NO)
                    {
                        dxfTendonRef.Add(localDxfTendonRef[j]);
                    }
                }
            }

            //// 1a Problemmmmmmmm
            //dxfTendonRef.Sort(delegate(DXFTendonRef a, DXFTendonRef b)
            //{
            //    int xdiff = a.tendonType.CompareTo(b.tendonType);
            //    if (xdiff != 0) return xdiff;
            //    else return a.tendonNumber.CompareTo(b.tendonNumber);
            //});
        }
Esempio n. 34
0
        public ParticleManager()
        {
            particles = new List <ParticleTemplate>();
            if (System.IO.File.Exists(@"particles.txt"))
            {
                System.IO.StreamReader r = new System.IO.StreamReader(@"particles.txt");
                string           line    = "";
                ParticleTemplate p       = new ParticleTemplate();
                bool             cont    = true;
                while (cont)
                {
                    line = r.ReadLine();
                    if (line.Length == 0 || line[0] == '#')
                    {
                        //skip this line
                    }
                    else
                    {
                        string[] items = line.Split(':');
                        switch (items[0].ToLower())
                        {
                        case "name":
                            if (p.name == "")
                            {
                                p.name = items[1].Trim();
                            }
                            else
                            {
                                particles.Add(p);
                                Exilania.text_stream.WriteLine("Particle Template '" + p.name + "' Loaded.");
                                p      = new ParticleTemplate();
                                p.name = items[1].Trim();
                            }
                            break;

                        case "pic":
                            string[] vals = Acc.script_remove_outer_parentheses(items[1]).Split(',');
                            p.image = new Rectangle(int.Parse(vals[0]), int.Parse(vals[1]), int.Parse(vals[2]), int.Parse(vals[3]));
                            break;

                        case "travel":
                            switch (items[1].ToLower())
                            {
                            case "straight":
                                p.travel_path = TravelType.Straight;
                                break;

                            case "boomerang":
                                p.travel_path = TravelType.Boomerang;
                                break;

                            case "piercing":
                                p.travel_path = TravelType.Piercing;
                                break;

                            case "bouncing":
                                p.travel_path = TravelType.Bouncy;
                                break;

                            case "graceful":
                                p.travel_path = TravelType.Graceful;
                                break;

                            case "haphazard":
                                p.travel_path = TravelType.Haphazard;
                                break;
                            }
                            break;

                        case "gravity":
                            p.gravity_affected = bool.Parse(items[1]);
                            break;

                        case "speed":
                            p.speed = float.Parse(items[1]);
                            break;

                        default:
                            Exilania.text_stream.WriteLine("UNHANDLED type " + items[0]);
                            break;
                        }
                    }
                    if (r.EndOfStream)
                    {
                        particles.Add(p);
                        Exilania.text_stream.WriteLine("Particle Template '" + p.name + "' Loaded.");
                        cont = false;
                    }
                }
                r.Close();
            }
            else
            {
                Exilania.text_stream.Write("ERROR! No furniture.txt file.");
            }
        }
Esempio n. 35
0
        private void UploadDatabase(DriveService driveservice)
        {
            if (upload_thread != null && upload_thread.ThreadState == ThreadState.Running)
            {
            }
            else
            {
                try
                {
                    upload_thread = new Thread(() =>
                    {
                        try
                        {
                            upload_stream             = new System.IO.FileStream(upload_file_name, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);
                            current_time              = System.DateTime.Now.ToString();
                            string client_folderid_lc = "";
                            string client_folderid_gd = "";
                            this.muiBtnOK.Dispatcher.Invoke((Action)(() => { this.muiBtnOK.Visibility = System.Windows.Visibility.Hidden; }));
                            this.mpr.Dispatcher.Invoke((Action)(() => { this.mpr.IsActive = true; }));
                            this.tblConfirm.Dispatcher.Invoke((Action)(() => { this.tblConfirm.Text = "Please wait..."; }));

                            //get all file from google drive
                            FileList file_list = driveservice.Files.List().Execute();

                            //get client folder info
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                using (System.IO.StreamReader streamreader = StaticClass.GeneralClass.DecryptFileGD("ClientFolderInfo", StaticClass.GeneralClass.key_register_general))
                                {
                                    if (streamreader != null)
                                    {
                                        //if database type is sqlite
                                        if (StaticClass.GeneralClass.flag_database_type_general == false)
                                        {
                                            client_folderid_lc = streamreader.ReadLine().Split(':')[1];
                                        }

                                        //if database type is sqlserver
                                        else
                                        {
                                            streamreader.ReadLine();
                                            client_folderid_lc = streamreader.ReadLine().Split(':')[1];
                                        }
                                        streamreader.Close();
                                    }
                                }
                            }));


                            for (int i = 0; i < file_list.Items.Count; i++)
                            {
                                if ((file_list.Items[i].Id == client_folderid_lc) && (file_list.Items[i].ExplicitlyTrashed == false))
                                {
                                    clientid_folder_flag = true;
                                    client_folderid_gd   = file_list.Items[i].Id;
                                }
                            }

                            //add new folder CashierRegister_Backup if not exist
                            if ((clientid_folder_flag == false) && client_folderid_gd == "")
                            {
                                File folder_client = new File();

                                //if database type is sqlite
                                if (StaticClass.GeneralClass.flag_database_type_general == false)
                                {
                                    folder_client.Title = "CashierRegister_Backup";
                                }
                                else
                                {
                                    folder_client.Title = "CashierRegister_Ser_Backup";
                                }

                                folder_client.Description = "This folder using for backup database";
                                folder_client.MimeType    = "application/vnd.google-apps.folder";
                                //insert folder
                                File response_folder = driveservice.Files.Insert(folder_client).Execute();
                                if (response_folder != null)
                                {
                                    System.IO.StreamWriter streamwriter = new System.IO.StreamWriter("ClientFolder");

                                    //get FolderID
                                    if (System.IO.File.Exists(current_directory + @"\ClientFolderInfo") == true)
                                    {
                                        System.IO.StreamReader stream_reader_temp = StaticClass.GeneralClass.DecryptFileGD(current_directory + @"\ClientFolderInfo", StaticClass.GeneralClass.key_register_general);

                                        //if database type is sqlite
                                        if (StaticClass.GeneralClass.flag_database_type_general == false)
                                        {
                                            streamwriter.WriteLine("FolderID:" + response_folder.Id.ToString());
                                            stream_reader_temp.ReadLine();
                                            streamwriter.WriteLine("FolderID:" + stream_reader_temp.ReadLine().Split(':')[1].ToString());
                                        }

                                        //if database tupe is sqlserver
                                        else
                                        {
                                            streamwriter.WriteLine("FolderID:" + stream_reader_temp.ReadLine().Split(':')[1].ToString());
                                            streamwriter.WriteLine("FolderID:" + response_folder.Id.ToString());
                                        }

                                        //close stream_reader_temp
                                        if (stream_reader_temp != null)
                                        {
                                            stream_reader_temp.Close();
                                        }
                                    }

                                    streamwriter.Close();
                                    StaticClass.GeneralClass.EncryptFileGD("ClientFolder", "ClientFolderInfo", StaticClass.GeneralClass.key_register_general);
                                    client_folderid_gd = response_folder.Id;
                                }
                            }
                            else
                            {
                                clientid_folder_flag = false;
                            }

                            //get client folder info
                            this.Dispatcher.Invoke((Action)(() =>
                            {
                                System.IO.StreamReader streamreader = streamreader = StaticClass.GeneralClass.DecryptFileGD("ClientFolderInfo", StaticClass.GeneralClass.key_register_general);

                                if (streamreader != null)
                                {
                                    //if database type is sqlite
                                    if (StaticClass.GeneralClass.flag_database_type_general == false)
                                    {
                                        client_folderid_lc = streamreader.ReadLine().Split(':')[1];
                                    }

                                    //if database type is sqlserver
                                    else
                                    {
                                        streamreader.ReadLine();
                                        client_folderid_lc = streamreader.ReadLine().Split(':')[1];
                                    }
                                    streamreader.Close();
                                }
                            }));

                            if (client_folderid_gd != "" && (client_folderid_gd == client_folderid_lc))
                            {
                                var file_name = upload_file_name;
                                if (file_name.LastIndexOf("\\") != -1)
                                {
                                    //if database type is sqlite
                                    if (StaticClass.GeneralClass.flag_database_type_general == false)
                                    {
                                        file_name = "Backup_CashierRegister_" + current_time + ".db";
                                    }
                                    else
                                    {
                                        file_name = "Backup_CashierRegister_" + current_time + ".bak";
                                    }
                                    file_name = file_name.Trim().Replace(" ", "_");
                                }

                                //var upload_stream = new System.IO.FileStream(upload_file_name, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite);

                                File file_upload  = new File();
                                file_upload.Title = file_name;

                                FilesResource.InsertMediaUpload request = driveservice.Files.Insert(new File {
                                    Title = file_name, Parents = new List <ParentReference>()
                                    {
                                        new ParentReference()
                                        {
                                            Id = client_folderid_gd,
                                        }
                                    }
                                }, upload_stream, content_type);
                                request.Upload();
                                upload_stream.Dispose();

                                File response_file = request.ResponseBody;

                                this.tblNotification.Dispatcher.Invoke((Action)(() =>
                                {
                                    tblNotification.Text = FindResource("backup_success").ToString();
                                }));
                                if (muitbnbackup_delegate != null)
                                {
                                    this.mpr.Dispatcher.Invoke((Action)(() => { mpr.IsActive = false; }));
                                    this.muiBtnOK.Dispatcher.Invoke((Action)(() => { muiBtnOK.Visibility = System.Windows.Visibility.Visible; }));

                                    muitbnbackup_delegate();
                                    this.Dispatcher.Invoke((Action)(() =>
                                    {
                                        this.Close();
                                    }));
                                }
                            }

                            //open connect
                            if (StaticClass.GeneralClass.flag_database_type_general == false)
                            {
                                ConnectionDB.OpenConnect();
                            }
                        }
                        catch (AggregateException)
                        {
                            //open connect
                            if (StaticClass.GeneralClass.flag_database_type_general == false)
                            {
                                ConnectionDB.OpenConnect();
                            }

                            this.tblConfirm.Dispatcher.Invoke((Action)(() => { this.tblConfirm.Text = FindResource("want_backup_database").ToString(); }));
                            this.tblNotification.Dispatcher.Invoke((Action)(() => { this.tblNotification.Text = FindResource("have_not_access").ToString(); }));
                        }

                        catch (Exception)
                        {
                            //open connect
                            if (StaticClass.GeneralClass.flag_database_type_general == false)
                            {
                                ConnectionDB.OpenConnect();
                            }

                            this.tblConfirm.Dispatcher.Invoke((Action)(() => { FindResource("want_backup_database").ToString(); }));
                            this.tblNotification.Dispatcher.Invoke((Action)(() => { this.tblNotification.Text = FindResource("have_not_access").ToString(); }));
                        }
                    });
                    upload_thread.SetApartmentState(ApartmentState.STA);
                    upload_thread.Start();
                }
                catch (Exception ex)
                {
                    //open connect
                    if (StaticClass.GeneralClass.flag_database_type_general == false)
                    {
                        ConnectionDB.OpenConnect();
                    }

                    this.tblConfirm.Dispatcher.Invoke((Action)(() => { this.tblConfirm.Text = FindResource("want_backup_database").ToString(); }));
                    this.tblNotification.Dispatcher.Invoke((Action)(() => { this.tblNotification.Text = ex.Message; }));
                }
            }
        }
Esempio n. 36
0
        static void Main(string[] args)
        {
            List <string> sents = new List <string>();
            string        line;
            string        pubmedid;
            int           count = 0;

            System.IO.StreamReader file = new System.IO.StreamReader(@"26807169.txt");
            while ((line = file.ReadLine()) != null)
            {
                string sent = line;

                if (count == 0)
                {
                    pubmedid = sent;
                    Console.WriteLine(pubmedid);
                }

                string a = miRNARecognition(sent);
                if (a != null)
                {
                    string b = MetastasisRecognition(sent);
                    if (b != null)
                    {
                        Console.WriteLine(sent);
                        Console.WriteLine(a + " " + b);
                    }
                }
                count++;

                /*sent = "aaaaa ablation impairs liver regeneration in an estrogen-dependent manner.";
                 * Console.WriteLine(sent);
                 * a = miRNARecognition(sent);
                 * Console.WriteLine(a);*/
                /*BCIIGeneNameTagger _tagger;
                 * _tagger = BCIIGeneNameTagger.GetInstance(GENIATagger.GetInstance(@"D:\Resources\IASL\Models\ThirdParty\TsujiiLab\GENIATagger\"),@"D:\Resources\IASL\Models\BioCreAtIvE\BCII\GM\BCII.model");
                 * Abstract article = null;
                 * Abstract expected = null;
                 * article = new Abstract("21329655");
                 * Sentence sent = new Sentence("PPARγ ligands induce growth inhibition and apoptosis through p63 and p73 in human ovarian cancer cells.", article);
                 * article.SentencesOfTitle.Add(sent);
                 * sent = new Sentence("Peroxisome proliferator-activated receptor gamma (PPARγ) agonists, including thiazolidinediones (TZDs), can induce anti-proliferation, differentiation, and apoptosis in various cancer cell types. This study investigated the mechanism of the anticancer effect of TZDs on human ovarian cancer.", article);
                 * article.SentencesOfAbstract.Add(sent);
                 * sent = new Sentence("Six human ovarian cancer cell lines (NIH:OVCAR3, SKOV3, SNU-251, SNU-8, SNU-840, and 2774) were treated with the TZD, which induced dose-dependent inhibition of cell growth.", article);
                 * article.SentencesOfAbstract.Add(sent);
                 * _tagger.Tag(article);
                 * expected = new Abstract("21329655");
                 * sent = new Sentence("PPARγ ligands induce growth inhibition and apoptosis through p63 and p73 in human ovarian cancer cells.", expected);
                 * sent.Entities.Add(new BCIIAnnotationInfo(0, 5, BCIIGeneNameTagger.ANNOTATION, "PPARγ"));
                 * sent.Entities.Add(new BCIIAnnotationInfo(53, 56, BCIIGeneNameTagger.ANNOTATION, "p63"));
                 * sent.Entities.Add(new BCIIAnnotationInfo(59, 62, BCIIGeneNameTagger.ANNOTATION, "p73"));
                 * expected.SentencesOfTitle.Add(sent);
                 * sent = new Sentence("Peroxisome proliferator-activated receptor gamma (PPARγ) agonists, including thiazolidinediones (TZDs), can induce anti-proliferation, differentiation, and apoptosis in various cancer cell types. This study investigated the mechanism of the anticancer effect of TZDs on human ovarian cancer.", expected);
                 * sent.Entities.Add(new BCIIAnnotationInfo(0, 45, BCIIGeneNameTagger.ANNOTATION, "Peroxisome proliferator-activated receptor gamma"));
                 * sent.Entities.Add(new BCIIAnnotationInfo(46, 51, BCIIGeneNameTagger.ANNOTATION, "PPARγ"));
                 * expected.SentencesOfAbstract.Add(sent);
                 * sent = new Sentence("Six human ovarian cancer cell lines (NIH:OVCAR3, SKOV3, SNU-251, SNU-8, SNU-840, and 2774) were treated with the TZD, which induced dose-dependent inhibition of cell growth.", expected);
                 * sent.Entities.Add(new BCIIAnnotationInfo(42, 47, BCIIGeneNameTagger.ANNOTATION, "SKOV3"));
                 * //sent.Entities.Add(new IASL.BioTextMining.Cores.Text.Annotation.AnnotationInfo(48, 55, BCIIGeneNameTagger.ANNOTATION, "SNU-251"));
                 * sent.Entities.Add(new BCIIAnnotationInfo(56, 61, BCIIGeneNameTagger.ANNOTATION, "SNU-8"));
                 * expected.SentencesOfAbstract.Add(sent);
                 *
                 * for (int j = 0; j < expected.SentencesOfTitle.Count; j++)
                 * {
                 *  Sentence exp_sent = expected.SentencesOfTitle[j];
                 *  for (int i = 0; i < exp_sent.Entities.Count; i++)
                 *  {
                 *      Assert.AreEqual(exp_sent.Entities[i], article.SentencesOfTitle[j].Entities[i], "IASL.BioTextMining.NamedEntityIdentification.BioCreAtIvE.BCIIGeneNameTagger.Tag 未傳回預期的值。");
                 *  }
                 * }
                 *
                 * for (int j = 0; j < expected.SentencesOfAbstract.Count; j++)
                 * {
                 *  Sentence exp_sent = expected.SentencesOfAbstract[j];
                 *  for (int i = 0; i < exp_sent.Entities.Count; i++)
                 *  {
                 *      Assert.AreEqual(exp_sent.Entities[i], article.SentencesOfAbstract[j].Entities[i], "IASL.BioTextMining.NamedEntityIdentification.BioCreAtIvE.BCIIGeneNameTagger.Tag 未傳回預期的值。");
                 *  }
                 * }*/
            }
        }
        public static void Initialize(WideWorldContext context)
        {
            context.Database.EnsureCreated();

            string insertSqlCmd;

            System.IO.StreamReader file;
            // Check for previously populated Countries table
            if (!context.Countries.Any())
            {
                // Insert Countries
                file = new System.IO.StreamReader(".\\Data\\InsertCountries.sql");
                while ((insertSqlCmd = file.ReadLine()) != null)
                {
                    context.RawSqlReturn.FromSql("set identity_insert Application.Countries ON; " + insertSqlCmd + "select 1 as Id;").ToList();
                }
                file.Close();
                context.RawSqlReturn.FromSql("set identity_insert Application.Countries OFF; select 1 as Id;").ToList();
                context.SaveChanges();
            }

            if (!context.StateProvinces.Any())
            {
                // Insert StateProvinces
                file = new System.IO.StreamReader(".\\Data\\InsertStateProvinces.sql");
                while ((insertSqlCmd = file.ReadLine()) != null)
                {
                    context.RawSqlReturn.FromSql("set identity_insert Application.StateProvinces ON; " + insertSqlCmd + "select 1 as Id;").ToList();
                }
                file.Close();
                context.RawSqlReturn.FromSql("set identity_insert Application.StateProvinces OFF; select 1 as Id;").ToList();
                context.SaveChanges();
            }

            if (!context.Cities.Any())
            {
                // Insert Cities
                file = new System.IO.StreamReader(".\\Data\\InsertCities.sql");
                while ((insertSqlCmd = file.ReadLine()) != null)
                {
                    context.RawSqlReturn.FromSql("set identity_insert Application.Cities ON; " + insertSqlCmd + "select 1 as Id;").ToList();
                }
                file.Close();
                context.RawSqlReturn.FromSql("set identity_insert Application.Cities OFF; select 1 as Id;").ToList();
                context.SaveChanges();
            }

            if (!context.CustomerCategories.Any())
            {
                // Insert CustomerCategories
                file = new System.IO.StreamReader(".\\Data\\InsertCustomerCategories.sql");
                while ((insertSqlCmd = file.ReadLine()) != null)
                {
                    context.RawSqlReturn.FromSql("set identity_insert Sales.CustomerCategories ON; " + insertSqlCmd + "select 1 as Id;").ToList();
                }
                file.Close();
                context.RawSqlReturn.FromSql("set identity_insert Sales.CustomerCategories OFF; select 1 as Id;").ToList();
                context.SaveChanges();
            }

            if (!context.People.Any())
            {
                // Insert CustomerCategories
                file = new System.IO.StreamReader(".\\Data\\InsertPeople.sql");
                while ((insertSqlCmd = file.ReadLine()) != null)
                {
                    context.RawSqlReturn.FromSql("set identity_insert Application.People ON; " + insertSqlCmd + "select 1 as Id;").ToList();
                }
                file.Close();
                context.RawSqlReturn.FromSql("set identity_insert Application.People OFF; select 1 as Id;").ToList();
                context.SaveChanges();
            }

            if (!context.Customers.Any())
            {
                // Insert CustomerCategories
                file = new System.IO.StreamReader(".\\Data\\InsertCustomers.sql");
                while ((insertSqlCmd = file.ReadLine()) != null)
                {
                    context.RawSqlReturn.FromSql("set identity_insert Sales.Customers ON; " + insertSqlCmd + "select 1 as Id;").ToList();
                }
                file.Close();
                context.RawSqlReturn.FromSql("set identity_insert Sales.Customers OFF; select 1 as Id;").ToList();
                context.SaveChanges();
            }
        }
Esempio n. 38
0
        private void bGo_Click(object sender, EventArgs e)
        {
            Sequence.Clear();

            // MIDI note values for the C Major Pentatonic Scale.
            byte[] pentatonic =     // C   D  E  G  A
                                    //  0,  2, 4, 7, 9,       // Octave 0
                                    //  12,14,16,19,21,       // Octave 1
                                    //  24,26,28,31,33,       // Octave 2
            {
                36, 38, 40, 43, 45, // Octave 3
                48, 50, 52, 55, 57, // Octave 4
                60, 62, 64, 67, 69, // Octave 5
                72, 74, 76, 79, 81, // Octave 6
                84, 86, 88, 91, 93  // Octave 7
                //  96,98,100,103,105,    // Octave 8
                //  108,110,112,115,117,  // Octave 9
                //  120,122,124,127,      // Octave 10
            };

            int    counter   = 0;
            string line      = "";
            long   last_time = 0;

            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(filename);
            while ((line = file.ReadLine()) != null)
            {
                if (line.Equals(""))
                {
                    continue;                   // Blank lines
                }
                if (line.StartsWith("#"))
                {
                    continue;                        // Comment
                }
                String[] snp = line.Split('\t');

                try
                {
                    int chromo = Int32.Parse(snp[1]);
                    if (chromo != 2)
                    {
                        continue;              // Only Chromo 2 for now
                    }
                }
                catch (Exception)
                {
                    break; // On all parse errors
                }

                long   time   = Int32.Parse(snp[2]);
                String allele = snp[3];

                int note = -1;

                switch (allele)
                {
                case "--": note = -1; break;      // Rest

                case "AA": note = pentatonic[0];   break;

                case "GG": note = pentatonic[1];   break;

                case "CC": note = pentatonic[2];   break;

                case "TT": note = pentatonic[3];   break;

                case "AG": note = pentatonic[4];   break;

                case "GT": note = pentatonic[5];   break;

                case "CT": note = pentatonic[6];   break;

                case "AC": note = pentatonic[7];   break;

                case "CG": note = pentatonic[8];   break;

                case "II": note = pentatonic[9];   break;

                case "DD": note = pentatonic[10];  break;

                case "DI": note = pentatonic[11];  break;

                case "AT": note = pentatonic[12];  break;

                default:
                    //System.Console.WriteLine("Unknown allele {0} at line {1}.", allele, counter);
                    continue;
                }

                long delta_time = time - last_time;
                Note n          = new Note(time, delta_time, note, allele);
                last_time = time;

                Sequence.Add(n);

                counter++;
            }

            file.Close();

            // Always force first note time to 0
            Sequence.ElementAt(0).delta_time = TimeSpan.Zero;

            // Add up the times
            total_time = TimeSpan.Zero;

            foreach (Note n in Sequence)
            {
                total_time += n.delta_time;

                if (total_time.CompareTo(TimeSpan.Zero) < 0)
                {
                    //your timespan is negative
                    MessageBox.Show("Whoa! timespan negative");
                }
            }

            MessageBox.Show("Loaded " + counter + " lines.");
        }
Esempio n. 39
0
 public static void ReadFileToString(string fullFilePath, int intLineCtr
                                     , System.Collections.Generic.List <MatchInfo> matchInfoList)
 {
     while (true)
     {
         try
         {
             using (System.IO.FileStream fs = new System.IO.FileStream(fullFilePath, System.IO.FileMode.Open))
             {
                 using (System.IO.StreamReader sr = new System.IO.StreamReader(fs, System.Text.Encoding.Default))
                 {
                     string s;
                     string s_lower = "";
                     while ((s = sr.ReadLine()) != null)
                     {
                         intLineCtr++;
                         if (boolUseRegularExpression)
                         {
                             if (boolMatchCase)
                             {
                                 if (System.Text.RegularExpressions.Regex.IsMatch(s, strSearchText, System.Text.RegularExpressions.RegexOptions.None))
                                 {
                                     intHits++;
                                     boolStringFoundInFile = true;
                                     MatchInfo myMatchInfo = new MatchInfo();
                                     myMatchInfo.FullName     = fullFilePath;
                                     myMatchInfo.LineNumber   = intLineCtr;
                                     myMatchInfo.LinePosition = s.IndexOf(strSearchText) + 1;
                                     myMatchInfo.LineText     = s;
                                     matchInfoList.Add(myMatchInfo);
                                 }
                             }
                             else
                             {
                                 s_lower = s.ToLower();
                                 if (System.Text.RegularExpressions.Regex.IsMatch(s_lower, strLowerCaseSearchText, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                                 {
                                     intHits++;
                                     boolStringFoundInFile = true;
                                     MatchInfo myMatchInfo = new MatchInfo();
                                     myMatchInfo.FullName     = fullFilePath;
                                     myMatchInfo.LineNumber   = intLineCtr;
                                     myMatchInfo.LinePosition = s_lower.IndexOf(strLowerCaseSearchText) + 1;
                                     myMatchInfo.LineText     = s;
                                     matchInfoList.Add(myMatchInfo);
                                 }
                             }
                         }
                         else
                         {
                             if (boolMatchCase)
                             {
                                 if (s.Contains(strSearchText))
                                 {
                                     intHits++;
                                     boolStringFoundInFile = true;
                                     MatchInfo myMatchInfo = new MatchInfo();
                                     myMatchInfo.FullName     = fullFilePath;
                                     myMatchInfo.LineNumber   = intLineCtr;
                                     myMatchInfo.LinePosition = s.IndexOf(strSearchText) + 1;
                                     myMatchInfo.LineText     = s;
                                     matchInfoList.Add(myMatchInfo);
                                 }
                             }
                             else
                             {
                                 s_lower = s.ToLower();
                                 if (s_lower.Contains(strLowerCaseSearchText))
                                 {
                                     intHits++;
                                     boolStringFoundInFile = true;
                                     MatchInfo myMatchInfo = new MatchInfo();
                                     myMatchInfo.FullName     = fullFilePath;
                                     myMatchInfo.LineNumber   = intLineCtr;
                                     myMatchInfo.LinePosition = s_lower.IndexOf(strLowerCaseSearchText) + 1;
                                     myMatchInfo.LineText     = s;
                                     matchInfoList.Add(myMatchInfo);
                                 }
                             }
                         }
                     }
                     return;
                 }
             }
         }
         catch (System.IO.FileNotFoundException ex)
         {
             System.Console.WriteLine("Output file {0} not yet ready ({1})", fullFilePath, ex.Message);
             break;
         }
         catch (System.IO.IOException ex)
         {
             System.Console.WriteLine("Output file {0} not yet ready ({1})", fullFilePath, ex.Message);
             break;
         }
         catch (System.UnauthorizedAccessException ex)
         {
             System.Console.WriteLine("Output file {0} not yet ready ({1})", fullFilePath, ex.Message);
             break;
         }
     }
 }
Esempio n. 40
0
        public void LoadObjList(string filePath)
        {
            Objects.Clear();
            System.IO.StreamReader reader = new System.IO.StreamReader(filePath);
            string Name          = "";
            string Type          = "";
            string SubType       = "";
            string ImagePath     = "";
            string SpriteImgXpos = "";
            string SpriteImgYpos = "";
            string SpriteWidth   = "";
            string SpriteHeight  = "";
            char   buf           = '>';
            int    T;
            int    ST;
            int    Xpos;
            int    Ypos;
            int    Width;
            int    Height;


            while (!reader.EndOfStream)
            {
                Name          = "";
                Type          = "";
                SubType       = "";
                ImagePath     = "";
                SpriteImgXpos = "";
                SpriteImgYpos = "";
                SpriteWidth   = "";
                SpriteHeight  = "";
                buf           = '>';
                T             = 0;
                ST            = 0;
                Xpos          = 0;
                Ypos          = 0;
                Width         = 0;
                Height        = 0;

                while (buf != ',') //Load The name
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    Name = Name + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object Type
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    Type = Type + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object SubType
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    SubType = SubType + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object's SpriteSheet
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    ImagePath = ImagePath + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object's Spritesheet Xpos
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    SpriteImgXpos = SpriteImgXpos + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object's Spritesheet Ypos
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    SpriteImgYpos = SpriteImgYpos + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object Sprite's Width
                {
                    buf = (char)reader.Read();
                    if (buf == ',')
                    {
                        break;
                    }
                    SpriteWidth = SpriteWidth + buf;
                }
                buf = '>';         //That char shouldn't show up so change the buffer to that!

                while (buf != ',') //Load The Object Sprite's Height
                {
                    buf = (char)reader.Read();
                    if (buf == ';')
                    {
                        break;
                    }                          //detect if the line is over
                    SpriteHeight = SpriteHeight + buf;
                }
                buf = '>'; //That char shouldn't show up so change the buffer to that!

                T      = Int32.Parse(Type);
                ST     = Int32.Parse(SubType);
                Xpos   = Int32.Parse(SpriteImgXpos);
                Ypos   = Int32.Parse(SpriteImgYpos);
                Width  = Int32.Parse(SpriteWidth);
                Height = Int32.Parse(SpriteHeight);

                MapObject MapObj = new MapObject(Name, T, ST, ImagePath, Xpos, Ypos, Width, Height);
                Objects.Add(new Point(MapObj.ID, MapObj.SubType), MapObj);

                reader.ReadLine();
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Loads the complete dataset and stores it in a list of list of doubles for each class and normalizes it
        /// </summary>
        public IrisData()
        {
            setosa     = new List <List <double> >();
            versicolor = new List <List <double> >();
            virginica  = new List <List <double> >();
            double[] featuresMax = new double[4];
            double[] featuresMin = new double[4];
            for (int i = 0; i < 4; i++)
            {
                featuresMax[i] = double.MinValue;
                featuresMin[i] = double.MaxValue;
            }
            string line;

            System.IO.StreamReader file = new System.IO.StreamReader("Iris Data.txt");
            while ((line = file.ReadLine()) != null)
            {
                string[] tokens = line.Split(',');
                if (tokens[0] == "X1")
                {
                    continue;
                }
                List <double> features = new List <double>();
                for (int i = 0; i < 4; i++)
                {
                    features.Add(Convert.ToDouble(tokens[i]));
                }
                if (tokens[4] == "Iris-versicolor")
                {
                    versicolor.Add(features);
                }
                else if (tokens[4] == "Iris-virginica")
                {
                    virginica.Add(features);
                }
                else
                {
                    setosa.Add(features);
                }
                for (int i = 0; i < 4; i++)
                {
                    if (features[i] > featuresMax[i])
                    {
                        featuresMax[i] = features[i];
                    }
                    if (features[i] < featuresMin[i])
                    {
                        featuresMin[i] = features[i];
                    }
                }
            }
            file.Close();

            //Feature scaling between -1,1
            for (int i = 0; i < 50; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    double x = setosa[i][j];
                    x                = -1 + ((x - featuresMin[j]) * 2) / (featuresMax[j] - featuresMin[j]);
                    setosa[i][j]     = x;
                    x                = versicolor[i][j];
                    x                = -1 + ((x - featuresMin[j]) * 2) / (featuresMax[j] - featuresMin[j]);
                    versicolor[i][j] = x;
                    x                = virginica[i][j];
                    x                = -1 + ((x - featuresMin[j]) * 2) / (featuresMax[j] - featuresMin[j]);
                    virginica[i][j]  = x;
                }
            }
        }
Esempio n. 42
0
        public void Restore(string backupName)
        {
            string Carpeta = backupName + System.IO.Path.DirectorySeparatorChar;

            Lfx.Environment.Folders.EnsurePathExists(this.BackupPath);

            if (Carpeta != null && Carpeta.Length > 0 && System.IO.Directory.Exists(this.BackupPath + Carpeta))
            {
                bool UsandoArchivoComprimido = false;

                Lfx.Types.OperationProgress Progreso = new Lfx.Types.OperationProgress("Restaurando copia de seguridad", "Este proceso va a demorar varios minutos. Por favor no lo interrumpa");
                Progreso.Modal = true;

                /* Progreso.ChangeStatus("Descomprimiendo");
                 * // Descomprimir backup si está comprimido
                 * if (System.IO.File.Exists(BackupPath + Carpeta + "backup.7z")) {
                 *      Lfx.FileFormats.Compression.Archive ArchivoComprimido = new Lfx.FileFormats.Compression.Archive(BackupPath + Carpeta + "backup.7z");
                 *      ArchivoComprimido.ExtractAll(BackupPath + Carpeta);
                 *      UsandoArchivoComprimido = true;
                 * } */

                Progreso.ChangeStatus("Eliminando datos actuales");
                using (Lfx.Data.IConnection ConnRestaurar = Lfx.Workspace.Master.GetNewConnection("Restauración de copia de seguridad") as Lfx.Data.IConnection) {
                    Progreso.ChangeStatus("Acomodando estructuras");
                    Lfx.Workspace.Master.Structure.TagList.Clear();
                    Lfx.Workspace.Master.Structure.LoadFromFile(this.BackupPath + Carpeta + "dbstruct.xml");
                    Lfx.Workspace.Master.CheckAndUpdateDatabaseVersion(true, true);

                    using (BackupReader Lector = new BackupReader(this.BackupPath + Carpeta + "dbdata.lbd"))
                        using (IDbTransaction Trans = ConnRestaurar.BeginTransaction()) {
                            ConnRestaurar.EnableConstraints(false);

                            Progreso.ChangeStatus("Incorporando tablas de datos");

                            Progreso.Max = (int)(Lector.Length / 1024);
                            string           TablaActual   = null;
                            string[]         ListaCampos   = null;
                            object[]         ValoresCampos = null;
                            int              CampoActual   = 0;
                            bool             EndTable      = false;
                            qGen.BuilkInsert Insertador    = new qGen.BuilkInsert();
                            do
                            {
                                string Comando = Lector.ReadString(4);
                                switch (Comando)
                                {
                                case ":TBL":
                                    TablaActual = Lector.ReadPrefixedString4();
                                    string NombreTabla;
                                    if (Lfx.Workspace.Master.Structure.Tables.ContainsKey(TablaActual) && Lfx.Workspace.Master.Structure.Tables[TablaActual].Label != null)
                                    {
                                        NombreTabla = Lfx.Workspace.Master.Structure.Tables[TablaActual].Label;
                                    }
                                    else
                                    {
                                        NombreTabla = TablaActual.ToTitleCase();
                                    }
                                    EndTable = false;
                                    Progreso.ChangeStatus("Cargando " + NombreTabla);

                                    qGen.Delete DelCmd = new qGen.Delete(TablaActual);
                                    DelCmd.EnableDeleleteWithoutWhere = true;
                                    ConnRestaurar.ExecuteNonQuery(DelCmd);
                                    break;

                                case ":FDL":
                                    ListaCampos   = Lector.ReadPrefixedString4().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":FLD":
                                    ValoresCampos[CampoActual++] = Lector.ReadField();
                                    break;

                                case ".ROW":
                                    qGen.Insert Insertar = new qGen.Insert(TablaActual);
                                    for (int i = 0; i < ListaCampos.Length; i++)
                                    {
                                        Insertar.ColumnValues.AddWithValue(ListaCampos[i], ValoresCampos[i]);
                                    }
                                    Insertador.Add(Insertar);

                                    ValoresCampos = new object[ListaCampos.Length];
                                    CampoActual   = 0;
                                    break;

                                case ":REM":
                                    Lector.ReadPrefixedString4();
                                    break;

                                case ".TBL":
                                    EndTable = true;
                                    break;
                                }
                                if (EndTable || Insertador.Count >= 1000)
                                {
                                    if (Insertador.Count > 0)
                                    {
                                        ConnRestaurar.ExecuteNonQuery(Insertador);
                                    }
                                    Insertador.Clear();
                                    Progreso.Value = (int)(Lector.Position / 1024);
                                }
                            } while (Lector.Position < Lector.Length);
                            Lector.Close();

                            if (Lfx.Workspace.Master.MasterConnection.SqlMode == qGen.SqlModes.PostgreSql)
                            {
                                // PostgreSql: Tengo que actualizar las secuencias
                                Progreso.ChangeStatus("Actualizando secuencias");
                                string PatronSecuencia = @"nextval\(\'(.+)\'(.*)\)";
                                foreach (string Tabla in Lfx.Data.DatabaseCache.DefaultCache.GetTableNames())
                                {
                                    string OID = ConnRestaurar.FieldString("SELECT c.oid FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE pg_catalog.pg_table_is_visible(c.oid) AND c.relname ~ '^" + Tabla + "$'");
                                    System.Data.DataTable Campos = ConnRestaurar.Select("SELECT a.attname,pg_catalog.format_type(a.atttypid, a.atttypmod),(SELECT substring(d.adsrc for 128) FROM pg_catalog.pg_attrdef d WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef), a.attnotnull, a.attnum FROM pg_catalog.pg_attribute a WHERE a.attrelid = '" + OID + "' AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum");
                                    foreach (System.Data.DataRow Campo in Campos.Rows)
                                    {
                                        if (Campo[2] != DBNull.Value && Campo[2] != null)
                                        {
                                            string DefaultCampo = System.Convert.ToString(Campo[2]);
                                            if (Regex.IsMatch(DefaultCampo, PatronSecuencia))
                                            {
                                                string NombreCampo = System.Convert.ToString(Campo[0]);
                                                foreach (System.Text.RegularExpressions.Match Ocurrencia in Regex.Matches(DefaultCampo, PatronSecuencia))
                                                {
                                                    string Secuencia = Ocurrencia.Groups[1].ToString();
                                                    int    MaxId     = ConnRestaurar.FieldInt("SELECT MAX(" + NombreCampo + ") FROM " + Tabla) + 1;
                                                    ConnRestaurar.ExecuteNonQuery("ALTER SEQUENCE " + Secuencia + " RESTART WITH " + MaxId.ToString());
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (System.IO.File.Exists(this.BackupPath + Carpeta + "blobs.lst"))
                            {
                                // Incorporar Blobs
                                Progreso.ChangeStatus("Incorporando imágenes");
                                System.IO.StreamReader LectorBlobs = new System.IO.StreamReader(this.BackupPath + Carpeta + "blobs.lst", System.Text.Encoding.Default);
                                string InfoImagen = null;
                                do
                                {
                                    InfoImagen = LectorBlobs.ReadLine();
                                    if (InfoImagen != null && InfoImagen.Length > 0)
                                    {
                                        string Tabla               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string Campo               = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string CampoId             = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");
                                        string NombreArchivoImagen = Lfx.Types.Strings.GetNextToken(ref InfoImagen, ",");

                                        // Guardar blob nuevo
                                        qGen.Update ActualizarBlob = new qGen.Update(Tabla);
                                        ActualizarBlob.WhereClause = new qGen.Where(Campo, CampoId);

                                        System.IO.FileStream ArchivoImagen = new System.IO.FileStream(this.BackupPath + Carpeta + NombreArchivoImagen, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                        byte[] Contenido = new byte[System.Convert.ToInt32(ArchivoImagen.Length) - 1 + 1];
                                        ArchivoImagen.Read(Contenido, 0, System.Convert.ToInt32(ArchivoImagen.Length));
                                        ArchivoImagen.Close();

                                        ActualizarBlob.ColumnValues.AddWithValue(Campo, Contenido);
                                        ConnRestaurar.ExecuteNonQuery(ActualizarBlob);
                                    }
                                }while (InfoImagen != null);
                                LectorBlobs.Close();
                            }

                            if (UsandoArchivoComprimido)
                            {
                                Progreso.ChangeStatus("Eliminando archivos temporales");
                                // Borrar los archivos que descomprim temporalmente
                                System.IO.DirectoryInfo Dir = new System.IO.DirectoryInfo(this.BackupPath + Carpeta);
                                foreach (System.IO.FileInfo DirItem in Dir.GetFiles())
                                {
                                    if (DirItem.Name != "backup.7z" && DirItem.Name != "info.txt")
                                    {
                                        System.IO.File.Delete(this.BackupPath + Carpeta + DirItem.Name);
                                    }
                                }
                            }
                            Progreso.ChangeStatus("Terminando transacción");
                            Trans.Commit();
                        }
                    Progreso.End();
                }

                Lfx.Workspace.Master.RunTime.Toast("La copia de seguridad se restauró con éxito. A continuación se va a reiniciar la aplicación.", "Copia Restaurada");
            }
        }
Esempio n. 43
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        async Task FromAnalysisCenter(RequestDataMart reqDM)
        {
            //close the current task
            var currentTask = await PmnTask.GetActiveTaskForRequestActivityAsync(reqDM.Request.ID, reqDM.Request.WorkFlowActivityID.Value, DB);

            currentTask.Status          = DTO.Enums.TaskStatuses.Complete;
            currentTask.EndOn           = DateTime.UtcNow;
            currentTask.PercentComplete = 100d;

            //open new task and set the request to the new activity
            var task = DB.Actions.Add(PmnTask.CreateForWorkflowActivity(reqDM.Request.ID, CompleteDistributionActivityID, WorkflowID, DB));

            reqDM.Request.WorkFlowActivityID = CompleteDistributionActivityID;

            //get the documents uploaded by the analysis center
            var documents = await(from rd in DB.RequestDocuments
                                  join rsp in DB.Responses on rd.ResponseID equals rsp.ID
                                  join rdm in DB.RequestDataMarts on rsp.RequestDataMartID equals rdm.ID
                                  join dm in DB.DataMarts on rdm.DataMartID equals dm.ID
                                  join doc in DB.Documents on rd.RevisionSetID equals doc.RevisionSetID
                                  where rdm.RequestID == reqDM.Request.ID &&
                                  rdm.RoutingType == RoutingType.AnalysisCenter &&
                                  rd.DocumentType == RequestDocumentType.Output &&
                                  rsp.Count == rdm.Responses.Max(r => r.Count) &&
                                  doc.ID == DB.Documents.Where(dd => dd.RevisionSetID == doc.RevisionSetID).OrderByDescending(dd => dd.MajorVersion).ThenByDescending(dd => dd.MinorVersion).ThenByDescending(dd => dd.BuildVersion).ThenByDescending(dd => dd.RevisionVersion).Select(dd => dd.ID).FirstOrDefault()
                                  select new
            {
                DocumentID    = doc.ID,
                RevisionSetID = rd.RevisionSetID,
                DocumentKind  = doc.Kind,
                FileName      = doc.FileName
            }).ToArrayAsync();

            if (documents.Any(d => d.DocumentKind == JobFailTriggerFileKind))
            {
                //stop file, end regression.
                CompleteTask(task);
                reqDM.Request.WorkFlowActivityID = CompletedActivityID;

                //Save changes and reload entity
                //If this is not done, EF throws an exception on updating the status of the Request DataMart.
                await DB.SaveChangesAsync();

                await DB.Entry(reqDM).ReloadAsync();

                //Set the routing status to Failed.
                reqDM.Status = RoutingStatus.Failed;
                await DB.SaveChangesAsync();

                //change the status of the request to Failed
                //manually override the request status using sql direct, EF does not allow update of computed
                await DB.Database.ExecuteSqlCommandAsync("UPDATE Requests SET Status = @status WHERE ID = @ID", new System.Data.SqlClient.SqlParameter("@status", (int)RequestStatuses.Failed), new System.Data.SqlClient.SqlParameter("@ID", reqDM.Request.ID));

                return;
            }

            if (documents.Any(d => d.DocumentKind == StopProcessingTriggerDocumentKind))
            {
                //stop file, end regression. All the routes should be complete now and the request status should be already in Completed. Just need to update the current activity.
                CompleteTask(task);
                reqDM.Request.WorkFlowActivityID = CompletedActivityID;

                //NOTE: notification of complete request will be handled outside of the helper
            }
            else
            {
                if (documents.Length > 0)
                {//ASPE-605: change the association of the document owner from the analysis center response to the complete distribution task (current task).
                 //This is to support showing the AC documents in the task documents tab.

                    //add a reference to the response to the current task so that we can track back to the source.
                    try
                    {
                        Guid currentResponseID = await DB.Responses.Where(rsp => rsp.RequestDataMartID == reqDM.ID && rsp == rsp.RequestDataMart.Responses.OrderByDescending(rrsp => rrsp.Count).FirstOrDefault()).Select(rsp => rsp.ID).FirstAsync();

                        if (DB.Entry(currentTask).Collection(t => t.References).IsLoaded == false)
                        {
                            await DB.Entry(currentTask).Collection(t => t.References).LoadAsync();
                        }
                        if (currentTask.References.Any(tr => tr.ItemID == currentResponseID) == false)
                        {
                            task.References.Add(new TaskReference {
                                TaskID = currentTask.ID, ItemID = currentResponseID, Type = TaskItemTypes.Response
                            });
                        }
                    }catch
                    {
                        //do not kill processing if this fails, eventlog builder has contingencies to handle if the task reference to the response is not set.
                    }

                    StringBuilder query = new StringBuilder();
                    query.Append("UPDATE Documents SET ItemID='" + currentTask.ID.ToString("D") + "'");
                    query.Append(" WHERE ID IN (");
                    query.Append(string.Join(",", documents.Select(d => string.Format("'{0:D}'", d.DocumentID))));
                    query.Append(")");
                    await DB.Database.ExecuteSqlCommandAsync(query.ToString());
                }

                //the output files from the analysis center will now become the input files for each active dataparter route
                List <Guid> responseIDs = new List <Guid>();

                var allTasks = await DB.ActionReferences.Where(tr => tr.ItemID == reqDM.Request.ID &&
                                                               tr.Type == DTO.Enums.TaskItemTypes.Request &&
                                                               tr.Task.Type == DTO.Enums.TaskTypes.Task
                                                               )
                               .Select(tr => tr.Task.ID).ToArrayAsync();

                var attachments = await(from doc in DB.Documents.AsNoTracking()
                                        join x in (
                                            DB.Documents.Where(dd => allTasks.Contains(dd.ItemID))
                                            .GroupBy(k => k.RevisionSetID)
                                            .Select(k => k.OrderByDescending(d => d.MajorVersion).ThenByDescending(d => d.MinorVersion).ThenByDescending(d => d.BuildVersion).ThenByDescending(d => d.RevisionVersion).Select(y => y.ID).Distinct().FirstOrDefault())
                                            ) on doc.ID equals x
                                        where allTasks.Contains(doc.ItemID) && doc.Kind == "Attachment.Input"
                                        orderby doc.ItemID descending, doc.RevisionSetID descending, doc.CreatedOn descending
                                        select doc).ToArrayAsync();

                var dataPartnerRoutes = await DB.RequestDataMarts.Include(rdm => rdm.Responses).Where(rdm => rdm.RequestID == reqDM.Request.ID && rdm.Status != RoutingStatus.Canceled && rdm.RoutingType == RoutingType.DataPartner).ToArrayAsync();

                foreach (var route in dataPartnerRoutes)
                {
                    var response = route.AddResponse(IdentityID);
                    responseIDs.Add(response.ID);

                    route.Status = response.Count > 1 ? RoutingStatus.Resubmitted : RoutingStatus.Submitted;

                    foreach (var attachment in attachments)
                    {
                        DB.RequestDocuments.Add(new RequestDocument {
                            RevisionSetID = attachment.RevisionSetID.Value, ResponseID = response.ID, DocumentType = DTO.Enums.RequestDocumentType.AttachmentInput
                        });
                    }
                }

                var filelistDocument = documents.Where(d => !string.IsNullOrEmpty(d.DocumentKind) && string.Equals("DistributedRegression.FileList", d.DocumentKind, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (filelistDocument != null)
                {
                    //only include the files indicated in the filelist document
                    using (var ds = new Lpp.Dns.Data.Documents.DocumentStream(DB, filelistDocument.DocumentID))
                        using (var reader = new System.IO.StreamReader(ds))
                        {
                            //read the header line
                            reader.ReadLine();

                            string line, filename;
                            bool   includeInDistribution = false;
                            while (!reader.EndOfStream)
                            {
                                line = reader.ReadLine();
                                string[] split = line.Split(',');
                                if (split.Length > 0)
                                {
                                    filename = split[0].Trim();
                                    if (split.Length > 1)
                                    {
                                        includeInDistribution = string.Equals(split[1].Trim(), "1");
                                    }
                                    else
                                    {
                                        includeInDistribution = false;
                                    }

                                    if (includeInDistribution == false)
                                    {
                                        continue;
                                    }

                                    if (!string.IsNullOrEmpty(filename))
                                    {
                                        Guid?revisionSetID = documents.Where(d => string.Equals(d.FileName, filename, StringComparison.OrdinalIgnoreCase)).Select(d => d.RevisionSetID).FirstOrDefault();
                                        if (revisionSetID.HasValue)
                                        {
                                            DB.RequestDocuments.AddRange(responseIDs.Select(rspID => new RequestDocument {
                                                DocumentType = RequestDocumentType.Input, ResponseID = rspID, RevisionSetID = revisionSetID.Value
                                            }).ToArray());
                                        }
                                    }
                                }
                            }

                            reader.Close();
                        }
                }
                else
                {
                    var requestDocuments = (from d in documents
                                            from responseID in responseIDs
                                            where d.DocumentKind != "DistributedRegression.AdapterEventLog" && d.DocumentKind != "DistributedRegression.TrackingTable"
                                            select new RequestDocument
                    {
                        DocumentType = RequestDocumentType.Input,
                        ResponseID = responseID,
                        RevisionSetID = d.RevisionSetID
                    }).ToArray();

                    if (requestDocuments.Length > 0)
                    {
                        DB.RequestDocuments.AddRange(requestDocuments);
                    }
                }
            }

            await DB.SaveChangesAsync();
        }
Esempio n. 44
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        async Task FromDataPartner(RequestDataMart reqDM)
        {
            //close the current task
            var currentTask = await PmnTask.GetActiveTaskForRequestActivityAsync(reqDM.Request.ID, reqDM.Request.WorkFlowActivityID.Value, DB);

            CompleteTask(currentTask);

            //open new task and set the request to the new activity
            var task = DB.Actions.Add(PmnTask.CreateForWorkflowActivity(reqDM.Request.ID, ConductAnalysisActivityID, WorkflowID, DB));

            reqDM.Request.WorkFlowActivityID = ConductAnalysisActivityID;

            //create new routing
            var analysisCenterRouting = await DB.RequestDataMarts.Include(rdm => rdm.Responses).Where(rdm => rdm.RequestID == reqDM.Request.ID && rdm.RoutingType == RoutingType.AnalysisCenter).FirstOrDefaultAsync();

            Lpp.Dns.Data.Response analysisCenterResponse = null;
            if (analysisCenterRouting.Status == RoutingStatus.Draft && analysisCenterRouting.Responses.Count == 1 && analysisCenterRouting.Responses.Where(rsp => rsp.ResponseTime.HasValue == false).Any())
            {
                //if the initial status of the routing is draft, and there is only a single response assume this is the first time hitting the analysis center.
                //use the existing response to submit to the analysis center
                analysisCenterResponse = analysisCenterRouting.Responses.First();
            }
            else if (analysisCenterRouting.Status != RoutingStatus.Draft)
            {
                analysisCenterRouting.Status = RoutingStatus.Draft;
            }

            if (analysisCenterResponse == null)
            {
                analysisCenterResponse = analysisCenterRouting.AddResponse(IdentityID);
            }

            //use all the dp output documents to be the input documents for the AC routing
            //build a manifest for where the documents are coming from
            List <Lpp.Dns.DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem> manifestItems = new List <DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem>();
            var q = from rd in DB.RequestDocuments
                    join rsp in DB.Responses on rd.ResponseID equals rsp.ID
                    join rdm in DB.RequestDataMarts on rsp.RequestDataMartID equals rdm.ID
                    join dm in DB.DataMarts on rdm.DataMartID equals dm.ID
                    join doc in DB.Documents on rd.RevisionSetID equals doc.RevisionSetID
                    where rsp.Count == rsp.RequestDataMart.Responses.Max(r => r.Count) &&
                    rdm.RequestID == reqDM.Request.ID &&
                    rd.DocumentType == RequestDocumentType.Output &&
                    rdm.RoutingType == RoutingType.DataPartner &&
                    doc.ItemID == rsp.ID &&
                    doc.ID == DB.Documents.Where(dd => dd.RevisionSetID == doc.RevisionSetID && doc.ItemID == rsp.ID).OrderByDescending(dd => dd.MajorVersion).ThenByDescending(dd => dd.MinorVersion).ThenByDescending(dd => dd.BuildVersion).ThenByDescending(dd => dd.RevisionVersion).Select(dd => dd.ID).FirstOrDefault()
                    select new
            {
                DocumentID            = doc.ID,
                DocumentKind          = doc.Kind,
                DocumentFileName      = doc.FileName,
                ResponseID            = rd.ResponseID,
                RevisionSetID         = rd.RevisionSetID,
                RequestDataMartID     = rsp.RequestDataMartID,
                DataMartID            = rdm.DataMartID,
                DataPartnerIdentifier = dm.DataPartnerIdentifier,
                DataMart = dm.Name
            };

            var documents = await(q).ToArrayAsync();

            // further filtering based on if a output filelist document was included needs to be done. Only the files indicated should be passed on to the analysis center
            foreach (var dpDocuments in documents.GroupBy(k => k.RequestDataMartID))
            {
                var filelistDocument = dpDocuments.Where(d => !string.IsNullOrEmpty(d.DocumentKind) && string.Equals("DistributedRegression.FileList", d.DocumentKind, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (filelistDocument != null)
                {
                    //only include the files indicated in the filelist document
                    using (var ds = new Lpp.Dns.Data.Documents.DocumentStream(DB, filelistDocument.DocumentID))
                        using (var reader = new System.IO.StreamReader(ds))
                        {
                            //read the header line
                            reader.ReadLine();

                            string line, filename;
                            bool   includeInDistribution = false;
                            while (!reader.EndOfStream)
                            {
                                line = reader.ReadLine();
                                string[] split = line.Split(',');
                                if (split.Length > 0)
                                {
                                    filename = split[0].Trim();
                                    if (split.Length > 1)
                                    {
                                        includeInDistribution = string.Equals(split[1].Trim(), "1");
                                    }
                                    else
                                    {
                                        includeInDistribution = false;
                                    }

                                    if (includeInDistribution == false)
                                    {
                                        continue;
                                    }

                                    if (!string.IsNullOrEmpty(filename))
                                    {
                                        Guid?revisionSetID = dpDocuments.Where(d => string.Equals(d.DocumentFileName, filename, StringComparison.OrdinalIgnoreCase)).Select(d => d.RevisionSetID).FirstOrDefault();
                                        if (revisionSetID.HasValue)
                                        {
                                            DB.RequestDocuments.AddRange(dpDocuments.Where(d => d.RevisionSetID == revisionSetID.Value).Select(d => new RequestDocument {
                                                DocumentType = RequestDocumentType.Input, ResponseID = analysisCenterResponse.ID, RevisionSetID = d.RevisionSetID
                                            }).ToArray());
                                            manifestItems.AddRange(dpDocuments.Where(d => d.RevisionSetID == revisionSetID.Value).Select(d => new DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem
                                            {
                                                DocumentID            = d.DocumentID,
                                                DataMart              = d.DataMart,
                                                DataMartID            = d.DataMartID,
                                                DataPartnerIdentifier = d.DataPartnerIdentifier,
                                                RequestDataMartID     = d.RequestDataMartID,
                                                ResponseID            = d.ResponseID,
                                                RevisionSetID         = d.RevisionSetID
                                            }).ToArray());
                                        }
                                    }
                                }
                            }

                            reader.Close();
                        }
                }
                else
                {
                    var inputDocuments = dpDocuments.Where(d => d.DocumentKind != "DistributedRegression.AdapterEventLog" && d.DocumentKind != "DistributedRegression.TrackingTable");
                    if (inputDocuments.Count() > 0)
                    {
                        DB.RequestDocuments.AddRange(inputDocuments.Select(d => new RequestDocument {
                            DocumentType = RequestDocumentType.Input, ResponseID = analysisCenterResponse.ID, RevisionSetID = d.RevisionSetID
                        }).ToArray());
                        manifestItems.AddRange(inputDocuments.Select(d => new DTO.QueryComposer.DistributedRegressionAnalysisCenterManifestItem
                        {
                            DocumentID            = d.DocumentID,
                            DataMart              = d.DataMart,
                            DataMartID            = d.DataMartID,
                            DataPartnerIdentifier = d.DataPartnerIdentifier,
                            RequestDataMartID     = d.RequestDataMartID,
                            ResponseID            = d.ResponseID,
                            RevisionSetID         = d.RevisionSetID
                        }).ToArray());
                    }
                }
            }

            //serialize the manifest of dataparter documents to the analysis center
            byte[] buffer;
            using (var ms = new System.IO.MemoryStream())
                using (var sw = new System.IO.StreamWriter(ms))
                    using (var jw = new Newtonsoft.Json.JsonTextWriter(sw))
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Serialize(jw, manifestItems);
                        jw.Flush();

                        buffer = ms.ToArray();
                    }

            //create and add the manifest file
            Document analysisCenterManifest = DB.Documents.Add(new Document
            {
                Description  = "Contains information about the input documents and the datamart they came from.",
                Name         = "Internal: Analysis Center Manifest",
                FileName     = "manifest.json",
                ItemID       = task.ID,
                Kind         = DocumentKind.SystemGeneratedNoLog,
                UploadedByID = IdentityID,
                Viewable     = false,
                MimeType     = "application/json",
                Length       = buffer.Length
            });

            analysisCenterManifest.RevisionSetID = analysisCenterManifest.ID;

            //TODO:determine if there is a parent document to make the manifest a revision of. If there is update the revisionset id, and version numbers
            //chances are there should not be unless this is a resubmit for the same task

            var allTasks = await DB.ActionReferences.Where(tr => tr.ItemID == reqDM.Request.ID &&
                                                           tr.Type == DTO.Enums.TaskItemTypes.Request &&
                                                           tr.Task.Type == DTO.Enums.TaskTypes.Task
                                                           )
                           .Select(tr => tr.Task.ID).ToArrayAsync();

            var attachments = await(from doc in DB.Documents.AsNoTracking()
                                    join x in (
                                        DB.Documents.Where(dd => allTasks.Contains(dd.ItemID))
                                        .GroupBy(k => k.RevisionSetID)
                                        .Select(k => k.OrderByDescending(d => d.MajorVersion).ThenByDescending(d => d.MinorVersion).ThenByDescending(d => d.BuildVersion).ThenByDescending(d => d.RevisionVersion).Select(y => y.ID).Distinct().FirstOrDefault())
                                        ) on doc.ID equals x
                                    where allTasks.Contains(doc.ItemID) && doc.Kind == "Attachment.Input"
                                    orderby doc.ItemID descending, doc.RevisionSetID descending, doc.CreatedOn descending
                                    select doc).ToArrayAsync();

            DB.RequestDocuments.Add(new RequestDocument {
                DocumentType = RequestDocumentType.Input, ResponseID = analysisCenterResponse.ID, RevisionSetID = analysisCenterManifest.RevisionSetID.Value
            });

            foreach (var attachment in attachments)
            {
                DB.RequestDocuments.Add(new RequestDocument {
                    RevisionSetID = attachment.RevisionSetID.Value, ResponseID = analysisCenterResponse.ID, DocumentType = DTO.Enums.RequestDocumentType.AttachmentInput
                });
            }

            await DB.SaveChangesAsync();

            await DB.Entry(analysisCenterRouting).ReloadAsync();

            //post the manifest content
            analysisCenterManifest.SetData(DB, buffer);

            //submit the routing
            analysisCenterRouting.Status = analysisCenterResponse.Count > 1 ? RoutingStatus.Resubmitted : RoutingStatus.Submitted;
            await DB.SaveChangesAsync();

            //Check for Job Fail trigger, and update Data Partner Routing to Failed.
            //Request status will not be affected.
            if (documents.Any(d => d.DocumentKind == JobFailTriggerFileKind))
            {
                //Reload the entity before updating the status, else EF will report an exception.
                await DB.Entry(reqDM).ReloadAsync();

                reqDM.Status = RoutingStatus.Failed;
                await DB.SaveChangesAsync();
            }

            //change the status of the request to conducting analysis
            //manually override the request status using sql direct, EF does not allow update of computed
            await DB.Database.ExecuteSqlCommandAsync("UPDATE Requests SET Status = @status WHERE ID = @ID", new System.Data.SqlClient.SqlParameter("@status", (int)RequestStatuses.ConductingAnalysis), new System.Data.SqlClient.SqlParameter("@ID", reqDM.Request.ID));

            await DB.Entry(reqDM.Request).ReloadAsync();
        }
Esempio n. 45
0
        public static RDungeon LoadRDungeon(int dungeonNum)
        {
            RDungeon dungeon  = new RDungeon(dungeonNum);
            string   FilePath = IO.Paths.RDungeonsFolder + "rdungeon" + dungeonNum.ToString() + ".dat";

            using (System.IO.StreamReader reader = new System.IO.StreamReader(FilePath)) {
                while (!(reader.EndOfStream))
                {
                    string[] parse = reader.ReadLine().Split('|');
                    switch (parse[0].ToLower())
                    {
                    case "rdungeondata":
                        if (parse[1].ToLower() != "v1")
                        {
                            reader.Close();
                            reader.Dispose();
                            return(null);
                        }
                        break;

                    case "data":
                        dungeon.DungeonName = parse[1];
                        dungeon.Direction   = (Enums.Direction)parse[2].ToInt();
                        dungeon.MaxFloors   = parse[3].ToInt();
                        dungeon.Recruitment = parse[4].ToBool();
                        dungeon.Exp         = parse[5].ToBool();
                        break;

                    case "terrain": {
                        #region Terrain
                        dungeon.StairsX     = parse[1].ToInt();
                        dungeon.StairsSheet = parse[2].ToInt();

                        dungeon.mGroundX     = parse[3].ToInt();
                        dungeon.mGroundSheet = parse[4].ToInt();

                        dungeon.mTopLeftX       = parse[5].ToInt();
                        dungeon.mTopLeftSheet   = parse[6].ToInt();
                        dungeon.mTopCenterX     = parse[7].ToInt();
                        dungeon.mTopCenterSheet = parse[8].ToInt();
                        dungeon.mTopRightX      = parse[9].ToInt();
                        dungeon.mTopRightSheet  = parse[10].ToInt();

                        dungeon.mCenterLeftX       = parse[11].ToInt();
                        dungeon.mCenterLeftSheet   = parse[12].ToInt();
                        dungeon.mCenterCenterX     = parse[13].ToInt();
                        dungeon.mCenterCenterSheet = parse[14].ToInt();
                        dungeon.mCenterRightX      = parse[15].ToInt();
                        dungeon.mCenterRightSheet  = parse[16].ToInt();

                        dungeon.mBottomLeftX       = parse[17].ToInt();
                        dungeon.mBottomLeftSheet   = parse[18].ToInt();
                        dungeon.mBottomCenterX     = parse[19].ToInt();
                        dungeon.mBottomCenterSheet = parse[20].ToInt();
                        dungeon.mBottomRightX      = parse[21].ToInt();
                        dungeon.mBottomRightSheet  = parse[22].ToInt();

                        dungeon.mInnerTopLeftX        = parse[23].ToInt();
                        dungeon.mInnerTopLeftSheet    = parse[24].ToInt();
                        dungeon.mInnerBottomLeftX     = parse[25].ToInt();
                        dungeon.mInnerBottomLeftSheet = parse[26].ToInt();

                        dungeon.mInnerTopRightX        = parse[27].ToInt();
                        dungeon.mInnerTopRightSheet    = parse[28].ToInt();
                        dungeon.mInnerBottomRightX     = parse[29].ToInt();
                        dungeon.mInnerBottomRightSheet = parse[30].ToInt();

                        if (parse.Length > 32)
                        {
                            dungeon.mWaterX            = parse[31].ToInt();
                            dungeon.mWaterSheet        = parse[32].ToInt();
                            dungeon.mWaterAnimX        = parse[33].ToInt();
                            dungeon.mWaterAnimSheet    = parse[34].ToInt();
                            dungeon.mIsolatedWallX     = parse[35].ToInt();
                            dungeon.mIsolatedWallSheet = parse[36].ToInt();

                            dungeon.mColumnTopX        = parse[37].ToInt();
                            dungeon.mColumnTopSheet    = parse[38].ToInt();
                            dungeon.mColumnCenterX     = parse[39].ToInt();
                            dungeon.mColumnCenterSheet = parse[40].ToInt();
                            dungeon.mColumnBottomX     = parse[41].ToInt();
                            dungeon.mColumnBottomSheet = parse[42].ToInt();

                            dungeon.mRowLeftX       = parse[43].ToInt();
                            dungeon.mRowLeftSheet   = parse[44].ToInt();
                            dungeon.mRowCenterX     = parse[45].ToInt();
                            dungeon.mRowCenterSheet = parse[46].ToInt();
                            if (parse.Length > 48)
                            {
                                dungeon.mRowRightX     = parse[47].ToInt();
                                dungeon.mRowRightSheet = parse[48].ToInt();
                                if (parse.Length > 50)
                                {
                                    dungeon.mShoreTopLeftX             = parse[49].ToInt();
                                    dungeon.mShoreTopLeftSheet         = parse[50].ToInt();
                                    dungeon.mShoreTopRightX            = parse[51].ToInt();
                                    dungeon.mShoreTopRightSheet        = parse[52].ToInt();
                                    dungeon.mShoreBottomRightX         = parse[53].ToInt();
                                    dungeon.mShoreBottomRightSheet     = parse[54].ToInt();
                                    dungeon.mShoreBottomLeftX          = parse[55].ToInt();
                                    dungeon.mShoreBottomLeftSheet      = parse[56].ToInt();
                                    dungeon.mShoreDiagonalForwardX     = parse[57].ToInt();
                                    dungeon.mShoreDiagonalForwardSheet = parse[58].ToInt();
                                    dungeon.mShoreDiagonalBackX        = parse[59].ToInt();
                                    dungeon.mShoreDiagonalBackSheet    = parse[60].ToInt();

                                    dungeon.mShoreTopX            = parse[61].ToInt();
                                    dungeon.mShoreTopSheet        = parse[62].ToInt();
                                    dungeon.mShoreRightX          = parse[63].ToInt();
                                    dungeon.mShoreRightSheet      = parse[64].ToInt();
                                    dungeon.mShoreBottomX         = parse[65].ToInt();
                                    dungeon.mShoreBottomSheet     = parse[66].ToInt();
                                    dungeon.mShoreLeftX           = parse[67].ToInt();
                                    dungeon.mShoreLeftSheet       = parse[68].ToInt();
                                    dungeon.mShoreVerticalX       = parse[69].ToInt();
                                    dungeon.mShoreVerticalSheet   = parse[70].ToInt();
                                    dungeon.mShoreHorizontalX     = parse[71].ToInt();
                                    dungeon.mShoreHorizontalSheet = parse[72].ToInt();

                                    dungeon.mShoreInnerTopLeftX         = parse[73].ToInt();
                                    dungeon.mShoreInnerTopLeftSheet     = parse[74].ToInt();
                                    dungeon.mShoreInnerTopRightX        = parse[75].ToInt();
                                    dungeon.mShoreInnerTopRightSheet    = parse[76].ToInt();
                                    dungeon.mShoreInnerBottomRightX     = parse[77].ToInt();
                                    dungeon.mShoreInnerBottomRightSheet = parse[78].ToInt();
                                    dungeon.mShoreInnerBottomLeftX      = parse[79].ToInt();
                                    dungeon.mShoreInnerBottomLeftSheet  = parse[80].ToInt();

                                    dungeon.mShoreInnerTopX        = parse[81].ToInt();
                                    dungeon.mShoreInnerTopSheet    = parse[82].ToInt();
                                    dungeon.mShoreInnerRightX      = parse[83].ToInt();
                                    dungeon.mShoreInnerRightSheet  = parse[84].ToInt();
                                    dungeon.mShoreInnerBottomX     = parse[85].ToInt();
                                    dungeon.mShoreInnerBottomSheet = parse[86].ToInt();
                                    dungeon.mShoreInnerLeftX       = parse[87].ToInt();
                                    dungeon.mShoreInnerLeftSheet   = parse[88].ToInt();

                                    dungeon.mShoreSurroundedX     = parse[89].ToInt();
                                    dungeon.mShoreSurroundedSheet = parse[90].ToInt();
                                }
                            }
                        }
                        #endregion
                    }
                    break;

                    case "floor": {
                        RDungeonFloor floor = new RDungeonFloor();
                        floor.WeatherIntensity = parse[1].ToInt();
                        floor.Weather          = (Enums.Weather)parse[2].ToInt();
                        floor.Music            = parse[3];
                        floor.GoalType         = (Enums.RFloorGoalType)parse[4].ToInt();
                        floor.GoalMap          = parse[5].ToInt();
                        floor.GoalX            = parse[6].ToInt();
                        floor.GoalY            = parse[7].ToInt();
                        floor.ItemSpawnRate    = parse[8].ToInt();
                        int maxTraps = parse[9].ToInt();

                        int n = 10;
                        for (int i = 0; i < 15; i++)
                        {
                            floor.Npc[i] = parse[n].ToInt();
                            n++;
                        }
                        for (int i = 0; i < 8; i++)
                        {
                            floor.Items[i] = parse[n].ToInt();
                            n++;
                        }
                        for (int i = 0; i < maxTraps; i++)
                        {
                            floor.Traps.Add(parse[n].ToInt());
                            n++;
                        }
                        dungeon.Floors.Add(floor);
                    }
                    break;

                    case "cratersettings": {
                        dungeon.Options.Craters         = parse[1].ToInt();
                        dungeon.Options.CraterMinLength = parse[2].ToInt();
                        dungeon.Options.CraterMaxLength = parse[3].ToInt();
                        dungeon.Options.CraterFuzzy     = parse[4].ToBool();
                    }
                    break;
                    }
                }
            }
            return(dungeon);
        }
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No arguments were passed.");
                Console.ReadLine();  // Keep the console open.
                return;
            }

            var filePath = args[0];

            Console.WriteLine($"Processing {filePath}.");

            if (filePath.ToLower().EndsWith(".xlsx"))
            {
                var package = new ExcelPackage(new System.IO.FileInfo(filePath));

                filePath = filePath.Replace(".xlsx", ".csv");
                package.ConvertToCsv(filePath);

                package.Dispose();
            }

            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(filePath);

            // Get the Header (Columns)
            var columns = new List <DataTableColumn> ();
            // Read first libe (Header or column names)
            var line1 = file.ReadLine();
            // Comma separated
            var arrNames = line1.Split(',');

            foreach (var colName in arrNames)
            {
                var col = new DataTableColumn();
                col.ColumnName = colName;
                columns.Add(col);
            }

            // get the rows
            while ((line = file.ReadLine()) != null)
            {
                var values = line.Split(',');
                var index  = 0;
                foreach (var value in values)
                {
                    columns[index++].Values.Add(value);
                }
            }

            file.Close();
            var dataTableName = "Data";

            var has = columns.FirstOrDefault(col => col.ColumnName == "Type");

            if (has != null)
            {
                dataTableName = has.Values[0];
            }

            var datatable = $"let {dataTableName} = datatable (" + appendColumns(columns) + ") [";

            datatable += Environment.NewLine;
            datatable += appendRows(columns);
            datatable += Environment.NewLine;
            datatable += "];";
            datatable += Environment.NewLine;
            datatable += dataTableName;
            Console.WriteLine(datatable);
            // TODO: Save as .kql for Kusto explorer
            var logPath   = filePath.Replace(".csv", ".kql");
            var logFile   = System.IO.File.Create(logPath);
            var logWriter = new System.IO.StreamWriter(logFile);

            logWriter.WriteLine(datatable);
            logWriter.Dispose();
            TextCopy.Clipboard.SetText(datatable);
        }
        public List <WorkflowStep> getWorkflowFromFile(string pathOfWorkflow)
        {
            List <WorkflowStep> returnList = new List <WorkflowStep>();


            int    counter = 0;
            string line;
            //  string path = Directory.GetCurrentDirectory();
            // string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\workflow.txt";

            string path = pathOfWorkflow;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(path);

            while ((line = file.ReadLine()) != null)
            {
                System.Console.WriteLine(line);

                if (line.Contains("<First>"))
                {
                    string name = line.Split('>')[1];
                    (returnList.Find(item => item.Name == name)).First = true;
                }

                else if (line.Contains("<Last>"))
                {
                    string name = line.Split('>')[1];
                    (returnList.Find(item => item.Name == name)).Last = true;
                }

                else if (line.Contains("<Create>"))
                {
                    string name = line.Split('>')[1];
                    (returnList.Find(item => item.Name == name)).CreateState = true;
                }

                else
                {
                    if (line.Contains(":"))
                    {
                        int      index       = 0;
                        string[] statusArray = line.Split(':');
                        string   mainStatus  = statusArray[0];

                        // first Entry == current Status
                        WorkflowStep status = new WorkflowStep(statusArray[0].Trim(), statusArray[0].Trim());

                        // Entry 2+ == mapped deprecated status
                        for (int i = index; i < statusArray.Length; i++)
                        {
                            status.Aliases.Add(statusArray[i].Trim());
                        }
                        returnList.Add(status);
                    }
                    else
                    {
                        returnList.Add(new WorkflowStep(line.Trim(), line.Trim()));
                    }
                }

                counter++;
            }
            Boolean ended = false;

            foreach (WorkflowStep step in returnList)
            {
                if (step.Last)
                {
                    ended = true;
                }
                if (ended)
                {
                    step.DoneState = true;
                }
            }

            file.Close();

            return(returnList);
        }
Esempio n. 48
0
        public static Item LoadItem(int itemNum)
        {
            Item item = new Item();

            string[] parse = null;
            using (System.IO.StreamReader read = new System.IO.StreamReader(IO.Paths.ItemsFolder + "item" + itemNum + ".dat"))
            {
                while (!(read.EndOfStream))
                {
                    parse = read.ReadLine().Split('|');
                    switch (parse[0].ToLower())
                    {
                    case "itemdata":
                        if (parse[1].ToLower() != "v2")
                        {
                            read.Close();
                            return(null);
                        }
                        break;

                    case "data":
                        item.Name  = parse[1].Trim();
                        item.Desc  = parse[2];
                        item.Pic   = parse[3].ToInt();
                        item.Type  = (Enums.ItemType)parse[4].ToInt();
                        item.Data1 = parse[5].ToInt();
                        item.Data2 = parse[6].ToInt();
                        item.Data3 = parse[7].ToInt();


                        item.Price     = parse[8].ToInt();
                        item.Stackable = parse[9].ToBool();
                        item.Bound     = parse[10].ToBool();
                        item.Loseable  = parse[11].ToBool();
                        item.Rarity    = parse[12].ToInt();
                        break;

                    case "reqs":
                    {
                        item.AttackReq   = parse[1].ToInt();
                        item.DefenseReq  = parse[2].ToInt();
                        item.SpAtkReq    = parse[3].ToInt();
                        item.SpDefReq    = parse[4].ToInt();
                        item.SpeedReq    = parse[5].ToInt();
                        item.ScriptedReq = parse[6].ToInt();
                    }
                    break;

                    case "stats":
                    {
                        item.AddHP       = parse[1].ToInt();
                        item.AddPP       = parse[2].ToInt();
                        item.AddAttack   = parse[3].ToInt();
                        item.AddDefense  = parse[4].ToInt();
                        item.AddSpAtk    = parse[5].ToInt();
                        item.AddSpDef    = parse[6].ToInt();
                        item.AddSpeed    = parse[7].ToInt();
                        item.AddEXP      = parse[8].ToInt();
                        item.AttackSpeed = parse[9].ToInt();

                        item.RecruitBonus = parse[10].ToInt();
                    }
                    break;
                    }
                }
            }
            return(item);
        }
Esempio n. 49
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Language lang;
            bool     restart = false;

            System.IO.StreamReader sr = null;
            try
            {
                sr      = new System.IO.StreamReader(Application.StartupPath + "\\Doc\\language.config");
                lang    = (Language)Enum.Parse(typeof(Language), sr.ReadLine());
                restart = bool.Parse(sr.ReadLine());
                sr.Close();
            }
            catch
            {
                if (sr != null)
                {
                    sr.Close();
                }
                lang = Language.English;
                System.IO.StreamWriter sw = new System.IO.StreamWriter(Application.StartupPath + "\\Doc\\language.config");
                sw.WriteLine("English");
                sw.WriteLine("false");
                sw.Flush();
                sw.Close();
            }
            try
            {
                RegistryKey mainkey = Registry.ClassesRoot.OpenSubKey(@".msm\Shell\Open\Command", false);
                string      value   = "\"" + Application.StartupPath + "\\MeasureMan.exe\"" + " \"%1\"";
                if (mainkey == null)
                {
                    RegistryKey key = Registry.ClassesRoot.CreateSubKey(".msm");
                    key.SetValue("File Type", "msm File");
                    key.CreateSubKey(@"Shell\Open\Command").SetValue("", value);
                    SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST | HChangeNotifyFlags.SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
                }
                else if (!value.Equals(mainkey.GetValue("").ToString()))
                {
                    RegistryKey anotherKey = Registry.ClassesRoot.OpenSubKey(@".msm\Shell\Open\Command", true);
                    anotherKey.SetValue("", value);
                    SHChangeNotify(HChangeNotifyEventID.SHCNE_ASSOCCHANGED, HChangeNotifyFlags.SHCNF_IDLIST | HChangeNotifyFlags.SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);
                }
            }
            catch
            {
                if (!restart)
                {
                    if (lang == Language.Chinese)
                    {
                        MessageBox.Show("以管理员身份运行可将工程文件关联到此程序");
                    }
                    else if (lang == Language.English)
                    {
                        MessageBox.Show("Run as an administrator to associate the project file with this program");
                    }
                }
            }
            try
            {
                string[] args = Environment.GetCommandLineArgs();
                if (args.Length == 2)
                {
                    Application.Run(new MeasureMan(args[1], lang));
                }
                else
                {
                    Application.Run(new MeasureMan(null, lang));
                }
            }
            catch { }
        }
Esempio n. 50
0
        private void DetermineDelimiter()
        {
            string line;
            int    columnCounter = 0;

            char[] possibleDelimiters = { ',', '\t', ';' };
            int[]  delimitersFrequecy = { 0, 0, 0 };
            int    index = 0;


            while (index <= 2)
            {
                System.IO.StreamReader file = new System.IO.StreamReader(_filePath);

                if ((line = file.ReadLine()) != null)
                {
                    string[] result = line.Split(possibleDelimiters[index]);

                    columnCounter = result.Length;

                    Console.WriteLine("for file " + _filePath + " counter is " + columnCounter + " for " + possibleDelimiters[index]);
                    Console.Read();
                }

                bool ok = true;
                while ((line = file.ReadLine()) != null)
                {
                    string[] result = line.Split(possibleDelimiters[index]);

                    //Console.WriteLine("for file " + _filePath + " result counter is " + result.Length + " for " + possibleDelimiters[index]);
                    //Console.Read();

                    if (result.Length != columnCounter)
                    {
                        delimitersFrequecy[index] = 0;
                        ok = false;
                        break;
                    }
                }

                if (ok == true)
                {
                    delimitersFrequecy[index] = columnCounter;
                }

                index++;
                file.Close();
            }

            int maxVal         = 0;
            int delimiterIndex = 0;

            for (int i = 0; i <= 2; i++)
            {
                if (delimitersFrequecy[i] > maxVal)
                {
                    maxVal         = delimitersFrequecy[i];
                    delimiterIndex = i;
                }
            }

            _fileFormat._fileDelimiter = possibleDelimiters[delimiterIndex];
        }
Esempio n. 51
0
        /// <summary>
        /// Creates a new JsonCulture instance from the supplied CultureInfo.
        /// </summary>
        /// <param name="cultureInfo">The CultureInfo needed to get the proper translations for this JsonCulture instance</param>
        /// <param name="resourceType">Type of resource (blog or admin)</param>
        /// <remarks>
        ///
        /// This class uses a dictionary as its basis for storing/caching its information. This makes it incredibly easy to extend
        /// without having to create/remove properties.
        ///
        /// </remarks>
        public BlogCulture(CultureInfo cultureInfo, ResourceType resourceType)
        {
            if (cultureInfo == null)
            {
                throw new ArgumentNullException("cultureInfo");
            }
            this.cultureInfo = cultureInfo;

            if (resourceType == ResourceType.Admin)
            {
                try
                {
                    var filePath = System.Web.HttpContext.Current.Server.MapPath(
                        System.IO.Path.Combine(BlogConfig.StorageLocation, "labels.txt"));

                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.StreamReader reader = System.IO.File.OpenText(filePath);
                        while (!reader.EndOfStream)
                        {
                            string line = reader.ReadLine();
                            if (!string.IsNullOrEmpty(line) && line.Trim().Length > 0)
                            {
                                AddResource(line);
                            }
                        }
                    }
                    else
                    {
                        AddJavaScriptResources();
                    }
                }
                catch (Exception ex)
                {
                    Utils.Log("Error loading admin labels from App_Data/labels.txt", ex);
                }
            }
            else
            {
                AddResource("apmlDescription");
                AddResource("beTheFirstToRate");
                AddResource("cancel");
                AddResource("comments");
                AddResource("commentWaitingModeration");
                AddResource("commentWasSaved");
                AddResource("couldNotSaveQuickPost");
                AddResource("currentlyRated");
                AddResource("defaultPostCategory");
                AddResource("delete");
                AddResource("filter");
                AddResource("hasRated");
                AddResource("noNotesYet");
                AddResource("notAuthorizedToCreateNewPosts");
                AddResource("or");
                AddResource("postSaved");
                AddResource("publish");
                AddResource("rateThisXStars");
                AddResource("ratingHasBeenRegistered");
                AddResource("save");
                AddResource("savingTheComment");
                AddResource("tagsCommaDelimited");
            }
        }
Esempio n. 52
0
        private void DetermineFileStructure()
        {
            System.IO.StreamReader file = new System.IO.StreamReader(_filePath);

            string line;

            string[] colsName = { " " };
            if ((line = file.ReadLine()) != null)
            {
                colsName = line.Split(_fileFormat._fileDelimiter);

                for (int iterator = 0; iterator < colsName.Length; iterator++)
                {
                    Console.WriteLine(_filePath + " col " + colsName[iterator]);
                    _fileFormat._fileStructure[colsName[iterator]] = "undefined";

                    _fileCols[colsName[iterator]] = new List <string>();
                }
            }

            while ((line = file.ReadLine()) != null)
            {
                string[] result = line.Split(_fileFormat._fileDelimiter);

                for (int iterator = 0; iterator < result.Length; iterator++)
                {
                    _fileCols[colsName[iterator]].Add(result[iterator]); // add in the dictionary for file

                    if (this.IsDateType(result[iterator]))
                    {
                        if (_fileFormat._fileStructure[colsName[iterator]] == "undefined")
                        {
                            _fileFormat._fileStructure[colsName[iterator]] = "Date";
                        }
                        else
                        {
                            if (_fileFormat._fileStructure[colsName[iterator]] != "Date")
                            {
                                Console.WriteLine("error from file structure" + _filePath);
                                Console.Read();
                            }
                        }
                    }
                    else
                    {
                        if (this.IsNumberType(result[iterator]))
                        {
                            if (_fileFormat._fileStructure[colsName[iterator]] == "undefined")
                            {
                                _fileFormat._fileStructure[colsName[iterator]] = "Number";
                            }
                            else
                            {
                                if (_fileFormat._fileStructure[colsName[iterator]] != "Number")
                                {
                                    Console.WriteLine("error from file structure" + _filePath);
                                    Console.Read();
                                }
                            }
                        }
                        else
                        {
                            if (_fileFormat._fileStructure[colsName[iterator]] == "undefined")
                            {
                                _fileFormat._fileStructure[colsName[iterator]] = "String";
                            }
                            else
                            {
                                if (_fileFormat._fileStructure[colsName[iterator]] != "String")
                                {
                                    Console.WriteLine("error from file structure" + _filePath);
                                    Console.Read();
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 53
0
        public static void test4(string filename)
        {
            HasseDiagram        HDM      = new HasseDiagram(HasseNodeFactory.NodeType.STRING);
            HasseNodeCollection elements = new HasseNodeCollection();

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            System.IO.TextReader rdr = new System.IO.StreamReader(fs);
            int maxCount             = 200000;
            int count = 0;

            List <string> Words = new List <string>();


            do
            {
                //if (count >= maxCount)   break;

                char[] delim = { ' ', ',', '.' };
                string line  = rdr.ReadLine();
                if (line == null)
                {
                    break;
                }
                string[] words = line.Split(delim);
                for (int i = 0; i < words.Length; i++)
                {
                    count += 1;
                    string w = words[i];
                    w = w.Trim();
                    w = w.ToLower();
                    w = w.Replace("*", "");
                    w = w.Replace("(", "");
                    w = w.Replace(")", "");
                    w = w.Replace("]", "");
                    w = w.Replace("[", "");
                    w = w.Replace("„", "");
                    w = w.Replace(":", "");
                    w = w.Replace("\"", "");
                    if (!string.IsNullOrEmpty(w))
                    {
                        Words.Add(w); // Add to list for insertion below
                    }
                }
            } while (true);

            // 'randomise' order
            StringHashComparer shc = new StringHashComparer();

            Words.Sort(shc);

            //65533
            count = 0;
            foreach (string Word in Words)
            {
                count += 1;

                System.Diagnostics.Debug.WriteLine(Word);
                foreach (char c in Word.ToCharArray())
                {
                    //    System.Diagnostics.Debug.WriteLine(((int)c).ToString ());
                }

                HDM.AddNode(Word);
                if (count >= maxCount)
                {
                    break;
                }
            }

            fs.Close();
            sw.Stop();

            System.Diagnostics.Debug.WriteLine("Total time: " + ((double)sw.ElapsedMilliseconds / 1000).ToString() + " seconds");
            System.Diagnostics.Debug.WriteLine("Total time: " + ((double)sw.ElapsedTicks / System.Diagnostics.Stopwatch.Frequency).ToString() + " seconds");

            HDM.ContractChains2();

            HDM.HasseDiagramNodes.Sort();
            foreach (HasseNode n in HDM.HasseDiagramNodes.Values)
            {
                System.Diagnostics.Debug.WriteLine(n.KeyString);
            }

            DotFileWriter DW = new DotFileWriter(HDM.HasseDiagramNodes, "C:\\Users\\ssampath\\Documents\\HasseDiagramOutput\\testdotfile.dot");

            DW.LabelMode = labelMode.USE_NODE_KEY;
            DW.WriteDotFile();
            System.Diagnostics.Debug.WriteLine(HDM.RootNode.HashString());
            System.Diagnostics.Debug.WriteLine(HDM.HasseDiagramNodes.Count.ToString() + " Diagram objects");
            System.Diagnostics.Debug.WriteLine(HDM.DifferenceNodes.Count.ToString() + " Difference objects");
            //System.Diagnostics.Debug.WriteLine(HasseDiagramStats.Report(HDM.HasseDiagramNodes));
        }
Esempio n. 54
0
        //Legge dal server una riga
        public String readLine()
        {
            String returndata = streamReader.ReadLine();

            return(returndata);
        }
Esempio n. 55
0
        private void BtnZaloguj_Click(object sender, RoutedEventArgs e)
        {
            //Zczytywanie data z pliku
            DateTime dataTeraz = DateTime.Now;                                            //pobieram obecną datę w celu porównania z tą w pliku
            string   dataWpliku;                                                          //kontener na datę z dokumentu

            System.IO.StreamReader dataTXT = new System.IO.StreamReader("DataKopii.txt"); //Wskazanie pliku dla StreamReadera

            MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder(); //Obiekt tworzący łańcuch połączeniowy z bazą

            connString.Server   = "DESKTOP-OBR3EBS" /*"LAPTOP-EEGICNKI"*/;                //Przekazanie nazwy serwera,
            connString.Database = "KartotekaAdamPosluszny";                               //nazwy bazy danych,
            string login = txtLogin.Text;

            if (login.EndsWith("1"))
            {
                string[] loginStr = login.Split(' ');
                connString.UserID = loginStr[0];
                blokuj            = 1;
            }
            else
            {
                connString.UserID = login;
            }
            connString.Password = pswHaslo.Password;                  //oraz hasła do łańcucha połączeniowego

            conn = new MySqlConnection(connString.ConnectionString);  //Przekazanie łańcucha do obiektu conn

            try                                                       //Próba nawiązania połączenia z bazą
            {
                dataWpliku = dataTXT.ReadLine();                      //odczytanie 1 linii z pliku DataKopii.txt
                dataTXT.Close();                                      //zamknięcie pliku
                DateTime dataZpliku = Convert.ToDateTime(dataWpliku); //konwertuję datę z pliku na typ DateTime w celu porównania
                TimeSpan roznicaDat = dataTeraz - dataZpliku;         //tworze TimeSpana żeby zapisać różnicę między datami
                int      dni        = roznicaDat.Days;                //wyciągam całkowitą liczbę dni pomiędzy Datami

                conn.Open();                                          //Otwarcie połączenia z bazą

                if (dni > 30)                                         //jeżeli od ostatniego backupu minęło więcej niż 30 dni czyli miesiąc
                {
                    //Tu będzie kod robiący eksport bazy
                    string lokalizacjaKopii = /*NIE ZAPOMNIJ ZMIENIĆ ŚCIEŻKI*/ @"C:\Kartoteka\KopieBazy\" + dataTeraz.ToShortDateString() + "kartoteka.sql";   //ścieżka do pliku po eksporcie
                    using (MySqlCommand polecenie = new MySqlCommand())
                    {
                        using (MySqlBackup backup = new MySqlBackup(polecenie))     //Był potrzebny pakiet MySqlBackup.Net
                        {
                            polecenie.Connection = conn;
                            backup.ExportToFile(lokalizacjaKopii);
                        }
                    }
                    //i nadpisujący plik DataKopii.txt datą utworzenia
                    System.IO.StreamWriter dataTXTnadpisz = new System.IO.StreamWriter("DataKopii.txt", false); //StreamWriter z parametrem false nadpisuje cały plik
                    dataTXTnadpisz.Write(dataTeraz.ToString());                                                 //Zapisuję nową datę w pliku
                    dataTXTnadpisz.Close();                                                                     //zamykam plik
                    MessageBox.Show("Wykonano kopię bazy danych!");
                }


                PacjenciOsobowe pacjenciOsobowe = new PacjenciOsobowe(conn); //Utworzenie nowe obiektu klasy PacjenciOsobowe i przekazanie do niego połączenia conn
                pacjenciOsobowe.Show();                                      //Wywołanie metody Show dla obiektu pacjenciOsobowe
                this.Close();                                                //Zamknięcie okna logowania metodą Close
            }
            catch (MySqlException ex)                                        //Przechwycenie błędu połączenia z bazą
            {
                MessageBox.Show(ex.Message);                                 //Wyświetlenie treści błędu
            }
        }
Esempio n. 56
0
        public void ImportConfig(string filename)
        {
            if (!System.IO.File.Exists(filename))
            {
                System.Windows.Forms.MessageBox.Show("File does not exist!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return;
            }

            if (mMachineStatus == MacStatus.Idle)
            {
                try
                {
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
                    {
                        lock (this)
                        {
                            mSentPtr  = new System.Collections.Generic.List <IGrblRow>();                            //assign sent queue
                            mQueuePtr = new System.Collections.Generic.Queue <GrblCommand>();

                            string rline = null;
                            while ((rline = sr.ReadLine()) != null)
                            {
                                if (rline.StartsWith("$"))
                                {
                                    mQueuePtr.Enqueue(new GrblCommand(rline));
                                }
                            }
                        }

                        try
                        {
                            sr.Close();
                            while (com.IsOpen && (mQueuePtr.Count > 0 || mPending.Count > 0))                             //resta in attesa del completamento della comunicazione
                            {
                                ;
                            }

                            int errors = 0;
                            foreach (IGrblRow row in mSentPtr)
                            {
                                if (row is GrblCommand)
                                {
                                    if (((GrblCommand)row).Result != "OK")
                                    {
                                        errors++;
                                    }
                                }
                            }

                            if (errors > 0)
                            {
                                System.Windows.Forms.MessageBox.Show(String.Format("{0} Config imported with {1} errors!", mSentPtr.Count, errors), "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show(String.Format("{0} Config imported with success!", mSentPtr.Count), "Success", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                            }
                        }
                        catch { System.Windows.Forms.MessageBox.Show("Error reading file!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); }

                        lock (this)
                        {
                            mQueuePtr = mQueue;
                            mSentPtr  = mSent;                            //restore queue
                        }
                    }
                }
                catch { System.Windows.Forms.MessageBox.Show("Error reading file!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); }
            }
        }
        static void Main(string[] args)
        {
            List <List <string> > list     = new List <List <string> >();
            List <List <string> > data     = new List <List <string> >();
            List <string>         triangle = new List <string>();

            List <List <string> > distance = new List <List <string> >();

            List <List <string> > classList2 = new List <List <string> >();
            List <string>         classList  = new List <string>();
            List <List <string> > knnList    = new List <List <string> >();

            List <string> classIf = new List <string>();

            List <List <string> > countClassElements = new List <List <string> >();
            List <List <string> > average2           = new List <List <string> >();
            List <string>         average            = new List <string>();

            int countClass, min = 0, options = 0;

            kNNn();

            for (int i = 0; i < list.Count - 2; i++)
            {
                sorting(distance[i][0], min);
            }

            Console.WriteLine($"{triangle[triangle.Count-1]} - {distance[distance.Count-1][1]}");


            void kNNn()
            {
                int    counter = 0;
                string line;

                System.IO.StreamReader file = new System.IO.StreamReader(@"F:\kNNn.txt");
                while ((line = file.ReadLine()) != null)
                {
                    list.Add(new List <string> {
                        line
                    });
                    pars(counter, line);
                    counter++;
                }
                file.Close();

                Console.WriteLine("Данные");
                foreach (List <string> subList in list)
                {
                    foreach (string item in subList)
                    {
                        Console.Write(" " + item);
                    }
                    Console.WriteLine();
                }

                for (int i = 0; i < data[data.Count - 1].Count - 1; i++)
                {
                    if (i == 0)
                    {
                        classList.Add(data[data.Count - 1][i]);
                    }
                    if (data[data.Count - 1][i] != data[data.Count - 1][i + 1])
                    {
                        classList.Add(data[data.Count - 1][i + 1]);
                    }
                }

                centeringСlassification();

                distanceСalculation();

                countClass = classList.Count;

                for (int i = 0; i < countClass; i++)
                {
                    classIf.Add(0.ToString());
                }
            }

            void pars(int counter, string str)
            {
                string str1       = "";
                int    param      = 0;
                int    paramStart = 0;

                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] == ' ')
                    {
                        if (counter == 0)
                        {
                            data.Add(new List <string> {
                            });
                        }
                        param++;
                    }
                }

                options = param;

                if (counter == 0)
                {
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (param != 0)
                        {
                            for (int j = i; j < str.Length; j++)
                            {
                                if (str[j] != ' ')
                                {
                                    str1 += str[j];
                                }
                                if (str[j] == ' ')
                                {
                                    triangle.Add(str1);
                                    str1 = null;
                                    paramStart++;
                                    i = j;
                                    break;
                                }
                            }
                            param--;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if (counter > 0)
                {
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (param != 0)
                        {
                            for (int j = i; j < str.Length; j++)
                            {
                                if (str[j] != ' ')
                                {
                                    str1 += str[j];
                                }
                                if (str[j] == ' ')
                                {
                                    data[paramStart].Add(str1);
                                    str1 = null;
                                    paramStart++;
                                    i = j;
                                    break;
                                }
                            }
                            param--;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            void centeringСlassification()
            {
                double sumA  = 0;
                int    check = 0;
                int    count = -1;

                for (int i = 0; i < classList.Count; i++)
                {
                    countClassElements.Add(new List <string> {
                    });
                    countClassElements[i].Add("0");
                    countClassElements[i].Add(classList[i]);


                    for (int j = 0; j < data[data.Count - 1].Count; j++)
                    {
                        if (classList[i] == data[data.Count - 1][j])
                        {
                            countClassElements[i][0] = (Convert.ToInt32(countClassElements[i][0]) + 1).ToString();
                        }
                    }
                }

                for (int a = 0; a < countClassElements.Count; a++)
                {
                    for (int j = 0; j < options - 1; j++)
                    {
                        average2.Add(new List <string> {
                        });

                        for (int i = 0; i < Convert.ToInt32(countClassElements[a][0]); i++)
                        {
                            sumA += Convert.ToDouble(data[j][i + check]);
                        }
                        count++;
                        average2[count].Add(Convert.ToDouble(sumA / Convert.ToDouble(countClassElements[a][0])).ToString());
                        average2[count].Add(countClassElements[a][1]);

                        sumA = 0;
                    }
                    check += Convert.ToInt32(countClassElements[a][0]);
                }
            }

            void distanceСalculation()
            {
                for (int i = 0; i < average2.Count - 1; i++)
                {
                    double distanceFormula = 0;
                    double sum             = 0;
                    for (int j = 0; j < options - 1; j++)
                    {
                        distanceFormula = Math.Pow((Convert.ToDouble(triangle[j]) - Convert.ToDouble(average2[i][0])), 2);
                        sum             = sum + distanceFormula;
                    }

                    distanceFormula = Math.Sqrt(sum);

                    distance.Add(new List <string> {
                    });
                    distance[i].Add(distanceFormula.ToString());
                    distance[i].Add(average2[i][1].ToString());
                }
            }

            void sorting(string kolon, int min1)
            {
                List <List <string> > temp = new List <List <string> >();

                for (int i = 0; i < distance.Count - 1; i++)
                {
                    bool f = false;
                    for (int j = 0; j < distance.Count - i - 1; j++)
                    {
                        if (Convert.ToDouble(distance[j + 1][0]) > Convert.ToDouble(distance[j][0]))
                        {
                            f = true;
                            temp.Add(distance[j + 1]);
                            distance[j + 1] = distance[j];
                            distance[j]     = temp[temp.Count - 1];
                        }
                    }
                    if (!f)
                    {
                        break;
                    }
                }
            }
        }
        private void getVoicesInEditor()
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            process.StartInfo.FileName  = Util.Config.TTS_MACOS;
            process.StartInfo.Arguments = "-v '?'";

            try
            {
                System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process, Util.Constants.DEFAULT_TTS_KILL_TIME));
                worker.Start();

                do
                {
                    System.Threading.Thread.Sleep(50);
                } while (worker.IsAlive || !process.HasExited);

                if (Util.Constants.DEV_DEBUG)
                {
                    Debug.Log("Finished after: " + (process.ExitTime - process.StartTime).Seconds);
                }

                if (process.ExitCode == 0)
                {
                    System.Collections.Generic.List <Model.Voice> voices = new System.Collections.Generic.List <Model.Voice>(100);

                    using (System.IO.StreamReader streamReader = process.StandardOutput)
                    {
                        string reply;
                        string name;

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

                            if (!string.IsNullOrEmpty(reply))
                            {
                                System.Text.RegularExpressions.Match match = sayRegex.Match(reply);

                                if (match.Success)
                                {
                                    name = match.Groups[1].ToString();
                                    voices.Add(new Model.Voice(match.Groups[1].ToString(), match.Groups[3].ToString(), Util.Helper.AppleVoiceNameToGender(name), "unknown", match.Groups[2].ToString().Replace('_', '-')));
                                }
                            }
                        }
                    }

                    cachedVoices = voices.OrderBy(s => s.Name).ToList();

                    if (Util.Constants.DEV_DEBUG)
                    {
                        Debug.Log("Voices read: " + cachedVoices.CTDump());
                    }
                }
                else
                {
                    using (System.IO.StreamReader sr = process.StandardError)
                    {
                        string errorMessage = "Could not get any voices: " + process.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                        Debug.LogError(errorMessage);
                    }
                }
            }
            catch (System.Exception ex)
            {
                string errorMessage = "Could not get any voices!" + System.Environment.NewLine + ex;
                Debug.LogError(errorMessage);
            }

            process.Dispose();
            onVoicesReady();
        }
Esempio n. 59
0
        public void AnalyzeFile(string filename)
        {
            System.IO.StreamReader sr = null;
            try
            {
                for (int i = 0; i < 30; i++)
                {
                    try
                    {
                        sr = new System.IO.StreamReader(filename, Encoding.Default);
                        break;
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.WriteLine(ee.Message);
                    }
                }
                if (sr == null)
                {
                    throw new ApplicationException("Could not open input file, copy error?");
                }
                string header = sr.ReadLine();

                string[] fields = header.Split(SplitChars);

                /*Detect OE format*/
                int fldID, fldSI, fldFName, fldEName, fldClub, fldClass, fldStart, fldTime, fldStatus, fldFirstPost, fldText1, fldText2, fldText3, fldFinish, fldLeg;
                int fldTotalTime;
                OxTools.DetectOxCSVFormat(OxTools.SourceProgram.OE, fields, out fldID, out fldSI, out fldFName, out fldEName, out fldClub, out fldClass, out fldStart, out fldTime, out fldStatus, out fldFirstPost, out fldLeg, out fldFinish, out fldText1, out fldText2, out fldText3, out fldTotalTime);

                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1 ||
                    fldStart == -1 || fldFirstPost == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }


                if (fldID == -1 || fldSI == -1 || fldFName == -1 || fldEName == -1 || fldClub == -1 || fldClass == -1 ||
                    fldStart == -1 || fldTime == -1)
                {
                    throw new System.IO.IOException("Not OE-formatted file!");
                }

                string tmp;
                while ((tmp = sr.ReadLine()) != null)
                {
                    string[] parts = tmp.Split(SplitChars);

                    /* check so that the line is not incomplete*/
                    int    id    = Convert.ToInt32(parts[fldID]);
                    string name  = parts[fldFName].Trim('\"') + " " + parts[fldEName].Trim('\"');
                    string club  = parts[fldClub].Trim('\"');
                    string Class = parts[fldClass].Trim('\"');
                    int    start = strTimeToInt(parts[fldStart]);
                    int    time  = strTimeToInt(parts[fldTime]);


                    int status = 0;
                    try
                    {
                        status = Convert.ToInt32(parts[fldStatus]);
                    }
                    catch
                    {
                    }

                    var splittimes = new List <ResultStruct>();
                    /*parse splittimes*/
                    var codes = new List <int>();
                    if (fldFirstPost >= 0)
                    {
                        for (int i = fldFirstPost; i < parts.Length - 4; i++)
                        {
                            if (parts[i + 1].Length == 0 ||
                                parts[i + 2].Length == 0)
                            {
                                i += 3;
                                continue;
                            }
                            var s = new ResultStruct();
                            try
                            {
                                //s.ControlNo = Convert.ToInt32(parts[i]);
                                i++;
                                s.ControlCode = Convert.ToInt32(parts[i]);

                                if (s.ControlCode == 999)
                                {
                                    i++;
                                    if (time == -1 && status == 0)
                                    {
                                        time = strTimeToInt(parts[i]);
                                    }

                                    i++;
                                }
                                else
                                {
                                    s.ControlCode += 1000;
                                    while (codes.Contains(s.ControlCode))
                                    {
                                        s.ControlCode += 1000;
                                    }
                                    codes.Add(s.ControlCode);

                                    i++;
                                    s.Time = strTimeToInt(parts[i]);
                                    i++;

                                    if (s.Time > 0)
                                    {
                                        s.Place = 0;
                                        try
                                        {
                                            s.Place = Convert.ToInt32(parts[i]);
                                        }
                                        catch
                                        { }

                                        splittimes.Add(s);
                                    }
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    FireOnResult(new Result {
                        ID         = id,
                        RunnerName = name,
                        RunnerClub = club,
                        Class      = Class,
                        StartTime  = start,
                        Time       = time,
                        Status     = status,
                        SplitTimes = splittimes
                    });
                }
            }
            catch (Exception ee)
            {
                FireLogMsg("ERROR in OEPArser: " + ee.Message);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
        }
Esempio n. 60
0
        public static MeshData ReadObj(string filePath)
        {
            //按顺序存放所有 顶点坐标
            List <Vector3> tempVertexVector = new List <Vector3>();
            //按顺序存放所有 顶点法线
            List <Vector3> tempNormalVector = new List <Vector3>();
            //字典类型,key是顶点 位置序号 ,value是顶点对应的 法向量序号
            var mapVerNum2NorNum = new Dictionary <int, int>();
            //按顺序存放所有 法线索引
            List <int> vertexIndice = new List <int>();
            //MeshData顶点索引
            string line;

            string[] strs;
            string[] temp;
            System.IO.StreamReader file = new System.IO.StreamReader(filePath);
            while ((line = file.ReadLine()) != null)
            {
                strs = line.Split(' ');
                //按顺序添加顶点位置->按顺序添加顶点法向量->按顺序添加三角形片面,并完成位置<->法向量映射表
                if (strs[0] == "v")
                {
                    tempVertexVector.Add(new Vector3(float.Parse(strs[1]), float.Parse(strs[2]), float.Parse(strs[3])));
                }
                else if (strs[0] == "vn")
                {
                    tempNormalVector.Add(new Vector3(float.Parse(strs[1]), float.Parse(strs[2]), float.Parse(strs[3])));
                }
                else if (strs[0] == "f")
                {
                    //处理一个3顶点片面
                    if (strs.Length == 4)
                    {
                        temp = strs[1].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(int.Parse(temp[0]));
                        temp = strs[2].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(int.Parse(temp[0]));
                        temp = strs[3].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(int.Parse(temp[0]));
                    }
                    else
                    {
                        //处理一个四顶点片面
                        temp = strs[1].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(int.Parse(temp[0]));
                        temp = strs[2].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(int.Parse(temp[0]));
                        temp = strs[3].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(int.Parse(temp[0]));
                        temp = strs[4].Split('/');
                        mapVerNum2NorNum[int.Parse(temp[0])] = int.Parse(temp[2]);
                        vertexIndice.Add(vertexIndice[vertexIndice.Count - 1]);
                        vertexIndice.Add(int.Parse(temp[0]));
                        vertexIndice.Add(vertexIndice[vertexIndice.Count - 5]);
                    }
                }
            }
            List <MyVertex> outMyVertex = new List <MyVertex>(tempVertexVector.Count);

            foreach (int key in mapVerNum2NorNum.Keys)
            {
                outMyVertex.Add(new MyVertex()
                {
                    Position = tempVertexVector[key - 1],
                    Normal   = tempNormalVector[mapVerNum2NorNum[key] - 1],
                });
            }
            MeshData meshData = new MeshData(outMyVertex.Count, vertexIndice.Count);

            meshData.Vertices = outMyVertex.ToArray();
            meshData.Indices  = vertexIndice.ToArray();
            return(meshData);
        }