Peek() private method

private Peek ( ) : int
return int
Example #1
0
        private IEnumerable<Record> ReadRecords(string fileName)
        {
            var stringBuilder = new StringBuilder();

            using (var reader = new StreamReader(fileName))
            {
                ReadOnlyCollection<string> header;
                if (reader.Peek() >= 0)
                {
                    var first = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray();

                    header = new ReadOnlyCollection<string>(first);
                }
                else
                {
                    yield break;
                }

                for (var i = 0; i < this._numberRecordsToSkip && reader.Peek() >= 0; i++)
                {
                    reader.ReadLine();
                }

                while (reader.Peek() >= 0)
                {
                    var items = this.ParseLine(reader.ReadLine(), stringBuilder).ToArray();

                    yield return new Record(header, items);
                }
            }
        }
Example #2
0
 public static void AddCurrentRow(int oneChar, StreamReader DataStream)
 {
     if (oneChar == 10 && DataStream.Peek() == 13) { DataStream.Read(); }
     else if (oneChar == 13 && DataStream.Peek() == 10) { DataStream.Read(); }
     CurrentRow += 1;
     CurrentColumn = 0;
 }
Example #3
0
        /// <summary>
        /// 将Csv读入DataTable
        /// </summary>
        /// <param name="filePath">csv文件路径</param>
        /// <param name="n">表示第n行是字段title,第n+1行是记录开始</param>
        public static DataTable CsvToDt(string filePath, int n)
        {
            DataTable dt = new DataTable();
            StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, false);
            int i = 0;
            int m = 0;
            reader.Peek();
            while (reader.Peek() > 0)
            {
                m = m + 1;
                string str = reader.ReadLine();
                if (m >= n + 1)
                {
                    string[] split = str.Split(',');

                    System.Data.DataRow dr = dt.NewRow();
                    for (i = 0; i < split.Length; i++)
                    {
                        dr[i] = split[i];
                    }
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
Example #4
0
        /// <summary>
        ///     将CSV格式的流读入table
        /// </summary>
        /// <param name="ms">数据流</param>
        /// <param name="n">整型值</param>
        /// <returns>DataTable</returns>
        public static DataTable Csv2DataTable(MemoryStream ms, int n)
        {
            var dt = new DataTable();
            using (var reader = new StreamReader(ms))
            {
                int i = 0, m = 0;
                reader.Peek();
                while (reader.Peek() > 0)
                {
                    m = m + 1;
                    string str = reader.ReadLine();
                    if (m >= n + 1)
                    {
                        string[] split = str.Split(',');

                        DataRow dr = dt.NewRow();
                        for (i = 0; i < split.Length; i++)
                        {
                            dr[i] = split[i];
                        }
                        dt.Rows.Add(dr);
                    }
                }
                return dt;
            }
        }
Example #5
0
        public static String ProcessDigit(int FirstCharactor, StreamReader DataStream)
        {
            StringBuilder theNumber = new StringBuilder();
            theNumber.Append((char)FirstCharactor);
            int peekedChar;
            //43 + 45 - 46 .
            while (((peekedChar = DataStream.Peek()) >= 48 && peekedChar <= 57)
                || peekedChar == 46)
            {
                theNumber.Append((char)DataStream.Read());
            }

            if (peekedChar == 69) // E
            {
                theNumber.Append((char)DataStream.Read());
                if ((peekedChar = DataStream.Peek()) == 43 || peekedChar == 45)
                {
                    theNumber.Append((char)DataStream.Read());
                }
                while ((peekedChar = DataStream.Peek()) >= 48 && peekedChar <= 57)
                {
                    theNumber.Append((char)DataStream.Read());
                }
            }
            return theNumber.ToString();
            //Console.WriteLine(theNumber);
        }
 public virtual List<student> ReadAll(string fileName)
 {
     FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
     StreamReader sr = new StreamReader(file);
     List<student> result = new List<student>();
     if (Indexed)
     {
         FileStream fs = new FileStream("Index.txt", FileMode.Open, FileAccess.Read);
         StreamReader Sr = new StreamReader(fs);
         if (Sr.Peek() != -1)
             CurrentIndexVal1 = int.Parse(Sr.ReadLine());
         while (Sr.Peek() != -1)
         {
             CurrentIndexVal2 = int.Parse(Sr.ReadLine());
             student std = this.Read(sr);
             result.Add(std);
             CurrentIndexVal1 = CurrentIndexVal2;
         }
     }
     else
     {
         while (sr.Peek() != -1)
         {
             student std = this.Read(sr);
             result.Add(std);
         }
     }
     sr.Close();
     return result;
 }
Example #7
0
        public void Split()
        {
            int split_num = 1;
            string destFilePart = Path.Combine(_opts.WorkingDirectory, string.Format(_opts.SplitFilePattern, split_num));
            StreamWriter sw = new StreamWriter(destFilePart);
            long read_line = 0;
            using (StreamReader sr = new StreamReader(_opts.InputFileName))
            {
                while (sr.Peek() >= 0)
                {

                    // Progress reporting
                    //if (++read_line % rowDivider == 0)
                    //    Console.Write("{0:f2}%   \r",
                    //      100.0 * sr.BaseStream.Position / sr.BaseStream.Length);

                    // Copy a line
                    sw.WriteLine(sr.ReadLine());

                    // If the file is big, then make a new split,
                    // however if this was the last line then don't bother
                    if (read_line / split_num > _opts.FileSizeDivider && sr.Peek() >= 0)
                    {
                        sw.Close();
                        destFilePart = Path.Combine(_opts.WorkingDirectory, string.Format(_opts.SplitFilePattern, split_num++));
                        sw = new StreamWriter(destFilePart);
                    }
                }
            }
            sw.Close();
        }
Example #8
0
        private string ReadNumber(StreamReader FileReader)
        {
            string TempString = "";
            while ((FileReader.Peek() >= 0) && ((Char.IsNumber((char)FileReader.Peek()))
                || ((char)FileReader.Peek() == '.')))
            {

                TempString += (char)FileReader.Read();
            }
            if ((((char)FileReader.Peek()) == 'E') || (((char)FileReader.Peek()) == 'e'))
            {
                TempString += (char)FileReader.Read();
                while (Char.IsNumber((char)FileReader.Peek()))
                {
                    TempString += (char)FileReader.Read();
                }
                if ((((char)FileReader.Peek()) == '+') || (((char)FileReader.Peek()) == '-'))
                {
                    TempString += (char)FileReader.Read();
                    while (Char.IsNumber((char)FileReader.Peek()))
                    {
                        TempString += (char)FileReader.Read();
                    }

                }

            }
            return TempString;
        }
        public static List<Employee> LoadEntries()
        {
            List<Employee> list = null;

            try {
                using (FileStream fileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read)) {
                    using (StreamReader reader = new StreamReader(fileStream)) {

                        //Populate List from lines in file
                        list = new List<Employee>();
                        while (reader.Peek() != -1) {
                            Employee employee = new Employee();

                            for (int i = 0; i <= 3; i++) {
                                string line;

                                if (reader.Peek() != -1) {
                                    line = reader.ReadLine();
                                } else {
                                    break;
                                }

                                switch (i) {
                                    case 0:
                                        employee.firstName = line;
                                        break;

                                    case 1:
                                        employee.lastName = line;
                                        break;

                                    case 2:
                                        employee.employeeID = Convert.ToInt32(line.Substring(2));
                                        break;

                                    case 3:
                                        employee.department = line;
                                        break;
                                }
                            }

                            list.Add(employee);

                            if (reader.Peek() != -1) {
                                reader.ReadLine();
                            }
                        }
                    }
                }
            } catch (FileNotFoundException) {
                MessageBox.Show("File not found: " + inputFile, "File Error");
            } catch (DirectoryNotFoundException) {
                MessageBox.Show("Directory not found: " + inputDir, "Directory Error");
            } catch (IOException ex) {
                MessageBox.Show(ex.GetType() + ": " + ex.Message, "IOException");
            }

            return list;
        }
Example #10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Enter filepath to read from");
            var inputFile = Console.ReadLine();
            var inputFileName = string.IsNullOrWhiteSpace(inputFile) ? @"C:\users\vshardul\desktop\testRunEntries.txt" : inputFile;

            Console.WriteLine("Enter output filepath");
            var outputFile = Console.ReadLine();
            var outputFileName = string.IsNullOrWhiteSpace(outputFile) ? @"Output.txt" : outputFile;

            Console.WriteLine("Entries to ignore - ");
            var entriesToIgnore = long.Parse(Console.ReadLine());

            if (!File.Exists(inputFileName))
            {
                Console.WriteLine("Invalid input file path");
                return;
            }

            using (var inputStream = new StreamReader(inputFileName))
            {
                if (inputStream.Peek() < 0)
                {
                    Console.WriteLine("Enpty Stream");
                    return;
                }

                var headerRow = inputStream.ReadLine();

                int ignoreCount = 0;
                while (ignoreCount < entriesToIgnore && inputStream.Peek() >= 0)
                {
                    inputStream.ReadLine();
                    ignoreCount++;
                }

                using (var outputStream = new StreamWriter(outputFileName))
                {
                    outputStream.WriteLine(headerRow);
                    while (inputStream.Peek() >= 0)
                    {
                        var line = inputStream.ReadLine();
                        if (line != null && line.Split('\t').Length == headerRow.Split('\t').Length)
                        {
                            outputStream.WriteLine(line);
                        }
                    }

                    outputStream.Close();
                }

                inputStream.Close();
            }

            Console.WriteLine("File content trnafer successfull");
        }
Example #11
0
 /// <summary>
 /// 从CSV文件总获取联系人的方法
 /// </summary>
 /// <param name="fileStream">CSV文件流</param>
 /// <returns>联系人字典</returns>
 public static Dictionary<string, string> GetContactAccessor(Stream fileStream)
 {
     System.IO.StreamReader reader = new System.IO.StreamReader(fileStream, Encoding.Default);
     Dictionary<string, string> contacts = new Dictionary<string, string>(); //存放读取出来的csv联系人
     //根据表头确定联系人的名字在什么地方。
     int lastNameIndex = -1;
     int firstNameIndex = -1;
     if (reader.Peek() > 0)
     {
         string contact = reader.ReadLine();
         contact = contact.Replace("\"", "");
         string[] contactArray = contact.Split(new char[] { ',' });
         for (int i = 0; i < contactArray.Length; i++)
         {
             if (string.IsNullOrEmpty(contactArray[i]))
                 continue;
             switch (contactArray[i].ToLower())
             {
                 case "姓名":
                     lastNameIndex = i;
                     break;
                 case "name":
                     lastNameIndex = i;
                     break;
                 case "名":
                     lastNameIndex = i;
                     break;
                 case "姓":
                     firstNameIndex = i;
                     break;
                 default:
                     break;
             }
         }
     }
     //循环获取联系人名和Email信息
     while (reader.Peek() > 0)
     {
         string contact = reader.ReadLine();
         contact = contact.Replace("\"", "");
         string[] contactArray = contact.Split(new char[] { ',' });
         string name = string.Empty;
         if (firstNameIndex != -1)
             name += contactArray[firstNameIndex];
         if (lastNameIndex != -1)
             name += contactArray[lastNameIndex];
         Regex regex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
         Match match = regex.Match(contact);
         string email = null;
         if (match.Success)
             email = match.Value;
         if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(name))
             contacts[email] = name;
     }
     return contacts;
 }
Example #12
0
 public String ReadAndDecode(StreamReader sr)
 {
     String ts=sr.ReadLine();
     while((sr.Peek()==9)||(sr.Peek()==32))
     {
         sr.Read();
         ts=ts+'\r'+'\n'+sr.ReadLine();
     }
     return Decode(ts);
 }
Example #13
0
 public int GetStreamDigits(StreamReader sr, int count=2)
 {
     char inp; string nums="";
     if(count<1||sr==null||sr.Peek()<0) return -1;
     while(nums.Length<count && sr.Peek()>=0) {
         do { inp=(char)sr.Read(); } while(!Char.IsDigit(inp) && sr.Peek()>=0);
         if(Char.IsDigit(inp)) nums+=inp;
     }
     return nums.Length>0?int.Parse(nums):-1;
 }
Example #14
0
		public void Formatting()
		{
			var o = DFormattingOptions.CreateDStandard();
			
			bool isTargetCode = false;
			
			var rawCode = string.Empty;
			var sb = new StringBuilder();
			var l = new List<Tuple<string,string>>();
			
			using(var st = Assembly.GetExecutingAssembly().GetManifestResourceStream("formatterTests")){
				using(var r = new StreamReader(st))
				{
					int n;
					while((n=r.Read()) != -1)
					{
						if((n == ':' && r.Peek() == ':') || (n == '#' && r.Peek() == '#'))
						{
							r.ReadLine();
							
							if(n == '#')
							{								
								if(isTargetCode)
								{
									l.Add(new Tuple<string,string>(rawCode, sb.ToString().Trim()));
									sb.Clear();
								}
								else
								{
									rawCode = sb.ToString().Trim();
									sb.Clear();
								}
								
								isTargetCode = !isTargetCode;
							}
						}
						else if(n == '\r' || n == '\n')
						{
							sb.Append((char)n);
						}
						else
						{
							sb.Append((char)n);
							sb.AppendLine(r.ReadLine());
						}
					}
				}
			}
			
			foreach(var tup in l)
			{
				Fmt(tup.Item1, tup.Item2, o);
			}
		}
        public static int CountProteins(FileStream proteinFastaDatabase, bool onTheFlyDecoys, out int targetProteins, out int decoyProteins, out int onTheFlyDecoyProteins)
        {
            targetProteins = 0;
            decoyProteins = 0;
            onTheFlyDecoyProteins = 0;

            StreamReader fasta = new StreamReader(proteinFastaDatabase);

            string description = null;

            while(true)
            {
                string line = fasta.ReadLine();

                if(line.StartsWith(">"))
                {
                    description = line.Substring(1);
                }

                if(fasta.Peek() == '>' || fasta.Peek() == -1)
                {
                    if(description.Contains(Protein.DECOY_IDENTIFIER))
                    {
                        if(onTheFlyDecoys)
                        {
                            throw new ArgumentException(proteinFastaDatabase.Name + " contains decoy proteins; database should not contain decoy proteins when \"create target–decoy database on the fly\" option is enabled");
                        }
                        decoyProteins++;
                    }
                    else
                    {
                        targetProteins++;
                        if(onTheFlyDecoys)
                        {
                            onTheFlyDecoyProteins++;
                        }
                    }

                    description = null;

                    if(fasta.Peek() == -1)
                    {
                        break;
                    }
                }
            }

            proteinFastaDatabase.Seek(0, SeekOrigin.Begin);

            return targetProteins + decoyProteins + onTheFlyDecoyProteins;
        }
Example #16
0
 /// <summary>
 /// Updates the PlayerControls from the given file
 /// </summary>
 /// <param name="file">file to update from</param>
 public void UpdateFromFile(System.IO.StreamReader file)
 {
     if (file.Peek() >= 0)
     {
         Options.Get().levelStatic = System.Convert.ToBoolean(file.ReadLine());
     }
     foreach (PlayerControls item in players)
     {
         if (file.Peek() >= 0)
         {
             item.UpdateFromString(file.ReadLine());
         }
     }
 }
Example #17
0
        void ConsumeEmptyLines(StreamReader stream)
        {
            while(
               (stream.Peek() == '\n' ||
                stream.Peek() == '\r' ||
                stream.Peek() == '\f') &&
                stream.Peek() > -1)
            {
                if(stream.EndOfStream)
                    break;
                stream.ReadLine();

                // Console.WriteLine("QACategory removing nonessential line: " + stream.ReadLine());
            }
        }
Example #18
0
    private string archivoFiltrado(string ruta)
    {
        string estado = "";

        try
        {
            System.IO.StreamReader filtrado        = System.IO.File.OpenText(ruta + ".txt");
            System.IO.StreamWriter ArchivoSalida_F = new System.IO.StreamWriter(ruta + "Final.txt");
            string fila_F = "";
            while (filtrado.Peek() > -1)
            {
                fila_F = filtrado.ReadLine();
                ArchivoSalida_F.WriteLine(fila_F.Replace("�", "").Replace("0//", "") + ";" + fecha_scac + ";" + Nom_SCAC + ";" + Ciclo_SCAC);
            }
            ArchivoSalida_F.Close();
            filtrado.Close();
            if (Vaciar() == 0)
            {
                estado = subirAlServidor(ruta + "Final.txt", Nom_SCAC);
            }
            else
            {
                estado = "Problemas con la Tabla Temporal. Intente de Nuevo por Favor.";
            }
        }
        catch (Exception msj)
        {
            estado = "Archivo Filtrado " + msj.Message;
        }
        return(estado);
    }
Example #19
0
        public static void Load()
        {
            
            if (Directory.Exists(baseAccountPath) == false)
                Directory.CreateDirectory(baseAccountPath);
            
            Account = AccountSettings.Load(baseAccountPath + "\\Accounts.xusr");

            IExtendFramework.Text.INIDocument doc = null;
            if (!File.Exists(baseAccountPath + "\\..\\Settings.ini"))
            {
                doc = new IExtendFramework.Text.INIDocument();
                doc["general"]["WaitToCheckForEmailSeconds"] = 30000.ToString();
                doc.Save(baseAccountPath + "\\..\\Settings.ini");
            }
            doc = new IExtendFramework.Text.INIDocument(baseAccountPath + "\\..\\Settings.ini");
            WaitToCheckForEmailSeconds = doc.GetInt32("general", "WaitToCheckForEmailSeconds");

            string base2 = baseAccountPath + "\\..\\Emails.list"; // up one folder
            if (!File.Exists(base2))
            {
                using (StreamWriter sw = new StreamWriter(base2))
                {
                    sw.WriteLine(Account.Accounts[0].EmailAddress);
                    sw.Close();
                }
            }
            StreamReader sr = new StreamReader(base2);
            while (sr.Peek() != -1)
                Emails.Add(sr.ReadLine());
            sr.Close();
        }
Example #20
0
        public static List<Calendar> LoadCalendarList(string path, DateTime week)
        {
            List<string> list = new List<string>(); //lijst van alle regels
            List<Calendar> calendarlist = new List<Calendar>();

            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    list.Add(sr.ReadLine()); //txt opsplitsen per lijn
                }
                Console.WriteLine("Calender loaded");
            }

            int count = 13; //aantal velden in regel
            for (int i = 0; i < list.Count; i++)
            {
                string[] item = new string[count];
                item = list[i].Split(new char[] { '\t' }); //regel opsplitsen per tab

                Calendar c = new Calendar();
                c.Teachers = c.MakeArray(item[3]); //3 = docent
                c.Abbreviation = item[4]; //4 = afkorting
                c.Subject = item[5]; //5 = onderwerp
                c.Classes = c.MakeArray(item[6]); //6 = klas
                c.Classrooms = c.MakeArray(item[7]); //7 = lokaal
                c.Departments = c.MakeDepartments(c.Classes);
                c.Start = c.MakeStart(week, item[12], item[13]); //12 = dag, 13 = startuur
                c.End = c.MakeEnd(c.Start, item[1]); //1 = duur

                calendarlist.Add(c);
            }

            return calendarlist;
        }
        // <summary>
        /// The extract trades.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        /// <exception cref="InvalidDataException">
        /// </exception>
        public override async Task<List<Trade>> ExtractTrades(Stream source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            List<Trade> returnList = new List<Trade>();

            using (var sr = new StreamReader(source))
            {
                while (sr.Peek() > -1)
                {
                    var line = sr.ReadLine().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    try
                    {
                        var trade = this.ExtractTrade(line);
                        returnList.Add(trade);
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidDataException("Provided data is of invalid format", ex);
                    }                  
                }  
            }

            return returnList;
        }
Example #22
0
 public static void Load()
 {
     string file = System.IO.Directory.GetCurrentDirectory() + "\\DataArrays\\Lore.txt";
     FileStream strLib = File.Open(file, FileMode.Open);
     using (StreamReader read = new StreamReader(strLib, Encoding.UTF7))
     {
         while (read.Peek() >= 0)
         {
             Lore toAdd = new Lore(read.ReadLine());
             if (!Categories.Contains(toAdd.Category))
             {
                 Categories.Add(toAdd.Category);
             }
             if(!CategoryLists.ContainsKey(toAdd.Category))
             {
                 CategoryLists.Add(toAdd.Category, new List<Lore>());
             }
             CategoryLists[toAdd.Category].Add(toAdd);
             _library.Add(toAdd.Id, toAdd);
             _sortedLores.Add(toAdd);
         }
     }
     Categories.Sort();
     _sortedLores.Sort();
 }
Example #23
0
 public string ParseFileReadValue(string key)
 {
     using (StreamReader reader =
         new StreamReader(_iniFileName))
     {
         do
         {
             string line = reader.ReadLine();
             Match match =
                 _iniKeyValuePatternRegex.Match(line);
             if (match.Success)
             {
                 string currentKey =
                     match.Groups["Key"].Value as string;
                 if (currentKey != null &&
                     currentKey.Trim().CompareTo(key) == 0)
                 {
                     string value =
                         match.Groups["Value"].Value as string;
                     return value;
                 }
             }
         } while (reader.Peek() != -1);
     }
     return null;
 }
Example #24
0
    public static void Main()
    {
        if (System.IO.File.Exists(Filename))
        {
            sr = new System.IO.StreamReader(Filename);

            while (sr.Peek() > 0)
            {
                aLine     = sr.ReadLine();
                aLine     = aLine.Replace("\"", "");
                LineArray = aLine.Split(',');
                foreach (string item in LineArray)
                {
                    NameList.Add(item);
                }
            }

            NameList.Sort();
            sum = 0;

            for (int i = 0; i <= NameList.Count - 1; i++)
            {
                encodedBytes = Encoding.ASCII.GetBytes(NameList[i]);

                foreach (byte b in encodedBytes)
                {
                    WordSum  = 0;
                    WordSum += (b - 64);
                    sum     += (i + 1) * WordSum;
                }
            }
            Console.Write(System.Convert.ToString(sum) + "\n");
            //Answer: 871198282
        }
    }
Example #25
0
        //获取远程服务器ATN结果,验证是否是支付宝服务器发来的请求
        public static string GetHttp(string aStrUrl, int timeout)
        {
            string strResult;
            try
            {
                var myReq = (HttpWebRequest)WebRequest.Create(aStrUrl);
                myReq.Timeout = timeout;
                var httpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = httpWResp.GetResponseStream();
                var sr = new StreamReader(myStream, Encoding.Default);
                var strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }

                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {

                strResult = "错误:" + exp.Message;
            }

            return strResult;
        }
Example #26
0
		    public bool Check(string code) {
			    using (var reader = new StreamReader(env.ROOT + "lib" + env.DELIM + "colors.csv")) {
				    while (reader.Peek() != -1) {
					    string[] line = reader.ReadLine().Split(',');
					    if (code.Split(new string[] { ",", "-" }, StringSplitOptions.None).Length == 3) {
						    string[] temp = code.Split(new string[] { ",", "-" }, StringSplitOptions.None);
						    if (line[1] == String.Format("{0}-{1}-{2}", temp[0], temp[1], temp[2])) 
                                return true;
					    } else if (code[1] == '#') {
						    string temp = code.Substring(1, code.Length - 1);
						    if (line[2].Substring(1, line[2].Length - 1) == temp) 
                                return true;
					    } else {
						    string letters = String.Empty;
						    for (int i = 0; i < code.Length; ++i) {
							    char c = char.ToLower(code[i]);
							    if ((int)c < 122 && (int)c > 97) 
                                    letters += c.ToString();
						    }
                            if (letters.Length == code.Length && letters == code)
                                return true;
					    }
				    }
				    reader.Dispose();
			    }
			    return false;
		    }
Example #27
0
 private void GetNameList()
 {
     string strFile = m_rootPath + "Record.txt";
     try
     {
         if (File.Exists(strFile))
         {
             using (StreamReader sr = new StreamReader(strFile,Encoding.GetEncoding("gb2312")))
             {
                 ArrayList str_list = new ArrayList();
                 while (sr.Peek() >= 0)
                 {
                     string str = sr.ReadLine();
                     str_list.Add(str);                            
                 }
                 int count=str_list.Count;
                 m_nameList = str_list.GetRange(3, count - 3);
             }
         }
     }
     catch (System.Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Example #28
0
        //------------------------------------------------------------------------------
        // buildLoadInfo
        //
        // Extract the map description from the .mis file
        //------------------------------------------------------------------------------

        public static void BuildLoadInfo(string mission)
        {
            //Replaced the torque file stuff w/ csharp, less stuff inside of torque.
            ClearLoadInfo();
            string missionpath = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "\\" + mission.Replace("/", "\\");
            if (File.Exists(missionpath))
                {
                string infoObject = "";
                using (StreamReader sr = new StreamReader(missionpath))
                    {
                    bool inInfoBlock = false;
                    while (sr.Peek() >= 0)
                        {
                        string line = sr.ReadLine();
                        if (line.Trim().StartsWith("new ScriptObject(MissionInfo) {"))
                            inInfoBlock = true;
                        if (line.Trim().StartsWith("new LevelInfo(theLevelInfo) {"))
                            inInfoBlock = true;
                        else if (inInfoBlock && line.Trim().StartsWith("};"))
                            {
                            inInfoBlock = false;
                            infoObject += line;
                            break;
                            }
                        if (inInfoBlock)
                            infoObject += line + " ";
                        }
                    }
                omni.console.Eval(infoObject);
                }
            else
                omni.console.error(string.Format("Level File {0} not found.", mission));
        }
Example #29
0
    /// <summary>
    /// Reads the class names.
    /// </summary>
    /// <returns>The class names.</returns>
    /// <param name="filename">Filename.</param>
    private List <string> readClassNames(string filename)
    {
        List <string> classNames = new List <string>();

        System.IO.StreamReader cReader = null;
        try
        {
            cReader = new System.IO.StreamReader(filename, System.Text.Encoding.Default);

            while (cReader.Peek() >= 0)
            {
                string name = cReader.ReadLine();
                classNames.Add(name);
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError(ex.Message);
            return(null);
        }
        finally
        {
            if (cReader != null)
            {
                cReader.Close();
            }
        }

        return(classNames);
    }
Example #30
0
        public static List<Customer> GetCustomers()
        {
            // if the directory doesn't exist, create it
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            // create the object for the input stream for a text file
            StreamReader textIn =
                new StreamReader(
                    new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

            // create the array list for customers
            List<Customer> customers = new List<Customer>();

            // read the data from the file and store it in the ArrayList
            while (textIn.Peek() != -1)
            {
                string row = textIn.ReadLine();
                string[] columns = row.Split('|');
                Customer customer = new Customer();
                customer.FirstName = columns[0];
                customer.LastName = columns[1];
                customer.Email = columns[2];
                customers.Add(customer);
            }

            textIn.Close();

            return customers;
        }
Example #31
0
 private void ParseTests(StreamReader standardOutput, ITestCaseDiscoverySink discoverySink, IMessageLogger logger, string source)
 {
     string testcase = "";
     bool testsStarted = false;
     Regex testCaseMatch = new Regex(@".*\.$");
     while (standardOutput.Peek() != -1)
     {
         string line = standardOutput.ReadLine();
         if (!string.IsNullOrEmpty(line))
         {
             if (testCaseMatch.IsMatch(line))
             {
                 testsStarted = true;
                 testcase = line.Trim();
                 logger.SendMessage(TestMessageLevel.Informational, string.Format("Found test case {0}", testcase.Trim('.')));
             }
             else if(testsStarted)
             {
                 TestCase test = new TestCase(testcase + line.Trim(), Plugin.VisualStudio2012.GTest.GTestExecutor.ExecutorUri, source);
                 discoverySink.SendTestCase(test);
                 logger.SendMessage(TestMessageLevel.Informational, string.Format("Found test {0}", testcase + line.Trim()));
             }
         }
     }
 }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the CircleOfTrust class.
        /// </summary>
        /// <param name="fileName">The file used to initiliaze this class.</param>
        public CircleOfTrust(string fileName)
        {
            try
            {
                this.Attributes = new NameValueCollection();

                StreamReader streamReader = new StreamReader(File.OpenRead(fileName));
                char[] separators = { '=' };
                while (streamReader.Peek() >= 0)
                {
                    string line = streamReader.ReadLine();
                    string[] tokens = line.Split(separators);
                    string key = tokens[0];
                    string value = tokens[1];
                    this.Attributes[key] = value;
                }

                streamReader.Close();
            }
            catch (DirectoryNotFoundException dnfe)
            {
                throw new CircleOfTrustException(Resources.CircleOfTrustDirNotFound, dnfe);
            }
            catch (FileNotFoundException fnfe)
            {
                throw new CircleOfTrustException(Resources.CircleOfTrustFileNotFound, fnfe);
            }
            catch (Exception e)
            {
                throw new CircleOfTrustException(Resources.CircleOfTrustUnhandledException, e);
            }
        }
Example #33
0
 public static void AnalyzeSimilarLines()
 {
     // Convert all .txt file to .dat files
     string[] inFiles = Directory.GetFiles(hydro.getDataDirectory() + @"\wspro88\", "*.DAT");
     foreach (string f in inFiles)
     {
         using (StreamReader sr = new StreamReader(f))
         {
             //System.Collections.Hashtable streamHash = new System.Collections.Hashtable();
             while (sr.Peek() >= 0)
             {
                 string line = sr.ReadLine();
                 string key = "";
                 if (line.Length <= 2) key = line;
                 else key = line.Substring(0, 2);
                 key.Trim();
                 if (key.Length > 0 && key.IndexOf('*') == -1)
                 {
                     string filename = hydro.getDataDirectory() + @"\wspro88\" + key + "_Summary.in";
                     using (StreamWriter sw = new StreamWriter(filename, true))
                     {
                         sw.WriteLine(line);
                     }
                 }
             }
         }
         GC.Collect();
     }
 }
Example #34
0
 static void Main(string[] args)
 {
     if (args.Length < 2 || !File.Exists(args[0]) || !Directory.Exists(args[1]))
     {
         printUsage();
         return;
     }
     string foldersListConfigFile = args[0];
     string destinationFolder = args[1];
     logFilePath = destinationFolder + @"/log.txt";
     indexRecord = new IndexRecord(destinationFolder);
     using (StreamReader reader = new StreamReader(foldersListConfigFile))
     {
         while (reader.Peek() >= 0)
         {
             string folder = reader.ReadLine();
             if (folder.StartsWith("-"))
                 notScanFolderList.Add(folder.Remove(0, 1));
             else
                 scanFolderList.Add(folder);
         }
     }
     foreach (string folder in scanFolderList)
     {
         Console.WriteLine("Start Scan Folder: " + folder);
         recordAllFileInfo(folder, destinationFolder);
     }
     indexRecord.scanCleanAndGenerateFileIDToDeleteList(destinationFolder + @"\delete");
     indexRecord.saveFileIDIndexedList();
     Console.WriteLine("Done! File Processed: {0}; Directory Processed: {1}; Directory Skipped: {2}; Error: {3}", processedFileCount, processedDirectoryCount, skippedDirectoryCount, errorCoult);
 }
Example #35
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     if (FileUpload1.FileName.Replace(" ", "").Equals(""))
     {
         LabelMensaje.Text = "<div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> Selecciona un Archivo por Favor. </div>";
     }
     else
     {
         string fecha = String.Format("{0: dd/MM/yyyy}", DateTime.Now);
         ruta = Server.MapPath("~") + "/temp/" + fecha.Replace("/", "_") + FileUpload1.FileName;
         FileUpload1.SaveAs(ruta);
         System.IO.StreamReader fd            = System.IO.File.OpenText(ruta);
         System.IO.StreamWriter ArchivoSalida = new System.IO.StreamWriter(ruta + ".txt");
         string fila   = "";
         Int32  indice = 1;
         fila = fd.ReadLine();
         while (fd.Peek() > -1)
         {
             indice += 1;
             fila    = fd.ReadLine();
             if (indice == 4)
             {
                 fecha_scac = fila.Substring(102, 10);
                 Nom_SCAC   = fila.Substring(238, 7);
                 Ciclo_SCAC = fila.Substring(294, 6);
             }
             if (fila.Split('/').Length >= 5)
             {
                 fila = fila.Replace(@"""", "");
                 fila = fila.Replace(",", ";");
                 ArchivoSalida.WriteLine(fila.Replace("�", "").Replace("0//", ""));
             }
         }
         ArchivoSalida.Close();
         fd.Close();
         if (Nom_SCAC == DropDownList1.SelectedItem.ToString().Trim())
         {
             if (Validar(Ciclo_SCAC, Nom_SCAC) == 0)
             {
                 LabelMensaje.Text = "<div class='alert alert-info alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> " + archivoFiltrado(ruta) + " </div>";
             }
             else
             {
                 LabelMensaje.Text = "<div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> " + Nom_SCAC + " del Ciclo " + Ciclo_SCAC + " YA Existe.  </div>";
             }
         }
         else
         {
             LabelMensaje.Text = "<div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> El archivo no es el correcto. Intente de nuevo por favor.</div>";
         }
     }
 }
Example #36
0
    public void LoadFromFile(string fileName, System.Text.Encoding encoding)
    {
        this.Clear();

        System.IO.StreamReader sr2 = new System.IO.StreamReader(fileName, encoding);

        while (sr2.Peek() >= 0)
        {
            this.AppendText(sr2.ReadLine());
        }

        sr2.Close();
    }
Example #37
0
    static void ProcessFile(ArrayList stats, string filename)
    {
        System.IO.StreamReader reader = System.IO.File.OpenText(filename);
        int iLineCount = 0;

        while (reader.Peek() >= 0)
        {
            reader.ReadLine();
            ++iLineCount;
        }
        stats.Add(new File(filename, iLineCount));
        reader.Close();
    }
Example #38
0
 void Awake()
 {
     using (System.IO.StreamReader _streamreader = new System.IO.StreamReader(_path))
     {
         int counter = 0;
         while (_streamreader.Peek() >= 0)
         {
             scores.Add(_streamreader.ReadLine());
             int score = int.Parse(scores[counter]);
             if (score > _highScore)
             {
                 _highScore = score;
             }
             counter++;
         }
     }
 }
    private string GetWord()
    {
        //this function returns a single word from the file passwords.txt
        //
        //store the path of the application in DBPath
        string DbPath = System.AppDomain.CurrentDomain.BaseDirectory;

        //create a connection to passwords.txt
        System.IO.StreamReader MyFile = new System.IO.StreamReader(DbPath + "\\passwords.txt");
        //declare a new arraylist for the words in the file
        List <string> Passwords = new List <string>();
        //var to store the one word
        string AWord;
        //var to store the random index of the selected word
        Int32 PWNo;
        //var to store the count of words in the list
        Int32 WordCount;
        //initialise the random number seed
        Random rnd = new Random();

        //initialise the word var
        AWord = "";
        //while there are words to read in the text file
        while (MyFile.Peek() >= 0)
        {
            //read in a single line (word)
            AWord = MyFile.ReadLine();
            //add the word to the array list
            Passwords.Add(AWord);
            //End While
        }
        //close the text file
        MyFile.Close();
        //get the number of words in the list
        WordCount = Passwords.Count - 1;
        //generate a random number between 0 and no of words less one
        //PWNo = Rnd() * WordCount
        PWNo = rnd.Next(0, WordCount);
        //get the word at that index
        AWord = Passwords[PWNo];
        //return the word
        return(AWord);
        //End Function
    }
Example #40
0
    public static void addVins(List <string> list, string path)
    {
        System.IO.StreamReader vinreader = new System.IO.StreamReader(path);
        string vin = vinreader.ReadLine();

        while (true)
        {
            if (vinreader.Peek() == -1)
            {
                break;
            }
            else
            {
                list.Add(vin);
                vin = vinreader.ReadLine();
            }
        }
        vinreader.Close();
    }
Example #41
0
    public void Read_File()
    {
        string line;
        string value;
        int    pos = 0;

        int[] coord_check           = new int[3];
        System.IO.StreamReader file = new System.IO.StreamReader(@"Assets\Standard Assets\Coords.txt");
        while (file.Peek() >= 0)
        {
            line = file.ReadLine();
            file_string.Add(line);
        }
        for (int p = 0; p < file_string.Count; p++) //бежим по всем строкам из файла
        {
            for (int j = 0; j < 2; j++)
            {
                pos            = file_string[p].IndexOf(" ");
                value          = file_string[p].Substring(0, pos);
                coord_check[j] = int.Parse(value);
                file_string[p] = file_string[p].Substring(pos + 1);
            }
            coord_check[2] = int.Parse(file_string[p]);
            for (int k = 0; k < elements.Count; k++) //бежим по всем кубикам
            {
                if ((elements[k].transform.position.x == coord_check[0]) && (elements[k].transform.position.y == coord_check[1]) && (elements[k].transform.position.z == coord_check[2]))
                {
                    Material myMaterial = (Material)Resources.Load("Navysmooth.mat"); //не работает текстура
                    //Material gg = (Material)Resources.Load<Material>()
                    if (myMaterial == null)
                    {
                        Debug.Log("Loser");
                    }
                    else
                    {
                        Debug.Log("Success!");
                    }
                    elements[k].GetComponent <MeshRenderer>().material = myMaterial;
                }
            }
        }
    }
Example #42
0
    void csv_read(string name)
    {
        //入力用ファイル
        var csv_file_path = Application.dataPath;

        csv_file_path = csv_file_path.Substring(0, csv_file_path.LastIndexOf(@"\") + 1);

        //読み込んだ文字列保存
        string string_line;

        //入力
        using (var read_file = new System.IO.StreamReader(csv_file_path + @"save_csv\" + name + ".csv", System.Text.Encoding.GetEncoding("utf-8")))
        {
            while (read_file.Peek() >= 0)
            {
                string_line = string.Empty;
                //一行ずつ読み込む
                string_line = read_file.ReadLine();

                //string_print(string_line);
                split_string_line(string_line);
            }
        }
    }
Example #43
0
        static void Main(string[] args)
        {
            Console.WriteLine("\t\t\t    TERMINAL READY.");
            Console.WriteLine("\t\t ds168 V 1.0 - The C# terminal application.");
            Console.WriteLine("\t\t Type \"help\" for available commands. ");
            Console.WriteLine("--------------------------------------------------------------------------------");

            while (true)
            {
                Console.Write(Environment.UserName + "@" + Environment.CurrentDirectory + "\\winsh>");
                String   inputString = Console.ReadLine();
                String[] str         = inputString.Split(' ');
                if (str.Length == 1 && str[0].Equals("help"))
                {
                    Console.WriteLine("\nCurrently implemented UNIX-commands (see \"man\" for implemented options)");
                    Console.WriteLine("\t man - an interface to the on-line reference manuals");
                    Console.WriteLine("\t ls  - list directory contents ");
                    Console.WriteLine("\t cp - copy files");
                    Console.WriteLine("\t more - file perusal filter for crt viewing");
                    Console.WriteLine("\t grep - print lines matching a pattern");
                    Console.WriteLine("\t cd - Changes the current directory");
                    Console.WriteLine("\t ps - Displays all running processes.");
                    Console.WriteLine("\t date - Displays system current date and time.");
                    Console.WriteLine("\t mv - move files");
                    Console.WriteLine("\t ping - send ICMP ECHO_REQUEST to network hosts");

                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("man"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t man - an interface to the on-line reference manuals");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t man [COMMAND]...");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t man is the system's manual pager.");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("ls"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t ls - list directory contents");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t ls [FILE]...");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t List  information  about  the FILEs (the current directory by default).");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("more"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t more - file perusal filter for crt viewing");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t more [FILE]...");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t  more is a filter for paging through text one screenful at a time.");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("cp"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t cp - copy files");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t cp [SOURCE...] [DIRECTORY...]");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t Copy SOURCE to DEST");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("grep"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t grep - print lines matching a pattern");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t  grep PATTERN [FILE...]");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t grep searches the named input FILEs for lines containing a match to the given PATTERN.");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("cd"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t cd - Changes the current directory");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t  cd  [DEST...] ..");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t cd DEST changes the current directory the Destination directory.");
                    Console.WriteLine("\t cd .. changes the current directory to the parent directory.");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("ps"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t ps - Displays all running processes.");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t  ps");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t program  provides  a  dynamic real-time view of a running system.");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("date"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t date - Displays system current date and time.");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t  ps");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t Prints system date and time");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("ping"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t ping - send ICMP ECHO_REQUEST to network hosts");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t  ping [URL]");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t Allows an application to determine whether a remote computer is accessible over the network.");
                    Console.WriteLine("\nEXAMPLE");
                    Console.WriteLine("\t ping http:\\www.google.com");
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("man") && str[1].Equals("mv"))
                {
                    Console.WriteLine("\nNAME");
                    Console.WriteLine("\t  mv - move files");
                    Console.WriteLine("\nSYNOPSIS");
                    Console.WriteLine("\t mv [SOURCE...] [DIRECTORY...]");
                    Console.WriteLine("\nDESCRIPTION");
                    Console.WriteLine("\t Move SOURCE(s) to DIRECTORY.");
                    Console.WriteLine();
                }
                else if (str.Length == 1 && str[0].Equals("ls"))
                {
                    string[] dirs = Directory.GetFiles(Environment.CurrentDirectory, "*");
                    Console.WriteLine("The number of files in current directory is {0}.", dirs.Length);
                    foreach (string dir in dirs)
                    {
                        Console.WriteLine("\t" + dir);
                    }
                    Console.WriteLine();
                }

                else if (str.Length == 2 && str[0].Equals("cd"))
                {
                    if (str[1] == "..")
                    {
                        try
                        {
                            String prevDir = Directory.GetParent(Directory.GetCurrentDirectory()).ToString();
                            Directory.SetCurrentDirectory(prevDir);
                        }
                        catch {
                            Console.WriteLine(" ");//At root Directory
                        }
                    }
                    else if (Directory.Exists(str[1]) == false)
                    {
                        Console.WriteLine(str[1] + ": No Such file or Directory");
                    }
                    else
                    {
                        String strin = str[1];
                        Directory.SetCurrentDirectory(strin);
                    }
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("more"))
                {
                    if (File.Exists(str[1]) == false)
                    {
                        Console.WriteLine(str[1] + ": No Such file exists");
                    }
                    else
                    {
                        string fullPath = Path.GetFullPath(str[1]);
                        int    counter  = 0;
                        string line;

                        // Read the file and display it line by line.
                        System.IO.StreamReader file =
                            new System.IO.StreamReader(fullPath);
                        Console.WriteLine("<Press Enter to read more lines>");
                        while ((file.Peek()) != -1)
                        {
                            Console.ReadKey();
                            counter = 0;
                            while (counter != 5)
                            {
                                line = file.ReadLine();
                                System.Console.WriteLine(line);
                                counter++;
                            }
                        }

                        file.Close();
                    }
                    Console.WriteLine();
                }
                else if (str.Length == 3 && str[0].Equals("cp"))
                {
                    if (File.Exists(str[1]) == false)
                    {
                        Console.WriteLine("Source file: " + str[1] + " not found");
                    }

                    else if (File.Exists(str[2]) == false)
                    {
                        Console.WriteLine("Target file: " + str[2] + " not found");
                    }
                    else
                    {
                        File.Copy(Path.GetFullPath(str[1]), Path.GetFullPath(str[2]), true);
                    }
                    Console.WriteLine();
                }
                else if (str.Length == 3 && str[0].Equals("grep"))
                {
                    if (File.Exists(str[2]) && Directory.Exists(str[2]) == false)
                    {
                        Console.WriteLine(str[1] + ": No Such file or Directory exists");
                    }
                    else
                    {
                        foreach (String d in Directory.GetDirectories(Directory.GetCurrentDirectory()))
                        {
                            Console.WriteLine("Directory: " + d);
                            foreach (String f in Directory.GetFiles(d))
                            {
                                Console.WriteLine("\t File: " + f);
                                string[] lines = File.ReadAllLines(f);

                                foreach (string line in lines)
                                {
                                    if (line.Contains(str[1]))
                                    {
                                        Console.WriteLine(line);
                                    }
                                }
                            }
                        }
                    }
                    Console.WriteLine();
                }
                else if (str.Length == 1 && str[0].Equals("ps"))
                {
                    Process[] processlist = Process.GetProcesses();

                    foreach (Process theprocess in processlist)
                    {
                        Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id);
                    }
                    Console.WriteLine();
                }
                else if (str.Length == 1 && str[0].Equals("date"))
                {
                    Console.WriteLine(DateTime.Now);
                    Console.WriteLine();
                }
                else if (str.Length == 2 && str[0].Equals("ping"))
                {
                    Uri       url        = new Uri(str[1]);
                    string    pingurl    = string.Format("{0}", url.Host);
                    Ping      ping       = new Ping();
                    PingReply pingresult = ping.Send(pingurl, 3000);

                    if (pingresult.Status.ToString() == "Success")
                    {
                        Console.WriteLine("Connection Success");
                    }
                    else
                    {
                        Console.WriteLine("Connection Failed");
                    }

                    Console.WriteLine();
                }
                else if (str.Length == 3 && str[0].Equals("mv"))
                {
                    if (File.Exists(str[1]) == false)
                    {
                        Console.WriteLine("Source file not found");
                    }
                    else if (Directory.Exists(str[2]) == false)
                    {
                        Console.WriteLine("Target Directory not found");
                    }
                    else
                    {
                        File.Move(str[1], str[2] + "\\" + str[1]);
                    }


                    Console.WriteLine();
                }

                else
                {
                    Console.WriteLine("Command '" + inputString + "' not recognized.");
                    Console.WriteLine();
                }
            }
        }
Example #44
0
        private static void RecebeDados(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;
            int    received;

            try {
                received = current.EndReceive(AR);
            } catch (SocketException) {
                string nome = GetNomeCliente(current);
                Console.WriteLine("CLIENTE " + nome + " FOI DESCONECTADO.");
                current.Close();
                clienteSockets.RemoveAll(item => item.Value.Equals(current));
                EnviaMensagemParaTodosProntos("[" + nome + "] saiu do jogo..");

                string arquivoTexto            = "";
                System.IO.StreamReader arquivo = new System.IO.StreamReader(caminho);

                while (arquivo.Peek() >= 0)
                {
                    string   linha  = arquivo.ReadLine();
                    string[] campos = linha.Split(':');

                    if (campos[0] != nome)
                    {
                        arquivoTexto += linha + "\r\n";
                    }
                }

                arquivo.Close();

                File.WriteAllText(caminho, arquivoTexto, Encoding.UTF7);

                return;
            } catch (ObjectDisposedException) {
                return;
            }

            byte[] recBuf = new byte[received];
            Array.Copy(buffer, recBuf, received);
            string texto = Encoding.ASCII.GetString(recBuf);

            if (texto.Substring(0, 1) == "@")
            {
                string comando = texto.Substring(1, texto.IndexOf(" ") - 1);
                string valor   = texto.Substring(comando.Length + 2);

                if (comando == "NOME")
                {
                    Boolean jaExisteNome = false;
                    foreach (var elemento in clienteSockets)
                    {
                        if (elemento.Key == valor)
                        {
                            jaExisteNome = true;
                        }
                    }

                    if (jaExisteNome)
                    {
                        byte[] textoEnviado = Encoding.ASCII.GetBytes("#ERRO_NOME_JA_UTILIZADO");
                        current.Send(textoEnviado);
                    }
                    else
                    {
                        clienteSockets.RemoveAll(item => item.Value.Equals(current));
                        clienteSockets.Add(new KeyValuePair <string, Socket>(valor, current));
                        byte[] textoEnviado = Encoding.ASCII.GetBytes("#OK");
                        current.Send(textoEnviado);

                        string textoArquivo = File.ReadAllText(caminho, Encoding.UTF7);
                        File.WriteAllText(caminho, textoArquivo + valor + ":0\r\n", Encoding.UTF7);

                        EnviaMensagemParaTodosProntos("[" + valor + "] entrou no jogo..");
                    }
                }
            }
            else if (texto.Substring(0, 1) == "$")
            {
                string comando = texto.Substring(1, texto.IndexOf(" ") - 1);
                string valor   = texto.Substring(comando.Length + 2);

                if (comando == "DICA")
                {
                    Console.WriteLine("DICA: " + valor);
                    dica = valor;
                }
                else if (comando == "RESPOSTA")
                {
                    Console.WriteLine("RESPOSTA: " + valor);
                    resposta = valor;
                }
                else if (comando == "PERGUNTA_RESPOSTA")
                {
                    Console.WriteLine("[MESTRE - " + GetNomeCliente(current) + "] RESPONDEU: " + valor);
                    EnviaMensagemParaTodosExcetoMestreEJogadorVez("[MESTRE]: " + valor);
                    clienteSockets[jogadorVez].Value.Send(Encoding.ASCII.GetBytes("#SUA_VEZ_PALPITE " + valor));
                }
            }
            else if (texto.Substring(0, 1) == "%")
            {
                string comando = texto.Substring(1, texto.IndexOf(" ") - 1);
                string valor   = texto.Substring(comando.Length + 2);

                if (comando == "PERGUNTA")
                {
                    Console.WriteLine("[" + GetNomeCliente(current) + "] PERGUNTOU: " + valor);
                    EnviaMensagemParaMestre("#PERGUNTA " + valor);
                    EnviaMensagemParaTodosExcetoMestreEJogadorVez("[" + GetNomeCliente(current) + "]: " + valor);
                }
                else if (comando == "PALPITE")
                {
                    if (valor.ToLower() != resposta.ToLower())
                    {
                        Console.WriteLine("[" + GetNomeCliente(current) + "] ERROU SEU PALPITE");
                        EnviaMensagemParaMestre("\n[" + GetNomeCliente(current) + "] errou seu palpite");
                        EnviaMensagemParaTodosExcetoMestre("\nTentativa: " + valor + "\n[" + GetNomeCliente(current) + "] errou");
                        novaPergunta = false;
                    }
                    else
                    {
                        string arquivoTexto            = "";
                        System.IO.StreamReader arquivo = new System.IO.StreamReader(caminho);

                        while (arquivo.Peek() >= 0)
                        {
                            string   linha  = arquivo.ReadLine();
                            string[] campos = linha.Split(':');

                            if (campos[0] == GetNomeCliente(current))
                            {
                                arquivoTexto += campos[0] + ":" + (int.Parse(campos[1]) + 1) + "\r\n";
                            }
                            else
                            {
                                arquivoTexto += linha + "\r\n";
                            }
                        }

                        arquivo.Close();

                        File.WriteAllText(caminho, arquivoTexto, Encoding.UTF7);

                        novaPergunta = false;
                        novaPartida  = true;
                    }
                }
            }
            else
            {
                if (texto.ToLower() == "sair")
                {
                    string nome = GetNomeCliente(current);
                    current.Shutdown(SocketShutdown.Both);
                    current.Close();
                    clienteSockets.RemoveAll(item => item.Value.Equals(current));
                    Console.WriteLine("CLIENTE " + nome + " SAIU");

                    string arquivoTexto            = "";
                    System.IO.StreamReader arquivo = new System.IO.StreamReader(caminho);

                    while (arquivo.Peek() >= 0)
                    {
                        string   linha  = arquivo.ReadLine();
                        string[] campos = linha.Split(':');

                        if (campos[0] != nome)
                        {
                            arquivoTexto += linha + "\r\n";
                        }
                    }

                    arquivo.Close();

                    File.WriteAllText(caminho, arquivoTexto, Encoding.UTF7);

                    return;
                }
            }

            current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, RecebeDados, current);
        }
Example #45
0
        /// <summary> Read the ShelX from input. Each ShelX document is expected to contain
        /// one crystal structure.
        ///
        /// </summary>
        /// <returns> a ChemFile with the coordinates, charges, vectors, etc.
        /// </returns>
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence seq   = file.Builder.newChemSequence();
            IChemModel    model = file.Builder.newChemModel();

            crystal = file.Builder.newCrystal();

            System.String line      = input.ReadLine();
            bool          end_found = false;

            while (input.Peek() != -1 && line != null && !end_found)
            {
                if (line.StartsWith("#"))
                {
                    //logger.warn("Skipping comment: " + line);
                    // skip comment lines
                }
                else if (line.Length == 0)
                {
                    //logger.debug("Skipping empty line");
                    // skip empty lines
                }
                else if (!(line.StartsWith("_") || line.StartsWith("loop_")))
                {
                    //logger.warn("Skipping unrecognized line: " + line);
                    // skip line
                }
                else
                {
                    /* determine CIF command */
                    System.String command    = "";
                    int           spaceIndex = line.IndexOf(" ");
                    if (spaceIndex != -1)
                    {
                        // everything upto space is command
                        try
                        {
                            command = new System.Text.StringBuilder(line.Substring(0, (spaceIndex) - (0))).ToString();
                        }
                        catch (System.ArgumentOutOfRangeException sioobe)
                        {
                            // disregard this line
                            break;
                        }
                    }
                    else
                    {
                        // complete line is command
                        command = line;
                    }

                    //logger.debug("command: " + command);
                    if (command.StartsWith("_cell"))
                    {
                        processCellParameter(command, line);
                    }
                    else if (command.Equals("loop_"))
                    {
                        processLoopBlock();
                    }
                    else if (command.Equals("_symmetry_space_group_name_H-M"))
                    {
                        System.String value_Renamed = line.Substring(29).Trim();
                        crystal.SpaceGroup = value_Renamed;
                    }
                    else
                    {
                        // skip command
                        //logger.warn("Skipping command: " + command);
                        line = input.ReadLine();
                        if (line.StartsWith(";"))
                        {
                            //logger.debug("Skipping block content");
                            line = input.ReadLine().Trim();
                            while (!line.Equals(";"))
                            {
                                line = input.ReadLine().Trim();
                                //logger.debug("Skipping block line: " + line);
                            }
                            line = input.ReadLine();
                        }
                    }
                }
                line = input.ReadLine();
            }
            //logger.info("Adding crystal to file with #atoms: " + crystal.AtomCount);
            model.Crystal = crystal;
            seq.addChemModel(model);
            file.addChemSequence(seq);
            return(file);
        }
Example #46
0
        /// <summary> Read the Gaussian98 output.
        ///
        /// </summary>
        /// <returns> a ChemFile with the coordinates, energies, and
        /// vibrations.
        /// </returns>
        /// <throws>  IOException  if an I/O error occurs </throws>
        /// <throws>  CDKException Description of the Exception </throws>
        private IChemFile readChemFile(IChemFile chemFile)
        {
            IChemSequence sequence = chemFile.Builder.newChemSequence();
            IChemModel    model    = null;

            System.String line = input.ReadLine();
            System.String levelOfTheory;
            System.String description;
            int           modelCounter = 0;

            // Find first set of coordinates by skipping all before "Standard orientation"
            while (input.Peek() != -1 && (line != null))
            {
                if (line.IndexOf("Standard orientation:") >= 0)
                {
                    // Found a set of coordinates
                    model = chemFile.Builder.newChemModel();
                    readCoordinates(model);
                    break;
                }
                line = input.ReadLine();
            }
            if (model != null)
            {
                // Read all other data
                line = input.ReadLine().Trim();
                while (input.Peek() != -1 && (line != null))
                {
                    if (line.IndexOf("#") == 0)
                    {
                        // Found the route section
                        // Memorizing this for the description of the chemmodel
                        lastRoute    = line;
                        modelCounter = 0;
                    }
                    else if (line.IndexOf("Standard orientation:") >= 0)
                    {
                        // Found a set of coordinates
                        // Add current frame to file and create a new one.
                        if (!readOptimizedStructureOnly.Set)
                        {
                            sequence.addChemModel(model);
                        }
                        else
                        {
                            //logger.info("Skipping frame, because I was told to do");
                        }
                        fireFrameRead();
                        model = chemFile.Builder.newChemModel();
                        modelCounter++;
                        readCoordinates(model);
                    }
                    else if (line.IndexOf("SCF Done:") >= 0)
                    {
                        // Found an energy
                        model.setProperty(CDKConstants.REMARK, line.Trim());
                    }
                    else if (line.IndexOf("Harmonic frequencies") >= 0)
                    {
                        // Found a set of vibrations
                        // readFrequencies(frame);
                    }
                    else if (line.IndexOf("Total atomic charges") >= 0)
                    {
                        readPartialCharges(model);
                    }
                    else if (line.IndexOf("Magnetic shielding") >= 0)
                    {
                        // Found NMR data
                        readNMRData(model, line);
                    }
                    else if (line.IndexOf("GINC") >= 0)
                    {
                        // Found calculation level of theory
                        levelOfTheory = parseLevelOfTheory(line);
                        //logger.debug("Level of Theory for this model: " + levelOfTheory);
                        description = lastRoute + ", model no. " + modelCounter;
                        model.setProperty(CDKConstants.DESCRIPTION, description);
                    }
                    else
                    {
                        ////logger.debug("Skipping line: " + line);
                    }
                    line = input.ReadLine();
                }

                // Add last frame to file
                sequence.addChemModel(model);
                fireFrameRead();
            }
            chemFile.addChemSequence(sequence);

            return(chemFile);
        }
Example #47
0
        static void Main(string[] args)
        {
            try
            {
                gblClass objMainClass = new gblClass();

                StaticClass.constr = new SqlConnection("Data Source=146.0.237.246;database=OnlineDB;uid=sa;password=Jan@Server007;Connect Timeout=5000");
                StaticClass.LocalCon.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Application.StartupPath + "\\db.mdb;User Id=admin;Password=;";
                string str                   = "";
                string localCode             = "";
                string filename              = Application.StartupPath + "\\tid.amp";
                string textline              = "";
                Int64  IsBlock               = 0;
                Int64  IsSuspend             = 0;
                string ExpiryCopyrightStatus = "";
                Int64  LeftCopyrightDays     = 0;

                string    strOpt    = "";
                string    proc      = Process.GetCurrentProcess().ProcessName;
                Process[] processes = Process.GetProcessesByName("StoreAndForwardPlayer");

                //                MessageBox.Show("First time " + processes.Length);
                if (processes.Length > 1)
                {
                    Application.Exit();
                    return;
                    // MessageBox.Show("Application is already running" );
                    //return;http://www.sikhiwiki.org/index.php/Guru_Granth_Sahib_on_alcohol
                }

                if (File.Exists(filename))
                {
                    System.IO.StreamReader objReader;
                    objReader = new System.IO.StreamReader(filename);
                    do
                    {
                        textline = textline + objReader.ReadLine();
                    } while (objReader.Peek() != -1);
                    objReader.Close();

                    try
                    {
                        string  strOpt1   = "select * from tbMisc";
                        DataSet dsOption1 = new DataSet();
                        dsOption1 = objMainClass.fnFillDataSet_Local(strOpt1);
                        if (dsOption1.Tables[0].Rows.Count > 0)
                        {
                            StaticClass.DealerCode        = dsOption1.Tables[0].Rows[0]["DealerCode"].ToString();
                            StaticClass.dfClientId        = dsOption1.Tables[0].Rows[0]["dfClientId"].ToString();
                            StaticClass.IsStore           = Convert.ToBoolean(dsOption1.Tables[0].Rows[0]["IsStore"]);
                            StaticClass.IsAdvt            = Convert.ToBoolean(dsOption1.Tables[0].Rows[0]["IsAdvt"]);
                            StaticClass.IsLock            = Convert.ToBoolean(dsOption1.Tables[0].Rows[0]["IsLock"]);
                            StaticClass.PlayerVersion     = Convert.ToInt32(dsOption1.Tables[0].Rows[0]["PlayerVersion"]);
                            StaticClass.MainwindowMessage = dsOption1.Tables[0].Rows[0]["support"].ToString();
                            StaticClass.ScheduleType      = dsOption1.Tables[0].Rows[0]["ScheduleType"].ToString();
                        }
                    }
                    catch (Exception ex) { }

                    if (objMainClass.CheckForInternetConnection() == false)
                    {
                        StaticClass.TokenServiceId = 0;
                        StaticClass.IsAdvtManual   = false;
                        StaticClass.IsBlockAdvt    = false;
                        StaticClass.TokenUserId    = 0;
                        StaticClass.AdvtCityId     = 0;
                        StaticClass.IsCopyright    = true;
                        StaticClass.TokenId        = textline;

                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new CopyrightPlayer());
                        return;
                    }


                    if (StaticClass.constr.State == ConnectionState.Open)
                    {
                        StaticClass.constr.Close();
                    }
                    StaticClass.constr.Open();

                    strOpt = "select ISNULL(IsCopyright,0) as Copyright, ISNULL(IsFitness,0) as Fitness, isnull(IsStream,0) as Stream,dealerCode, ISNULL(IsAdvt,0) as Advt, ISNULL(IsAdvtManual,0) as AdvtManual, ISNULL(IsBlockAdvt,0) as IsBlockAdvt, isnull(serviceid,0) as serviceid , isnull(cityid,0) as CityId  , isnull(StateId,0) as StateId, isnull(CountryId,0) as CountryId, UserId, isnull(isStore,0) as isStore,isnull(IsStopControl,0) as IsLock , isnull(IsVedioActive,0) as VedioActive, isnull(IsUpdated,0) as PlayerVersion, isnull(PersonName,'') as pname, isnull(AMPlayerTokens.ScheduleType,'0') as ScheduleType from AMPlayerTokens where TokenID=" + textline;
                    DataSet dsOption = new DataSet();
                    dsOption = objMainClass.fnFillDataSet(strOpt);
                    if (dsOption.Tables[0].Rows.Count > 0)
                    {
                        StaticClass.TokenServiceId = Convert.ToInt32(dsOption.Tables[0].Rows[0]["serviceid"]);
                        StaticClass.DealerCode     = dsOption.Tables[0].Rows[0]["DealerCode"].ToString();

                        StaticClass.IsAdvtManual  = Convert.ToBoolean(dsOption.Tables[0].Rows[0]["AdvtManual"]);
                        StaticClass.IsAdvt        = Convert.ToBoolean(dsOption.Tables[0].Rows[0]["Advt"]);
                        StaticClass.IsBlockAdvt   = Convert.ToBoolean(dsOption.Tables[0].Rows[0]["IsBlockAdvt"]);
                        StaticClass.TokenUserId   = Convert.ToInt32(dsOption.Tables[0].Rows[0]["userid"]);
                        StaticClass.AdvtCityId    = Convert.ToInt32(dsOption.Tables[0].Rows[0]["CityId"]);
                        StaticClass.Stateid       = Convert.ToInt32(dsOption.Tables[0].Rows[0]["Stateid"]);
                        StaticClass.CountryId     = Convert.ToInt32(dsOption.Tables[0].Rows[0]["CountryId"]);
                        StaticClass.IsStore       = Convert.ToBoolean(dsOption.Tables[0].Rows[0]["IsStore"]);
                        StaticClass.IsLock        = Convert.ToBoolean(dsOption.Tables[0].Rows[0]["IsLock"]);
                        StaticClass.IsVedioActive = Convert.ToBoolean(dsOption.Tables[0].Rows[0]["VedioActive"]);

                        StaticClass.TokenId       = textline;
                        StaticClass.PlayerVersion = Convert.ToInt32(dsOption.Tables[0].Rows[0]["PlayerVersion"]);

                        StaticClass.ScheduleType      = dsOption.Tables[0].Rows[0]["ScheduleType"].ToString();
                        StaticClass.MainwindowMessage = StaticClass.TokenId.ToString() + "  (" + dsOption.Tables[0].Rows[0]["pname"].ToString() + ")";


                        str = "spGetTokenExpiryStatus_Copyright " + textline + ", " + dsOption.Tables[0].Rows[0]["Copyright"] + ", " + dsOption.Tables[0].Rows[0]["Fitness"] + ", " + dsOption.Tables[0].Rows[0]["Stream"];
                        DataSet dsExpire = new DataSet();
                        dsExpire = objMainClass.fnFillDataSet(str);


                        ExpiryCopyrightStatus = dsExpire.Tables[0].Rows[0]["ExpiryCopyrightStatus"].ToString();
                        LeftCopyrightDays     = Convert.ToInt32(dsExpire.Tables[0].Rows[0]["LeftCopyrightDays"]);

                        StaticClass.StreamExpiryMessage = dsExpire.Tables[0].Rows[0]["ExpiryStreamStatus"].ToString();
                        StaticClass.LeftStreamtDays     = Convert.ToInt32(dsExpire.Tables[0].Rows[0]["LeftStreamDays"]);

                        if (ExpiryCopyrightStatus == "NoLic")
                        {
                            StaticClass.PlayerExpiryMessage = "Purchase the subscription of music player. Please contact our support team ";
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new frmNet());
                            return;
                        }
                        if (ExpiryCopyrightStatus == "Yes")
                        {
                            StaticClass.PlayerExpiryMessage = "Your license has expired. Please contact our support team ";
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new frmNet());
                            return;
                        }

                        if (ExpiryCopyrightStatus != "NoLic" && LeftCopyrightDays <= 10)
                        {
                            StaticClass.PlayerExpiryMessage = Convert.ToString(LeftCopyrightDays) + " days left to renewal of subscription. Please contact our support team";
                            StaticClass.IsCopyright         = true;
                        }
                        else if (ExpiryCopyrightStatus != "NoLic" && LeftCopyrightDays == 0)
                        {
                            StaticClass.PlayerExpiryMessage = "Last day to renewal of subscription. Please contact our support team ";
                            StaticClass.IsCopyright         = true;
                        }
                        else
                        {
                            StaticClass.IsCopyright = true;
                        }
                        if (ExpiryCopyrightStatus == "Yes")
                        {
                            StaticClass.PlayerExpiryMessage = "Your license has expired. Please contact our support team ";
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new frmNet());
                            return;
                        }

                        else if (ExpiryCopyrightStatus == "NoLic")
                        {
                            StaticClass.PlayerExpiryMessage = "You do not have license. Please contact our support team ";
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new frmNet());
                            return;
                        }

                        // str = "spGetTokenExpiryStatus_Copyleft " + Convert.ToInt32(textline) + ", " + dsOption.Tables[0].Rows[0]["Dam"] + ", " + dsOption.Tables[0].Rows[0]["Sanjivani"] + ", " + dsOption.Tables[0].Rows[0]["Stream"];
                        StaticClass.StreamExpiryMessage = dsExpire.Tables[0].Rows[0]["ExpiryStreamStatus"].ToString();
                        StaticClass.LeftStreamtDays     = Convert.ToInt32(dsExpire.Tables[0].Rows[0]["LeftStreamDays"]);
                        str = "select *, ISNULL(IsBlock,0) as Is_Block, ISNULL(IsSuspend,0) as Is_Suspend   from AMPlayerTokens where tokenid=" + textline;
                        DataSet ds     = new DataSet();
                        string  dbCode = "";

                        ds     = objMainClass.fnFillDataSet(str);
                        dbCode = ds.Tables[0].Rows[0]["code"].ToString();
                        try
                        {
                            localCode = GenerateId.getKey(GenerateId._wvpaudi);
                        }
                        catch (Exception ex)
                        {
                            //dbCode = textline;
                            // localCode = textline;
                        }
                        //6B16-4875-D8C6-7142-21D7
                        //6B16-4875-D8C6-7142-21D7

                        if (dbCode == localCode)
                        {
                            StaticClass.dfClientId = ds.Tables[0].Rows[0]["ClientID"].ToString();

                            StaticClass.TokenId = ds.Tables[0].Rows[0]["TokenId"].ToString();

                            IsBlock   = Convert.ToInt32(ds.Tables[0].Rows[0]["Is_Block"]);
                            IsSuspend = Convert.ToInt32(ds.Tables[0].Rows[0]["Is_Suspend"]);
                            if (IsBlock == 1)
                            {
                                MessageBox.Show("Your token is blocked by admin");
                                Application.Exit();
                                return;
                            }
                            else if (IsSuspend == 1)
                            {
                                MessageBox.Show("Your token is suspend by admin");
                                return;
                            }
                            //  Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);

                            Application.Run(new Clientlogin());
                            return;
                        }
                        else
                        {
                            //   Application.EnableVisualStyles();
                            Application.SetCompatibleTextRenderingDefault(false);
                            Application.Run(new frmStart());
                            return;
                        }
                    }
                    else
                    {
                        File.Delete(Application.StartupPath + "//tid.amp");
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new frmStart());
                        return;
                    }
                }
                else
                {
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new frmStart());
                    return;
                }
            }

            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
            }
        }
Example #48
0
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Event handler. Called by OpenBtn for click events. </summary>
        ///
        /// <remarks>   , 23/08/2018. </remarks>
        ///
        /// <param name="sender">   Source of the event. </param>
        /// <param name="e">        Event information. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        private void OpenBtn_Click(object sender, EventArgs e)
        {
            //If the DataGridView is empty then the open file dialog will open otherwise will ask a question.
            if (MyPeopleGrid.Rows.Count == 0)
            {
            }
            else
            {
                DialogResult dialogResult = MessageBox.Show("Do you want to clear the datagridview?", "Confirmation", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    MyPeopleGrid.Rows.Clear();
                }
                else if (dialogResult == DialogResult.No)
                {
                }
            }

            MyPeopleGrid.AllowUserToAddRows = false;
            openFileDialog1.Filter          = "CSV files (*.csv)|*.CSV";
            openFileDialog1.FileName        = "";
            openFileDialog1.ShowDialog();
            PathBox2.Text = openFileDialog1.FileName;

            string fileRow;

            string[] fileDataField;
            int      count = 0;

            try
            {
                if (System.IO.File.Exists(PathBox2.Text))
                {
                    System.IO.StreamReader fileReader = new System.IO.StreamReader(PathBox2.Text);

                    if (fileReader.Peek() != -1)
                    {
                        fileRow       = fileReader.ReadLine();
                        fileDataField = fileRow.Split(',').ToArray();
                        count         = fileDataField.Count();
                        count         = count - 1;
                    }
                    //Reading Data
                    while (fileReader.Peek() != -1)
                    {
                        this.MyPeopleGrid.Sort(this.MyPeopleGrid.Columns["Person"], ListSortDirection.Ascending);
                        fileRow       = fileReader.ReadLine();
                        fileDataField = fileRow.Split(',').ToArray();
                        MyPeopleGrid.Rows.Add(fileDataField);
                        string name = fileDataField[0].ToString();
                        ListOfPeople.Add(name.Trim());
                        //Delete empty rows
                        foreach (DataGridViewRow row1 in MyPeopleGrid.Rows)
                        {
                            if (row1.Cells.Cast <DataGridViewCell>().Any(c => c.Value == null || string.IsNullOrWhiteSpace(c.Value.ToString())))
                            {
                                MyPeopleGrid.Rows.RemoveAt(row1.Index);
                                break;
                            }
                            else
                            {
                            }
                        }
                    }
                    fileReader.Close();
                }
                else
                {
                    MessageBox.Show("No File Selected", "Message");
                }
                //select first row
                MyPeopleGrid.CurrentCell = MyPeopleGrid.Rows[0].Cells[0];
            }
            catch (Exception)
            {
            }
        }
Example #49
0
        public ReturnValue getControler()
        {
            ReturnValue _result = new ReturnValue();

            try
            {
                #region getXML
                string path = "Controler.xml";

                if (HttpContext.Current != null)
                {
                    path = HttpContext.Current.Server.MapPath(path);
                }

                System.IO.StreamReader sr = new System.IO.StreamReader(path, System.Text.Encoding.GetEncoding("utf-8"));
                sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                string s = "";

                while (sr.Peek() > -1)
                {
                    s += sr.ReadLine();
                }

                sr.Close();

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(s);
                #endregion

                #region fillInfo
                XmlNodeList _nl = doc.GetElementsByTagName("Owners").Item(0).SelectNodes("Owner");
                foreach (XmlNode _nd in _nl)
                {
                    Owner _owner = new Owner();
                    _owner.OwnerCode = _nd.Attributes["OwnerCode"].InnerXml;
                    _owner.RegSubKey = _nd.Attributes["RegSubKey"].InnerXml;
                    _owner.Name      = _nd.Attributes["Name"].InnerXml;
                    _owner.Enable    = Convert.ToBoolean(_nd.Attributes["Enable"].InnerXml);

                    #region ClassType

                    XmlNodeList _nlDictionary = _nd.SelectNodes("ClassType/Class");

                    foreach (XmlNode _ndColumn in _nlDictionary)
                    {
                        ClassType _classType = new ClassType();
                        _classType.ClassCode    = _ndColumn.Attributes["ClassCode"].InnerXml;
                        _classType.Type         = _ndColumn.Attributes["ClassType"].InnerXml;
                        _classType.AssemblyFile = _ndColumn.Attributes["AssemblyFile"].InnerXml;

                        _owner.ClassType.Add(_classType.ClassCode, _classType);
                    }

                    #endregion

                    #region OwnerInfo
                    _nlDictionary = _nd.SelectNodes("OwnerInfo/Info");

                    foreach (XmlNode _ndColumn in _nlDictionary)
                    {
                        _owner.OwnerInfo.Add(_ndColumn.Attributes["Key"].InnerXml, _ndColumn.InnerXml);
                    }


                    #endregion

                    #region Action
                    _nlDictionary = _nd.SelectNodes("Actions/Action");

                    foreach (XmlNode _ndColumn in _nlDictionary)
                    {
                        _owner.Actions.Add(_ndColumn.Attributes["Code"].InnerXml.ToUpper(), Convert.ToBoolean(_ndColumn.Attributes["Enable"].InnerXml));
                    }


                    #endregion

                    if (_owner.Enable == true)
                    {
                        this.Owners.Add(_owner);
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                _result.Success    = false;
                _result.ErrMessage = ex.ToString();
            }

            return(_result);
        }
        /// <summary>
        /// This build of sdict TM must be called BEFORE the build of sdict MT is called!
        /// And, the build of sdict CP must be called BEFORE the build of sdict MT is called!
        /// </summary>
        public void BuildSortDictForTableModules()
        {
            SysIo.FileStream   fileStream;
            SysIo.StreamReader streamReader;
            CValueTableModule  valueTableModule_TM;

            char[]   cDelims = { '\t' };
            string[] sSplits;
            string   sLine          = "Initialize";
            int      nLineReadCount = 0;

            //

            if (null != this.m_runProperties.m_sdictTableModules)
            {
                goto LABEL_RETURN_kds67_LABEL;
            }
            else
            {
                this.m_runProperties.m_sdictTableModules = new SysCollGen.SortedDictionary
                                                           <string, CValueTableModule>();
            }

            using
            (
                fileStream = new SysIo.FileStream
                             (
                    this.m_runProperties.GetPathToInputDelimFiles()
                    + this.m_runProperties.GetInputDelimFilesCommonPrefix()
                    + this.m_runProperties.GetDelimFileTableModules(),
                    SysIo.FileMode.Open,
                    SysIo.FileAccess.Read,
                    SysIo.FileShare.Read
                             )
            )
            {
                streamReader = new SysIo.StreamReader(fileStream);


                while (streamReader.Peek() >= 0)                  // Loop thru input records.
                {
                    try
                    {
                        nLineReadCount++;
                        sLine   = streamReader.ReadLine();
                        sSplits = sLine.Split(cDelims, StringSplitOptions.RemoveEmptyEntries);
                        if (2 > sSplits.Length)
                        {
                            continue;
                        }
                        if (sSplits[0].StartsWith("//"))
                        {
                            continue;
                        }
                        if (sSplits[0].Trim().Length == 0)
                        {
                            continue;
                        }

                        valueTableModule_TM = new CValueTableModule
                                              (
                            sSplits[1],                             // IComparable
                            sSplits[0],                             // TableName
                            sSplits[1]                              // ModuleName
                                              );


                        // T-M
                        this.m_runProperties.m_sdictTableModules.Add
                        (
                            valueTableModule_TM.GetKeyTableDelimModule(),
                            valueTableModule_TM
                        );
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error_cyb50: nLineReadCount={0}, sLine={1}", nLineReadCount, sLine);
                        throw e;
                    }
                }
            }

            LABEL_RETURN_kds67_LABEL :;

            if (null == this.m_runProperties.m_sdictTableModules)
            {
                this.m_runProperties.m_sdictTableModules = new SysCollGen.SortedDictionary
                                                           <string, CValueTableModule>();
            }
            return;
        }
        public void BuildSortDictForColumnsFkyPky()
        {
            SysIo.FileStream   fileStream;
            SysIo.StreamReader streamReader;
            SysCollGen.List <CValueColumnColumn> listColumnColumn;
            CValueColumnColumn valueColumnColumn;

            char[]   cDelims = { '\t' };
            string[] sSplits;
            string   sLine          = "Initialize.";
            int      nLineReadCount = 0;

            //

            if (null != this.m_runProperties.m_sdictColumnsFkyPky)
            {
                goto LABEL_RETURN_csh89_LABEL;
            }
            else
            {
                this.m_runProperties.m_sdictColumnsFkyPky = new SysCollGen.SortedDictionary
                                                            <int, SysCollGen.List <CValueColumnColumn> >();
            }

            using
            (
                fileStream = new SysIo.FileStream
                             (
                    this.m_runProperties.GetPathToInputDelimFiles()
                    + this.m_runProperties.GetInputDelimFilesCommonPrefix()
                    + this.m_runProperties.GetDelimFileColumnColumn(),
                    SysIo.FileMode.Open,
                    SysIo.FileAccess.Read,
                    SysIo.FileShare.Read
                             )
            )
            {
                streamReader = new SysIo.StreamReader(fileStream);


                while (streamReader.Peek() >= 0)
                {
                    try
                    {
                        nLineReadCount++;
                        sLine   = streamReader.ReadLine();
                        sSplits = sLine.Split(cDelims, StringSplitOptions.RemoveEmptyEntries);
                        if (4 > sSplits.Length)
                        {
                            continue;
                        }
                        if (sSplits[0].StartsWith("//"))
                        {
                            continue;
                        }
                        if (sSplits[0].Trim().Length == 0)
                        {
                            continue;
                        }

                        valueColumnColumn = new CValueColumnColumn
                                                (Convert.ToInt32(sSplits[0]), Convert.ToInt32(sSplits[1]), sSplits[2], sSplits[3]);


                        if (this.m_runProperties.m_sdictColumnsFkyPky.ContainsKey(valueColumnColumn.GetIdentityTT()))
                        {
                            listColumnColumn = this.m_runProperties.m_sdictColumnsFkyPky[valueColumnColumn.GetIdentityTT()];
                            listColumnColumn.Add(valueColumnColumn);
                        }
                        else                          // ! ContainsKey
                        {
                            listColumnColumn = new SysCollGen.List <CValueColumnColumn>();
                            listColumnColumn.Add(valueColumnColumn);
                            this.m_runProperties.m_sdictColumnsFkyPky.Add
                            (
                                valueColumnColumn.GetIdentityTT(),
                                listColumnColumn
                            );
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error_qmc41: nLineReadCount={0}, sLine={1}", nLineReadCount, sLine);
                        throw e;
                    }
                }         // EOWhile peek.
            }             // EOUsing FileStream.

            LABEL_RETURN_csh89_LABEL :;

            if (null == this.m_runProperties.m_sdictColumnsFkyPky)
            {
                this.m_runProperties.m_sdictColumnsFkyPky = new SysCollGen.SortedDictionary
                                                            <int, SysCollGen.List <CValueColumnColumn> >();
            }
            return;
        }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        System.IO.StreamReader rdr = null;
        try
        {
            lblMsg.Text = "";
            string strLine = "";
            string resp    = "";
            //binsert objDal = new binsert(ddlTableNames.SelectedItem.Text);
            BulkUploadCreditNote objDal = new BulkUploadCreditNote("CREDIT_NOTE_DETAILS");
            rdr = new System.IO.StreamReader(filepath);
            //string line;
            int cntinsert = 0, cntupdate = 0, cnterror = 0;
            while (rdr.Peek() != -1)
            {
                strLine = rdr.ReadLine();
                resp    = objDal.insertData(strLine);
                if (resp != "")
                {
                    if (resp.Trim().ToLower().StartsWith("data inserted"))
                    {
                        cntinsert = cntinsert + 1;
                    }
                    //else if (resp.Trim().ToLower().StartsWith("data exists"))
                    //{
                    //    cntupdate = cntupdate + 1;
                    //}
                    else
                    {
                        cnterror = cnterror + 1;
                        if (resp.Trim().ToLower().StartsWith("data exists"))
                        {
                            if (resp.Trim().ToLower().StartsWith("data exists"))
                            {
                                //writeLog(strLine, "Data exists against this SAP Credit Invoice Number.");
                                writeLog(strLine, resp);
                            }
                            else
                            {
                                writeLog(strLine, "");
                            }
                        }
                        else
                        {
                            writeLog(strLine, resp);
                        }
                    }
                }
            }

            //lblMsg.Text = "Data Inserted -- " + cntinsert + "</BR>" + " Data Updated -- " + cntupdate + "</BR>" + " Error -- " + cnterror;
            lblMsg.Text = "Data Inserted -- " + cntinsert + "</BR>" + " Error -- " + cnterror;
            rdr.Close();
            rdr.Dispose();
            if (errfilepath.Length > 0)
            {
                hlnkError.Visible     = true;
                hlnkError.NavigateUrl = "ErrorBulkUpload.aspx?erfnm=" + errfilepath;
            }
            else
            {
                hlnkError.Visible = false;
            }
        }
        catch (Exception ex)
        {
            rdr.Close();
            rdr.Dispose();
            lblMsg.Text = ex.Message;
        }
        errfilepath = "";
    }
    // Use this for initialization
    void Start()
    {
        //
        ////道路の端点を格納した道路データリスト(x1,z1,x2,z2)を作成する
        //
        // StreamRenderの新しいインスタンスを生成
        using (System.IO.StreamReader roadData = new System.IO.StreamReader("roaddata2.txt", System.Text.Encoding.UTF8))
        {
            //読み込んだ結果を格納する変数を宣言
            string roadStr = string.Empty;

            //読み込む文字がなくなるまで繰り返す
            while (roadData.Peek() >= 0)
            {
                //"roaddata.txt"を1行ずつ読み込む
                string roadBuffer = roadData.ReadLine();

                //読み込んだ1行の文字を格納して改行
                roadStr += roadBuffer + Environment.NewLine;
            }

            //格納した文字をカンマと改行で分割して配列に格納
            string[] roadArray = roadStr.Split(',', '\n');

            // Count用の変数 初期値は0
            int i = 0;

            //変数の初期化
            int x_point1 = 0;
            int y_point1 = 0;
            int x_point2 = 0;
            int y_point2 = 0;

            //Road型のListを宣言
            List <Road> roads = new List <Road>();

            //Road型のListに端点のつながり(道)を格納する
            //countの値がroadArrayの-4になるまでループ
            while (i < roadArray.Length - 4)
            {
                string str_x_point1 = roadArray[i];
                string str_y_point1 = roadArray[i + 1];
                string str_x_point2 = roadArray[i + 2];
                string str_y_poiny2 = roadArray[i + 3];

                x_point1 = int.Parse(str_x_point1);
                y_point1 = int.Parse(str_y_point1);
                x_point2 = int.Parse(str_x_point2);
                y_point2 = int.Parse(str_y_poiny2);

                //ListにAddメソッドでRoad型の変数を順次格納していく
                roads.Add(new Road(x_point1, y_point1, x_point2, y_point2));

                //4つずつ取り出しているのでcount+4
                i = i + 4;
            }


            //デバック用
            foreach (Road item in roads)
            {
                Debug.Log(item.x1 + "," + item.z1 + "," + item.x2 + "," + item.z2);
            }
        }
    }
Example #54
0
            /* ----------------------------------------------- Functions */
            #region Functions
            public static bool Exec(ref Setting settingBatchImporter,
                                    ref LibraryEditor_SpriteStudio6.Import.Setting settingImportInitial,
                                    string nameFileList,                                                /* Full-Path */
                                    string nameFileLog                                                  /* Full-Path */
                                    )
            {
//				const string messageLogPrefix = "Batch-Importer";

                if (true == string.IsNullOrEmpty(nameFileList))
                {
                    return(false);
                }

                /* Copy Setting (for Overwriting) */
                LibraryEditor_SpriteStudio6.Import.Setting settingImport = settingImportInitial;

                /* Get BaseDirectory (External File) */
#if false
                /* MEMO: Base directory is asset's directory when specify relative path in ListFile. */
//				string nameDirectoryBaseExternal = LibraryEditor_SpriteStudio6.Utility.File.NamePathRootNative;
#else
                /* MEMO: Base directory is ListFile's directory when specify relative path in ListFile. */
                string nameFile;
                string nameExternal;
                LibraryEditor_SpriteStudio6.Utility.File.PathSplit(out NameFolderBaseExternal, out nameFile, out nameExternal, nameFileList);
#endif
                NameFolderBaseExternal = PathNormalizeDelimiter(NameFolderBaseExternal, true);

                NameFolderRootAsset = "/";
                NameFolderRootAsset = PathNormalizeDelimiter(NameFolderRootAsset, true);

                NameBaseFolderSetting = string.Copy(NameFolderBaseExternal);
                NameBaseFolderAsset   = string.Copy(NameFolderRootAsset);
                NameBaseFolderData    = string.Copy(NameFolderBaseExternal);

                /* Set Log-File */
                System.IO.StreamWriter streamLog = null;
                if (false == string.IsNullOrEmpty(nameFileLog))
                {
                    streamLog = new System.IO.StreamWriter(nameFileLog, false, System.Text.Encoding.Default);                           /* Overwrite */
                }
                LibraryEditor_SpriteStudio6.Utility.Log.StreamExternal = streamLog;

                /* Open List-File */
                System.IO.StreamReader streamList = new System.IO.StreamReader(nameFileList, System.Text.Encoding.Default);

                /* Log Date */
                System.DateTimeOffset dateTime = System.DateTimeOffset.Now;
                LibraryEditor_SpriteStudio6.Utility.Log.Message("[Date imported] " + dateTime.ToString(), true, false);                                                   /* External-File only */
                LibraryEditor_SpriteStudio6.Utility.Log.Message("[In charge] " + System.Environment.MachineName + " (" + System.Environment.UserName + ")", true, false); /* External-File only */

                /* Decode List-File (1 Line) */
                Mode = LibraryEditor_SpriteStudio6.Import.Setting.KindMode.SS6PU;
                int    indexLine     = 0;
                string textLine      = "";
                string textLineValid = "";
                bool   flagValid;
                while (0 <= streamList.Peek())
                {
                    /* Read & Trim 1-Line */
                    flagValid = true;
                    textLine  = streamList.ReadLine();
                    indexLine++;
                    switch (LibraryEditor_SpriteStudio6.Utility.ExternalText.TypeGetLine(out textLineValid, textLine))
                    {
                    case LibraryEditor_SpriteStudio6.Utility.ExternalText.KindType.COMMAND:
                        /* Setting Command */
                        flagValid = DecodeCommand(ref settingBatchImporter, ref settingImport, indexLine, textLineValid);
                        break;

                    case LibraryEditor_SpriteStudio6.Utility.ExternalText.KindType.NORMAL:
                        /* File-Name to import */
                        flagValid = ImportFile(ref settingBatchImporter, ref settingImport, indexLine, textLineValid);
                        break;

                    case LibraryEditor_SpriteStudio6.Utility.ExternalText.KindType.IGNORE:
                        /* Remarks */
                        flagValid = true;
                        break;

                    default:
                        LogError("Syntax Error [" + textLine + "]", indexLine);
                        flagValid = false;
                        break;
                    }

                    /* Check Stopping-Processing */
                    if ((false == flagValid) && (false == settingBatchImporter.FlagNotBreakOnError))
                    {
                        return(false);
                    }
                }

                /* Close List-File */
                if (null != streamList)
                {
                    streamList.Close();
                    streamList = null;
                }

                /* Close Log-File */
                if (null != streamLog)
                {
                    streamLog.Close();
                    streamLog = null;
                }
                LibraryEditor_SpriteStudio6.Utility.Log.StreamExternal = null;

                return(true);
            }
Example #55
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            TaskDialog taskDialog = new TaskDialog("Shared Parameter Creator");

            taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconNone;
            taskDialog.MainInstruction = "Are you sure you want to create the Shared Parameters file?";
            taskDialog.CommonButtons   = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;

            fullFile_Excel = txtCSVFile.Text;

            insertIntoProjectParameters = chkInsert.Checked;

            if (fullFile_Excel == string.Empty)
            {
                TaskDialog.Show("No File Provided", "Make sure you have created a file with the .csv extension.");
            }
            else
            {
                if (taskDialog.Show() == TaskDialogResult.Yes)
                {
                    try
                    {
                        Category                  category        = null;
                        CategorySet               categorySet     = null;
                        InstanceBinding           instanceBinding = null;
                        Autodesk.Revit.DB.Binding typeBinding     = null;
                        BindingMap                bindingMap      = null;

                        categorySet     = myCommandData.Application.Application.Create.NewCategorySet();
                        instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                        typeBinding     = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                        bindingMap      = myCommandData.Application.ActiveUIDocument.Document.ParameterBindings;

                        DefinitionFile sharedParametersFile;

                        string fileName = string.Empty;
                        string filePath = string.Empty;

                        filePath = Path.GetDirectoryName(fullFile_Excel);
                        fileName = Path.GetFileNameWithoutExtension(fullFile_Excel);

                        fullFile_Parameters = filePath + "\\" + fileName + ".txt";

                        // THE SHARED PARAMETER FILE
                        sharedParametersFile = OpenSharedParametersFile(myCommandData.Application.Application);

                        DefinitionGroup sharedParameterDefinition = null;
                        Definition      definition = null;

                        string strTextLine = string.Empty;

                        StreamReader objReader = new System.IO.StreamReader(fullFile_Excel);
                        System.Collections.Specialized.StringCollection parameterCollection = new System.Collections.Specialized.StringCollection();

                        while (objReader.Peek() != -1)
                        {
                            strTextLine = objReader.ReadLine();

                            parameterCollection.Add(strTextLine);
                        }

                        //REVIT TRANSACTION
                        Transaction trans = new Transaction(myRevitDoc, "Create Shared Parameters");

                        trans.Start();

                        foreach (string param in parameterCollection)
                        {
                            // A, appliesTo, CATEGORY
                            // B, sharedParameterGroup, SHARED PARAMETER GROUP
                            // C, parameterDataType, DATA TYPE
                            // D, bindType, BINDING TYPE
                            // E, PARAMETER NAME

                            string        appliesTo            = string.Empty;
                            string        groupUnder           = string.Empty;
                            string        sharedParameterGroup = string.Empty;
                            ParameterType parameterDataType;
                            parameterDataType = ParameterType.Text;
                            string parameterDataType_Test = string.Empty;
                            string bindType      = string.Empty;
                            string parameterName = string.Empty;

                            char[]   chrSeparator = new char[] { ',' };
                            string[] arrValues    = param.Split(chrSeparator, StringSplitOptions.None);

                            appliesTo              = arrValues[0];
                            sharedParameterGroup   = arrValues[1];
                            parameterDataType_Test = arrValues[2];
                            bindType      = arrValues[3];
                            parameterName = arrValues[4];

                            switch (parameterDataType_Test)
                            {
                            case "Text":
                                parameterDataType = ParameterType.Text;
                                break;

                            case "Integer":
                                parameterDataType = ParameterType.Integer;
                                break;

                            case "Number":
                                parameterDataType = ParameterType.Number;
                                break;

                            case "Length":
                                parameterDataType = ParameterType.Length;
                                break;

                            case "Area":
                                parameterDataType = ParameterType.Area;
                                break;

                            case "Volume":
                                parameterDataType = ParameterType.Volume;
                                break;

                            case "Angle":
                                parameterDataType = ParameterType.Angle;
                                break;

                            case "Slope":
                                parameterDataType = ParameterType.Slope;
                                break;

                            case "Currency":
                                parameterDataType = ParameterType.Currency;
                                break;

                            case "Mass Density":
                                parameterDataType = ParameterType.MassDensity;
                                break;

                            case "URL":
                                parameterDataType = ParameterType.URL;
                                break;

                            case "Material":
                                parameterDataType = ParameterType.Material;
                                break;

                            case "Image":
                                parameterDataType = ParameterType.Image;
                                break;

                            case "Yes/No":
                                parameterDataType = ParameterType.YesNo;
                                break;

                            default:
                                parameterDataType = ParameterType.Text;
                                break;
                            }

                            sharedParameterDefinition = sharedParametersFile.Groups.get_Item(sharedParameterGroup);

                            if ((sharedParameterDefinition == null))
                            {
                                sharedParameterDefinition = sharedParametersFile.Groups.Create(sharedParameterGroup);
                            }

                            category    = myCommandData.Application.ActiveUIDocument.Document.Settings.Categories.get_Item(appliesTo);
                            categorySet = myCommandData.Application.Application.Create.NewCategorySet();
                            categorySet.Insert(category);
                            instanceBinding = myCommandData.Application.Application.Create.NewInstanceBinding(categorySet);
                            typeBinding     = myCommandData.Application.Application.Create.NewTypeBinding(categorySet);

                            if ((parameterName != null))
                            {
                                definition = OpenDefinition(sharedParameterDefinition, parameterName, parameterDataType);
                            }

                            if (insertIntoProjectParameters)
                            {
                                if (bindType == "Type")
                                {
                                    bindingMap.Insert(definition, typeBinding, BuiltInParameterGroup.PG_DATA);
                                }
                                else
                                {
                                    bindingMap.Insert(definition, instanceBinding, BuiltInParameterGroup.PG_DATA);
                                }
                            }
                        }

                        //END REVIT TRANSACTION
                        trans.Commit();

                        objReader.Close();

                        TaskDialog.Show("File Created Sucessfully", "The Shared Parameter file was created successfully");
                    }
                    catch (Exception ex)
                    {
                        TaskDialog errorMessage = new TaskDialog("Create Shared Parameter Error");
                        errorMessage.MainInstruction = "An error occurrued while creating the Shared Parameter file." + "\n" + "Please read the following error message below";
                        errorMessage.MainContent     = ex.Message + Environment.NewLine + ex.Source;
                        errorMessage.Show();
                    }
                }
            }
        }
Example #56
0
        // private procedures

        /// <summary>  Private method that actually parses the input to read a ChemFile
        /// object.
        ///
        /// </summary>
        /// <returns> A ChemFile containing the data parsed from input.
        /// </returns>
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence chemSequence = file.Builder.newChemSequence();

            int number_of_atoms = 0;

            SupportClass.Tokenizer tokenizer;

            try
            {
                System.String line = input.ReadLine();
                while (input.Peek() != -1 && line != null)
                {
                    // parse frame by frame
                    tokenizer = new SupportClass.Tokenizer(line, "\t ,;");

                    System.String token = tokenizer.NextToken();
                    number_of_atoms = System.Int32.Parse(token);
                    System.String info = input.ReadLine();

                    IChemModel      chemModel      = file.Builder.newChemModel();
                    ISetOfMolecules setOfMolecules = file.Builder.newSetOfMolecules();

                    IMolecule m = file.Builder.newMolecule();
                    m.setProperty(CDKConstants.TITLE, info);

                    for (int i = 0; i < number_of_atoms; i++)
                    {
                        line = input.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        if (line.StartsWith("#") && line.Length > 1)
                        {
                            System.Object comment = m.getProperty(CDKConstants.COMMENT);
                            if (comment == null)
                            {
                                comment = "";
                            }
                            //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                            comment = comment.ToString() + line.Substring(1).Trim();
                            m.setProperty(CDKConstants.COMMENT, comment);
                            //logger.debug("Found and set comment: ", comment);
                        }
                        else
                        {
                            double x = 0.0f, y = 0.0f, z = 0.0f;
                            double charge = 0.0f;
                            tokenizer = new SupportClass.Tokenizer(line, "\t ,;");
                            int fields = tokenizer.Count;

                            if (fields < 4)
                            {
                                // this is an error but cannot throw exception
                            }
                            else
                            {
                                System.String atomtype = tokenizer.NextToken();
                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                x = (System.Double.Parse(tokenizer.NextToken()));
                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                y = (System.Double.Parse(tokenizer.NextToken()));
                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                z = (System.Double.Parse(tokenizer.NextToken()));

                                if (fields == 8)
                                {
                                    //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                    charge = (System.Double.Parse(tokenizer.NextToken()));
                                }

                                IAtom atom = file.Builder.newAtom(atomtype, new Point3d(x, y, z));
                                atom.setCharge(charge);
                                m.addAtom(atom);
                            }
                        }
                    }

                    setOfMolecules.addMolecule(m);
                    chemModel.SetOfMolecules = setOfMolecules;
                    chemSequence.addChemModel(chemModel);
                    line = input.ReadLine();
                }
                file.addChemSequence(chemSequence);
            }
            catch (System.IO.IOException e)
            {
                // should make some noise now
                file = null;
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                //logger.error("Error while reading file: ", e.Message);
                //logger.debug(e);
            }
            return(file);
        }
        public static bool ImportSSPJBatch(string FileImportList)
        {
            /* Create SSPJ Import-Setting */
            /* MEMO: Default-Values are same SSPJ-Importer's Default. (except "FlagConfirmOverWrite") */
            LibraryEditor_SpriteStudio.SettingImport DataSettingImport = new LibraryEditor_SpriteStudio.SettingImport();
            DataSettingImport.TextureSizePixelMaximum             = 8192;
            DataSettingImport.CollisionThicknessZ                 = 1.0f;
            DataSettingImport.FlagAttachRigidBody                 = true;
            DataSettingImport.FlagAttachControlGameObject         = true;
            DataSettingImport.FlagConfirmOverWrite                = false;      /* Caution!: This item is different */
            DataSettingImport.FlagCreateProjectFolder             = true;
            DataSettingImport.FlagGetAnimationReferencedPartsRoot = true;
            DataSettingImport.FlagGetMaterialPartsRoot            = true;
            DataSettingImport.FlagGetTextureMaterial              = true;
            DataSettingImport.FlagDataCalculateInAdvance          = true;
            DataSettingImport.FlagDataCompress = false;                         /* Caution!: This item is different */

            UnityEngine.Object ObjectSelected = Selection.activeObject;
            if (null == ObjectSelected)
            {                   /* No Selected *//* Error */
                NameBaseFolderAsset = "Assets";
            }
            else
            {                   /* Selected */
                NameBaseFolderAsset = AssetDatabase.GetAssetPath(ObjectSelected);
            }

            /* Open List-File */
            System.IO.StreamReader FileReader = new System.IO.StreamReader(FileImportList, System.Text.Encoding.Default);

            /* Decode List-File (1 Line) */
            string TextLineOriginal = "";
            string TextLineTrimmed  = "";
            char   PrifixLine;

            while (0 <= FileReader.Peek())
            {
                /* Read & Trim 1-Line */
                TextLineOriginal = FileReader.ReadLine();
                TextLineTrimmed  = Decode.TextTrim(TextLineOriginal);

                /* Line-Top-Command Decode */
                if (false == String.IsNullOrEmpty(TextLineTrimmed))
                {
                    PrifixLine = TextLineTrimmed[0];                            /* Get Top-Letter */
                    switch (PrifixLine)
                    {
                    case PrefixChangeSetting:
                    {
                        /* Remove Top-Letter & Decode Command */
                        Decode.ChangeSetting(ref DataSettingImport, TextLineTrimmed.Remove(0, 1));
                    }
                    break;

                    case PrefixRemarks:
                        /* MEMO: Text of this line will be ignored . */
                        break;

                    default:
                        /* File-Import */
                        Decode.Import(ref DataSettingImport, TextLineTrimmed);
                        break;
                    }
                }
            }

            /* Close List-File */
            FileReader.Close();
        /// <summary>
        /// Such as CustTable might be a child of three other tables, according to Dynamics AX 2012 AOT
        /// (thus three key-value pairs for CustTable).
        /// </summary>
        /// <returns>SortedDictionary, key=ChildTableName (+" "+ParentTableName), value=CValueTableTable.
        /// Never null.</returns>
        /// <remarks>Caution: In this method pair, GetSortDictFor* ChildParents & ParentChilds,
        /// each method initializes both itself and the other sdict, when appropriate.
        /// </remarks>
        public void BuildSortDictForChildParents_and_ParentChilds()
        {
            SysIo.FileStream   fileStream;
            SysIo.StreamReader streamReader;
            SysCollGen.List <CValueTableTable> listTableTable;
            CValueTableTable valueTableTable_CP, valueTableTable_PC;

            char[]   cDelims = { '\t' };
            string[] sSplits;
            string   sLine = "Initialize.";
            string   sChildTableName, sParentTableName;
            int      nKeyTT;
            int      nLineReadCount = 0;

            //

            if (null != this.m_runProperties.m_sdictChildParents)
            {
                goto LABEL_RETURN_msj58_LABEL;
            }
            else
            {
                this.m_runProperties.m_sdictChildParents = new SysCollGen.SortedDictionary                  // C-P
                                                           <string, SysCollGen.List <CValueTableTable> >();

                this.m_runProperties.m_sdictParentChilds = new SysCollGen.SortedDictionary                  // P-C
                                                           <string, SysCollGen.List <CValueTableTable> >();
            }

            using
            (
                fileStream = new SysIo.FileStream
                             (
                    this.m_runProperties.GetPathToInputDelimFiles()
                    + this.m_runProperties.GetInputDelimFilesCommonPrefix()
                    + this.m_runProperties.GetDelimFileChildParents(),
                    SysIo.FileMode.Open,
                    SysIo.FileAccess.Read,
                    SysIo.FileShare.Read
                             )
            )
            {
                streamReader = new SysIo.StreamReader(fileStream);


                while (streamReader.Peek() >= 0)
                {
                    try
                    {
                        nLineReadCount++;
                        sLine   = streamReader.ReadLine();
                        sSplits = sLine.Split(cDelims, StringSplitOptions.RemoveEmptyEntries);
                        if (3 > sSplits.Length)
                        {
                            continue;
                        }
                        if (sSplits[0].StartsWith("//"))
                        {
                            continue;
                        }
                        if (sSplits[0].Trim().Length == 0)
                        {
                            continue;
                        }

                        nKeyTT           = Convert.ToInt32(sSplits[0]);
                        sChildTableName  = sSplits[1];
                        sParentTableName = sSplits[2];

                        valueTableTable_CP = new CValueTableTable
                                             (
                            sParentTableName,                             // IComparable.
                            nKeyTT,
                            sChildTableName,
                            sParentTableName
                                             );


                        // Child-Parents
                        if (this.m_runProperties.m_sdictChildParents.ContainsKey(valueTableTable_CP.GetKeyChildDelimParent()))
                        {
                            listTableTable = this.m_runProperties.m_sdictChildParents[valueTableTable_CP.GetKeyChildDelimParent()];
                            listTableTable.Add(valueTableTable_CP); // Also SORTED, by Parent, earlier during X++ time.
                        }
                        else                                        // ! ContainsKey
                        {
                            listTableTable = new SysCollGen.List <CValueTableTable>();
                            listTableTable.Add(valueTableTable_CP);
                            this.m_runProperties.m_sdictChildParents.Add
                            (
                                valueTableTable_CP.GetKeyChildDelimParent(),
                                listTableTable
                            );
                        }


                        // Parent-Childs

                        // Clone vtt, need different IComparable string to sort by.
                        valueTableTable_PC = valueTableTable_CP.CloneThis(valueTableTable_CP.GetTableNameChild());

                        if (this.m_runProperties.m_sdictParentChilds.ContainsKey(valueTableTable_PC.GetKeyParentDelimChild()))
                        {
                            listTableTable = this.m_runProperties.m_sdictParentChilds[valueTableTable_PC.GetKeyParentDelimChild()];
                            listTableTable.Add(valueTableTable_PC); // SORTED, by Child, by IComparable.
                        }
                        else                                        // ! ContainsKey
                        {
                            listTableTable = new SysCollGen.List <CValueTableTable>();
                            listTableTable.Add(valueTableTable_PC);
                            this.m_runProperties.m_sdictParentChilds.Add
                            (
                                valueTableTable_PC.GetKeyParentDelimChild(),
                                listTableTable
                            );
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error_cys78: nLineReadCount={0}, sLine={1}", nLineReadCount, sLine);
                        throw e;
                    }
                }         // EOWhile peek.
            }             // EOUsing FileStream.

            LABEL_RETURN_msj58_LABEL :;

            if (null == this.m_runProperties.m_sdictChildParents)
            {
                this.m_runProperties.m_sdictChildParents =
                    new SysCollGen.SortedDictionary
                    <string, SysCollGen.List <CValueTableTable> >();

                this.m_runProperties.m_sdictParentChilds =
                    new SysCollGen.SortedDictionary
                    <string, SysCollGen.List <CValueTableTable> >();
            }

            return;
        }
Example #59
0
    public Tuple <string, string> LeerArchivo(string ruta)
    {
        //string newruta = ruta; //Server.MapPath("~") + "/temp/afil25/ 24_10_2019AFIL25/AFIL25.C001";
        System.IO.StreamReader fd             = System.IO.File.OpenText(ruta);
        System.IO.StreamWriter ArchivoSalida2 = new System.IO.StreamWriter(ruta + DateTime.Now.Year + ".txt");
        string filas = "";

        filas = fd.ReadLine();
        while (fd.Peek() > -1)
        {
            if (filas.Contains("SUBDELG."))
            {
                subdel = filas.Substring((filas.LastIndexOf("SUBDELG.") + 12), 2);
            }
            if (filas.Contains("DELEGACION  "))
            {
                Delegacion = filas.Substring((filas.LastIndexOf("DELEGACION  ") + 12), 2);
            }
            if (filas.Contains("CICLO ACTUALIZACION NUM."))
            {
                ciclo = filas.Substring((filas.LastIndexOf("CICLO ACTUALIZACION NUM.") + 24), 4);
            }
            if (filas.Contains("  GUIA "))
            {
                guia = filas.Substring((filas.LastIndexOf("  GUIA ") + 7), 5);
            }
            if (filas.Contains("MOVIMIENTOS OPERADOS DE ASEGURADOS, PATRONES"))
            {
                fecha = filas.Substring((filas.LastIndexOf("MOVIMIENTOS OPERADOS DE ASEGURADOS, PATRONES") + 66), 10);
            }
            filas = fd.ReadLine();
            if ((filas.Length == 132))
            {
                if (!filas.Contains("DELEGACION"))
                {
                    if (!filas.Contains("NO.SEGURO SOCIAL"))
                    {
                        if (!filas.Contains("NO.SEG.SOC.CORR"))
                        {
                            filas = filas.Insert(0, Delegacion + ";");
                            filas = filas.Insert(3, subdel + ";");
                            filas = filas.Insert(6, ciclo.Trim().PadLeft(4, '0') + ";");
                            filas = filas.Insert(11, guia + ";");
                            filas = filas.Insert(34, ";");
                            filas = filas.Insert(64, ";");
                            filas = filas.Insert(68, ";");
                            filas = filas.Insert(73, ";");
                            filas = filas.Insert(78, ";");
                            filas = filas.Insert(83, ";");
                            filas = filas.Insert(99, ";");
                            filas = filas.Insert(102, ";");
                            filas = filas.Insert(114, ";");
                            filas = filas.Insert(120, ";");
                            filas = filas.Insert(125, ";");
                            filas = filas.Insert(133, ";");
                            filas = filas.Insert(141, ";");
                            filas = filas.Insert(146, ";");
                            filas = filas.Insert(150, ";");
                            filas = filas.Insert(162, ";");
                            ArchivoSalida2.WriteLine(filas);
                        }
                    }
                }
            }
        }
        ArchivoSalida2.Close();
        fd.Close();
        return(Tuple.Create(ciclo, fecha));
    }
Example #60
0
        public static void start()
        {
            Debug.Log("start document generator ");

            Debug.Log(System.Environment.CurrentDirectory);


            string path = System.Environment.CurrentDirectory + "/Assets/JOKER/Scripts/Novel/Components/";

            //指定フォルダ以下のディレクトリ全部読み込み
            string[] files = System.IO.Directory.GetFiles(
                path, "*", System.IO.SearchOption.AllDirectories);


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

            for (var i = 0; i < files.Length; i++)
            {
                System.Console.WriteLine(files [i]);

                System.IO.StreamReader cReader = (
                    new System.IO.StreamReader(files[i], System.Text.Encoding.Default)
                    );


                bool flag_doc = false;
                // 読み込みできる文字がなくなるまで繰り返す
                while (cReader.Peek() >= 0)
                {
                    // ファイルを 1 行ずつ読み込む
                    string stBuffer = cReader.ReadLine().Trim();

                    if (stBuffer == "")
                    {
                        //continue;
                    }

                    if (stBuffer == "[doc]")
                    {
                        flag_doc = true;
                    }

                    if (flag_doc == true)
                    {
                        arrDoc.Add(stBuffer);
                    }

                    if (stBuffer == "[_doc]")
                    {
                        flag_doc = false;
                    }
                }

                // cReader を閉じる (正しくは オブジェクトの破棄を保証する を参照)
                cReader.Close();
            }


            DocManager dm = new DocManager();

            //パーサーを動作させる

            foreach (string doc in arrDoc)
            {
                System.Console.WriteLine(doc);
                dm.addInfo(doc);
            }

            dm.showInfo();

            Debug.Log("finish export doc ");
        }