Пример #1
3
        public static string ExtractTextFromPdf(string path)
        {
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();

            using (PdfReader reader = new PdfReader(path))
            {
                StringBuilder text = new StringBuilder();

                for (int page = 1; page <= reader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

                    string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.Append(currentText);
                }

                System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
                file.WriteLine(text);

                file.Close();

                return text.ToString();
            }
        }
Пример #2
2
        public void TryPrint(string zplCommands)
        {
            try
            {
                // Open connection
                System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
                client.Connect(this.m_IPAddress, this.m_Port);

                // Write ZPL String to connection
                System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream());
                writer.Write(zplCommands);
                writer.Flush();

                // Close Connection
                writer.Close();
                client.Close();
            }
            catch (Exception ex)
            {
                this.m_ErrorCount += 1;
                if(this.m_ErrorCount < 10)
                {
                    System.Threading.Thread.Sleep(5000);
                    this.TryPrint(zplCommands);
                }
                else
                {
                    throw ex;
                }
            }
        }
        static void Main(string[] args)
        {
            IWebDriver driver = new FirefoxDriver();
            const int idInicio = 0;
            const int idFim = 1000;

            int id = idInicio;
            String url = "http://fcv.matheusacademico.com.br/Aluno/frmAlunoAlteracao.asp?id=";

            driver.Navigate().GoToUrl(url + id);
            driver.Manage().Window.Maximize();

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\AllStudents1.txt", true))
            {
                while (id < idFim)
                {
                    driver.Navigate().GoToUrl(url + id);
                    IWebElement nome = driver.FindElement(By.Id("txtNome"));
                    IWebElement email = driver.FindElement(By.Id("txtmail_maior"));

                    if (nome.GetAttribute("value").ToString() != "")
                        file.WriteLine(id.ToString() + " - " + nome.GetAttribute("value").ToString() + " - " + email.GetAttribute("value").ToString());
                    id++;
                }
            }
        }
Пример #4
0
        private void AnalyzeTweets(string inputFilePath)
        {
            if (inputFilePath == string.Empty)
                return;
            if (!System.IO.File.Exists(inputFilePath))
                return;

            int counter = 0;
            string line;

            System.IO.StreamReader sourceFile = new System.IO.StreamReader(inputFilePath);
            System.IO.StreamWriter ft1File = new System.IO.StreamWriter(outputFt1);
            System.IO.StreamWriter ft2File = new System.IO.StreamWriter(outputFt2);

            while ((line = sourceFile.ReadLine()) != null)
            {
                AnalyzeTweet(line);
                ft2File.WriteLine(GetMedian(numOfUniqueWords).ToString());
            }
            foreach(KeyValuePair<string, int> item in wordCount )
            {
                ft1File.WriteLine(String.Format("{0}\t{1}", item.Key, item.Value.ToString()));
            }
            ft1File.Flush();
            ft1File.Close();

            ft2File.Flush();
            ft2File.Close();

            lblStatus.Text = "Done.";
        }
Пример #5
0
        static void Main(string[] args)
        {
            string nombreFichero = "log_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt";
            Process[] procesos = null;
            string wanted = "java";

            using (System.IO.StreamWriter fichero = new System.IO.StreamWriter(nombreFichero))
            {
                fichero.WriteLine("==========================================================================================");
                fichero.WriteLine("==========================================================================================");
                fichero.WriteLine("Fecha y hora de inicio: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                fichero.WriteLine("");
                fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tObteniendo listado de procesos.");

                procesos = Process.GetProcesses();

                fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tListado de procesos obtenido.");
                fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tProceso a buscar: " + wanted);
                foreach (Process proceso in procesos)
                {
                    if (proceso.ProcessName.ToLower() == wanted)
                    {
                        fichero.Write(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tProceso " + wanted + " ("+ proceso.Id +") encontrado...");
                        Process p = Process.GetProcessById(proceso.Id);
                        p.Kill();
                        fichero.Write(" eliminado.\n");
                    }
                }
                fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tBúsqueda finalizada.");
            }
        }
Пример #6
0
        public static void WriteLog(string UserAgent, string Url, string Message, string StackTrace)
        {
            try
            {
                //Write Log
                var folderPath = string.Format(@"D:\SBSV\{0}", DateTime.Now.ToString("dd_MM_yyyy"));

                if (!System.IO.Directory.Exists(folderPath))
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }

                var filePath = string.Format(@"{0}\{1}.txt", folderPath, DateTime.Now.ToString("dd_MM_yyyy"));
                System.IO.TextWriter tw = new System.IO.StreamWriter(filePath, true);
                tw.WriteLine("UserAgent {0}", UserAgent);
                tw.WriteLine("Date {0}", DateTime.Now);
                tw.WriteLine("Url {0} ", Url);
                tw.WriteLine("Message {0} ", Message);
                tw.WriteLine("Log Contents: ");
                tw.WriteLine(StackTrace);
                tw.WriteLine("--------------------------------------------------------------");
                tw.Close();
                //Write Log
            }
            // ReSharper disable once EmptyGeneralCatchClause
            catch
            {
            }
        }
		/// <summary> <p>Creates source code for a Group and returns a GroupDef object that 
		/// describes the Group's name, optionality, repeatability.  The source 
		/// code is written under the given directory.</p>  
		/// <p>The structures list may contain [] and {} pairs representing 
		/// nested groups and their optionality and repeastability.  In these cases
		/// this method is called recursively.</p>
		/// <p>If the given structures list begins and ends with repetition and/or 
		/// optionality markers the repetition and optionality of the returned 
		/// GroupDef are set accordingly.</p>  
		/// </summary>
		/// <param name="structures">a list of the structures that comprise this group - must 
		/// be at least 2 long
		/// </param>
		/// <param name="baseDirectory">the directory to which files should be written
		/// </param>
		/// <param name="message">the message to which this group belongs
		/// </param>
		/// <throws>  HL7Exception if the repetition and optionality markers are not  </throws>
		/// <summary>      properly nested.  
		/// </summary>
		public static NuGenGroupDef writeGroup(NuGenStructureDef[] structures, System.String groupName, System.String baseDirectory, System.String version, System.String message)
		{
			
			//make base directory
			if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/")))
			{
				baseDirectory = baseDirectory + "/";
			}
			System.IO.FileInfo targetDir = NuGenSourceGenerator.makeDirectory(baseDirectory + NuGenSourceGenerator.getVersionPackagePath(version) + "group");
			
			NuGenGroupDef group = getGroupDef(structures, groupName, baseDirectory, version, message);
			System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(new System.IO.StreamWriter(targetDir.FullName + "/" + group.Name + ".java", false, System.Text.Encoding.Default).BaseStream, new System.IO.StreamWriter(targetDir.FullName + "/" + group.Name + ".java", false, System.Text.Encoding.Default).Encoding);
			out_Renamed.Write(makePreamble(group, version));
			out_Renamed.Write(makeConstructor(group, version));
			
			NuGenStructureDef[] shallow = group.Structures;
			for (int i = 0; i < shallow.Length; i++)
			{
				out_Renamed.Write(makeAccessor(group, i));
			}
			out_Renamed.Write("}\r\n");
			out_Renamed.Flush();
			out_Renamed.Close();
			
			return group;
		}
Пример #8
0
        static void Main(string[] args)
        {
            string[] funcListUrls = {
                                        //"http://www.xqueryfunctions.com/xq/c0008.html",
                                        //"http://www.xqueryfunctions.com/xq/c0011.html",
                                        //"http://www.xqueryfunctions.com/xq/c0002.html",
                                        //"http://www.xqueryfunctions.com/xq/c0013.html",
                                        //"http://www.xqueryfunctions.com/xq/c0015.html",
                                        "http://www.xqueryfunctions.com/xq/c0026.html",
                                        "http://www.xqueryfunctions.com/xq/c0033.html",
                                        "http://www.xqueryfunctions.com/xq/c0021.html",
                                        "http://www.xqueryfunctions.com/xq/c0023.html",
                                        "http://www.xqueryfunctions.com/xq/c0072.html"
                                    };

            foreach (string funcListUrl in funcListUrls)
            {
                FuncList[] funcLists = ParseFuncList(funcListUrl);
                foreach (FuncList funcList in funcLists)
                {
                    System.IO.StreamWriter testFile = new System.IO.StreamWriter(TESTCASE_FILE, true);
                    testFile.WriteLine("\n<!-- " + funcList.funcName + " - " + funcList.subcat + ": " + funcList.funclist.Length + " cases -->");
                    testFile.Close();
                    testFile = null;
                    foreach (string name in funcList.funclist)
                    {
                        string url = "http://www.xqueryfunctions.com/xq/functx_" + name + ".html";
                        Console.WriteLine("Parsing " + url + " ...");
                        ParseURL(funcList.funcName, funcList.subcat, url);
                    }
                }
            }
        }
Пример #9
0
        /// <summary>
        /// ドロップ情報をCSVに出力する
        /// </summary>
        /// <param name="dropList"></param>
        public static void OutputCsv(List<DatDropData> dropList)
        {
            if (dropList.Count == 0)
            {
                MessageBox.Show("ドロップ情報が0件のため、処理を中止します。");
                return;
            }

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            //保存先の初期値(マイドキュメント)
            dlg.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            dlg.Title = "保存先のファイルを選択してください";
            dlg.FileName = "ドロップ情報";
            dlg.Filter = "CSVファイル(*.csv)|*.csv";
            if (dlg.ShowDialog() == true)
            {
                try
                {
                    using (var sw = new System.IO.StreamWriter(dlg.FileName, false, System.Text.Encoding.GetEncoding("Shift_JIS")))
                    {
                        //ダブルクォーテーションで囲む
                        Func<string, string> dqot = (str) => { return "\"" + str.Replace("\"", "\"\"") + "\""; };
                        foreach (DatDropData d in dropList)
                            sw.WriteLine(dqot(d.DropWinDecision) + "," + dqot(d.DropKanmusuName));
                    }
                    MessageBox.Show("保存しました。");
                }
                catch (SystemException ex)
                {
                    MessageBox.Show(ClsConst.ErrorMessage);
                    ClsLogWrite.LogWrite("CSV出力中にエラーが起きました。",ex);
                }
            }
        }
Пример #10
0
        public static void Main(string[] args)
        {
            Defrag.IFileSystem fileSystem = new Defrag.Win32FileSystem("C:");
            Defrag.Optimizer optimizer = new Defrag.Optimizer(fileSystem);

            Defrag.Win32ChangeWatcher watcher = new Defrag.Win32ChangeWatcher("C:\\");
            System.IO.TextWriter log = new System.IO.StreamWriter(System.Console.OpenStandardOutput());

            while (true)
            {
                String path = watcher.NextFile();
                if (path != null)
                {
                    try
                    {
                        optimizer.DefragFile(path, log);
                    }
                    catch (Win32Exception ex)
                    {
                        log.WriteLine(ex.Message);
                        log.WriteLine("* * Failed! * *");
                    }
                    finally
                    {
                        log.WriteLine();
                        log.Flush();
                    }
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }
Пример #11
0
 protected override void OnStop()
 {
     using (System.IO.StreamWriter sw = new System.IO.StreamWriter("E:\\log.txt", true))
     {
         sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");
     }
 }
        public static void Error()
        {
            IntPtr ptr;

            Assert.Throws<Exception>(() => DynamicLibrary.Open("NOT_EXISTING"));

            string failure = "FAILURE";
            var fs = new System.IO.StreamWriter(System.IO.File.OpenWrite(failure));
            fs.Write("foobar");
            fs.Close();

            Assert.IsTrue(System.IO.File.Exists(failure));
            Assert.Throws<Exception>(() => DynamicLibrary.Open(failure));

            System.IO.File.Delete(failure);

            var dl = DynamicLibrary.Open(DynamicLibrary.Decorate("uv"));

            Assert.IsTrue(dl.TryGetSymbol("uv_default_loop", out ptr));
            Assert.AreNotEqual(ptr, IntPtr.Zero);

            Assert.IsFalse(dl.TryGetSymbol("NOT_EXISTING", out ptr));
            Assert.AreEqual(ptr, IntPtr.Zero);

            Assert.Throws<Exception>(() => dl.GetSymbol("NOT_EXISTING"));

            Assert.IsFalse(dl.Closed);
            dl.Close();
            Assert.IsTrue(dl.Closed);
        }
Пример #13
0
        /// <summary>
        /// Saves the colourz
        /// </summary>
        public void save()
        {
            if (!System.IO.Directory.Exists(Constants.CACHE_PATH))
            {
                System.IO.Directory.CreateDirectory(Constants.CACHE_PATH);
            }

            if (!System.IO.Directory.Exists(Constants.CACHE_PATH))
            {
                Console.WriteLine("Created directory");
                System.IO.Directory.CreateDirectory(Constants.CACHE_PATH);
            }

            System.IO.File.WriteAllBytes(Constants.CACHE_PATH + "Saved Colours.txt", new byte[0]);
            System.IO.StreamWriter file = new System.IO.StreamWriter(Constants.CACHE_PATH + "Saved Colours.txt", true);
            
            string saveText = "";
            for(int i = 0; i < stack.Children.Count; i++)
            {
                SavedColour s = (SavedColour)stack.Children[i];

                if(i != stack.Children.Count)
                    saveText += s.hex + ";";
            }
            file.WriteLine(saveText);
            file.Flush();
            file.Close();
        }
Пример #14
0
        protected override void OnStart(string[] args)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("E:\\log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "start.");
            }

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<HelloWorld>()
                .WithIdentity("myJob", "group1")
                .Build();

            //ITrigger trigger = TriggerBuilder.Create()
            //  .WithIdentity("myTrigger", "group1")
            //  .StartNow()
            //  .WithSimpleSchedule(x => x
            //      .WithIntervalInHours(1)
            //      .RepeatForever())
            //  .Build();
            ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("myTrigger", "group1")
            .WithCronSchedule("0/5 * * * * ?")
            .ForJob("myJob", "group1")
            .Build();
            sched.ScheduleJob(job, trigger);
        }
Пример #15
0
        public static void Main()
        {
            try
            {
                System.IO.File.Delete("debug.txt");
                tFileIO = System.IO.File.CreateText("debug.txt");

                IRCServices = new ServicesDaemon(BlackLight.Services.Error.Errors.ALL);
                IRCServices.onOutPut +=new BlackLight.Services.ServicesDaemon.onOutPutEventHandler(IRCServices_onOutPut);
                //Dim tDataBase As New DataBase
                //tDataBase.Test()
                //Exit Sub
                //CallyThingy()
                //System.Threading.Thread.Sleep(500);

                IRCServices.Begin();
                // Threading.Thread.CurrentThread.Suspend()
                while (true)
                {
                    System.Threading.Thread.Sleep(2000);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Connect Error: " + ex.Message + " " + ex.StackTrace);
                Console.ReadLine();
            }
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            RadioButton rbFullScreen = UIHelpers.FindChild<RadioButton>(this, "rbFullScreen");

            if (rbFullScreen.IsChecked.Value)
            {
                Settings.GetInstance().Mode = Settings.ScreenMode.Fullscreen;
                PageNavigator.MainWindow.WindowStyle = WindowStyle.None;
                PageNavigator.MainWindow.WindowState = WindowState.Maximized;
                PageNavigator.MainWindow.Focus();
            }
            else
            {
                Settings.GetInstance().Mode = Settings.ScreenMode.Windowed;
            }

            ComboBox cbLanguage = UIHelpers.FindChild<ComboBox>(this, "cbLanguage");
            AppSettings.GetInstance().setLanguage((Language)cbLanguage.SelectedItem);

            System.IO.StreamWriter file = new System.IO.StreamWriter(AppSettings.getCommonApplicationDataPath() + "\\game.settings");
            file.WriteLine(AppSettings.GetInstance().getLanguage().Name);
            file.WriteLine(Settings.GetInstance().Mode);
            file.Close();

            //PageNavigator.NavigateTo(new PageStartMenu());
        }
        private void submitButton_Click(object sender, RoutedEventArgs e)
        {
            var login = loginTextBox.Text;
            var pass = passwordTextBox.Password;

            Action<String> status = s => {
                statusLabel.Content = s;
                statusLabel.ToolTip = s;
            };

            try {
                channelFactory = new DuplexChannelFactory<IService>(new ClientImplementation(_MainWindow), "DnDServiceEndPoint");
                server = channelFactory.CreateChannel();

                if (server.Login(login, pass)) {
                    _MainWindow.InitializeServer(channelFactory, server);
                    this.DialogResult = true;
                } else {
                    statusLabel.Content = "Login lub hasło nie są poprawne!";
                    return;
                }

            } catch (Exception ex) {
                statusLabel.Content = "Nastąpił błąd! Spróbuj ponownie";
                System.IO.StreamWriter file = new System.IO.StreamWriter("log.txt");
                file.WriteLine(ex.ToString());
                file.Close();
                return;
            }
            this.Close();
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            //string xml;
               Contact contact = new Contact();

            contact.companyName = txtCompany.Text;
            contact.firstName = txtFName.Text;
            contact.middleName = txtMName.Text;
            contact.lastName = txtLName.Text;
            contact.liscence = txtLicense.Text;
            contact.phone = txtPhone.Text;
            contact.cell = txtCell.Text;
            contact.email = txtEmail.Text;
            contact.buildingLiscence = txtBuildingLicense.Text;
            contact.streetNumber = txtStreetNumber.Text;
            contact.streetName = txtStreetName.Text;
            contact.type = txtType.Text;
            contact.streetName2 = txtStreetName2.Text;
            contact.city = txtCity.Text;
            contact.state = txtState.Text;
            contact.zip = txtZip.Text;
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"Contact.xml");
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(contact.GetType());
            x.Serialize(file, contact);
            file.Close();
        }
Пример #19
0
 private static void CollectnPopulatePerfCounters()
 {
     try
     {
         foreach (var pc in System.Diagnostics.PerformanceCounterCategory.GetCategories())
         {
                 try
                 {
                     foreach (var insta in pc.GetInstanceNames())
                     {
                         try
                         {
                             foreach (PerformanceCounter cntr in pc.GetCounters(insta))
                             {
                                 using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\amit.txt", true))
                                 {
                                     sw.WriteLine("--------------------------------------------------------------------");
                                     sw.WriteLine("Category Name : " + pc.CategoryName);
                                     sw.WriteLine("Counter Name : " + cntr.CounterName);
                                     sw.WriteLine("Explain Text : " + cntr.CounterHelp);
                                     sw.WriteLine("Instance Name: " + cntr.InstanceName);
                                     sw.WriteLine("Value : " + Convert.ToString(Math.Round(cntr.NextValue(), 2)) + "%");
                                     sw.WriteLine("Counter Type : " + cntr.CounterType);
                                     sw.WriteLine("--------------------------------------------------------------------");
                                 }
                             }
                         }
                         catch (Exception) { }
                     }
                 }
                 catch (Exception) { }
         }
     }
     catch (Exception) { }
 }
Пример #20
0
        private void AddFileEventLog(string message, EventLogEntryType logType = EventLogEntryType.Information, string moduleName = "", int codeErreur = 0, bool fromWindowsLogEvent = false)
        {
            System.IO.StreamWriter w = null;
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            try {
                string strPath = System.IO.Path.GetDirectoryName(_logFilePath);
                if (!System.IO.Directory.Exists(strPath))
                    System.IO.Directory.CreateDirectory(strPath);

                w = new System.IO.StreamWriter(_logFilePath, true, System.Text.Encoding.Default);

                str.AppendFormat("[{0,-10:G} - {1,-8:G}]", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
                str.AppendFormat(" {0}", Const.DEFAULT_APPLICATION_NAME);
                if (!string.IsNullOrEmpty(moduleName))
                    str.AppendFormat(" ({0})", moduleName);
                str.AppendFormat(" - {0}", logType.ToString());
                if (codeErreur != 0)
                    str.AppendFormat(" - Code : {0}", codeErreur);

                str.Append("\r\n");
                str.Append(message);
                str.Append("\r\n");

                w.WriteLine(str.ToString());
            } catch (Exception ex) {
                if (!fromWindowsLogEvent) {
                    AddWindowsEventLog("Impossible d'écrire dans le fichier de log : " + _logFilePath + "\r\n" + message + "\r\nException : " + ex.Message, EventLogEntryType.Error, moduleName, 0, true);
                }
            } finally {
                if ((w != null))
                    w.Close();
            }
        }
Пример #21
0
        private void yesButton_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog save = new SaveFileDialog())
              {
            save.DefaultExt = "sql";
            save.OverwritePrompt = true;
            save.Filter = "SQL Script Files (*.sql)|*.sql|All Files (*.*)|*.*";
            save.FileName = String.Format("{0}.sql", _tableName);
            save.Title = "Save SQLite Change Script";

            DialogResult = save.ShowDialog(this);

            if (DialogResult == DialogResult.OK)
            {
              _defaultSave = _saveOrig.Checked;

              using (System.IO.StreamWriter writer = new System.IO.StreamWriter(save.FileName, false, Encoding.UTF8))
              {
            if ((_show.Visible == true && _saveOrig.Checked == true) || (_show.Visible == false && _splitter.Panel2Collapsed == true))
            {
              if (_show.Visible == true) writer.WriteLine("/*");
              writer.WriteLine(_original.Text.Replace("\r", "").TrimEnd('\n').Replace("\n", "\r\n"));
              if (_show.Visible == true) writer.WriteLine("*/");
            }
            if (_show.Visible == true || _splitter.Panel2Collapsed == false)
              writer.WriteLine(_script.Text.Replace("\r", "").TrimEnd('\n').Replace("\n", "\r\n"));
              }
            }
              }
              Close();
        }
Пример #22
0
 public override void Execute(object parameter)
 {
     MainWindow.Instance.TextView.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => {
         AvalonEditTextOutput output = new AvalonEditTextOutput();
         Parallel.ForEach(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct }, delegate(LoadedAssembly asm) {
             if (!asm.HasLoadError) {
                 Stopwatch w = Stopwatch.StartNew();
                 Exception exception = null;
                 using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) {
                     try {
                         new CSharpLanguage().DecompileAssembly(asm, new Decompiler.PlainTextOutput(writer), new DecompilationOptions { FullDecompilation = true, CancellationToken = ct });
                     }
                     catch (Exception ex) {
                         writer.WriteLine(ex.ToString());
                         exception = ex;
                     }
                 }
                 lock (output) {
                     output.Write(asm.ShortName + " - " + w.Elapsed);
                     if (exception != null) {
                         output.Write(" - ");
                         output.Write(exception.GetType().Name);
                     }
                     output.WriteLine();
                 }
             }
         });
         return output;
     }, ct), task => MainWindow.Instance.TextView.ShowText(task.Result));
 }
Пример #23
0
 public static void ExportFilteredDataTableToCsv(DataTable targetDataTable, string targetFilePath, string filterString)
 {
     using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(targetFilePath, false, Encoding.UTF8))
     {
         for (int i = 0; i < targetDataTable.Columns.Count; i++)
         {
             outFile.Write("\"");
             outFile.Write(targetDataTable.Columns[i].ColumnName.Replace("\"", "\"\""));
             outFile.Write("\"");
             outFile.Write(i == targetDataTable.Columns.Count - 1 ? Environment.NewLine : ",");
         }
         foreach (DataRow row in targetDataTable.Select(filterString))
         {
             for (int i = 0; i < targetDataTable.Columns.Count; i++)
             {
                 outFile.Write("\"");
                 if (targetDataTable.Columns[i].DataType.Equals(typeof(DateTime)))
                     outFile.Write(FormatDateFullTimeStamp((DateTime)row[i]));
                 else
                     outFile.Write(row[i].ToString().Replace("\"", "\"\""));
                 outFile.Write("\"");
                 outFile.Write(i == targetDataTable.Columns.Count - 1 ? Environment.NewLine : ",");
             }
         }
     }
 }
        public void Send(object sender, EventArgs args)
        {
            try
            {
                var publishArgs = args as Sitecore.Events.SitecoreEventArgs;

                var publisher = publishArgs.Parameters[0] as Sitecore.Publishing.Publisher;

                var publisherOptions = publisher.Options;

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("localhost");

                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add("*****@*****.**");
                mail.Subject = "Someone published the item " + publisherOptions.RootItem.Paths.FullPath;
                mail.Body = publisherOptions.RootItem.Fields["body"].Value;
                SmtpServer.Send(mail);

                string lines = publisherOptions.RootItem.Fields["body"].Value;

                // Write the string to a file.
                System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\Git\\Eduserv-Github-Example\\Source\\Website\\BritishLibrary.Website\\test.xml");
                file.WriteLine(lines);

                file.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine("Seems some problem!");
            }
        }
		private void  InitBlock()
		{
			System.IO.StreamWriter temp_writer;
			temp_writer = new System.IO.StreamWriter(System.Console.OpenStandardOutput(), System.Console.Out.Encoding);
			temp_writer.AutoFlush = true;
			debugStream = temp_writer;
		}
Пример #26
0
        private void LoadTestCredential()
        {
            string path = @"C:\Temp\AmazonAwsS3Test.xml";
            Models.AwsCredential credential;
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Models.AwsCredential));

            if (!System.IO.File.Exists(path))
            {
                //Cria um arquivo xml novo, se já não existir um
                credential = new Models.AwsCredential();
                credential.User = string.Empty;
                credential.AccessKeyId = string.Empty;
                credential.SecretAccessKey = string.Empty;
                credential.Region = string.Empty;

                using (var streamWriter = new System.IO.StreamWriter(path))
                {
                    xmlSerializer.Serialize(streamWriter, credential);
                }
            }

            //Carrega o xml
            using (var streamReader = new System.IO.StreamReader(path))
            {
                credential = (Models.AwsCredential)xmlSerializer.Deserialize(streamReader);
            }

            txtAccessKeyId.Text = credential.AccessKeyId;
            txtSecretAccessKey.Text = credential.SecretAccessKey;
            txtRegion.Text = credential.Region;
        }
Пример #27
0
 public static void WriteException(String pMethod, Exception pException)
 {
     String date = DateTime.Now.ToString("dd/MM/yyyy hh:MM:ss");
     String archieve = "C:\\TEMP\\MIToolDatabaseLog" + DateTime.Now.ToString("dd/MM/yyyy") + ".txt";            
     try
     {
         System.IO.StreamWriter file = new System.IO.StreamWriter(archieve, true);
         file.WriteLine("------------------------------------------");
         file.WriteLine("Method :" + pMethod);
         file.WriteLine("Date :" + date);
         file.WriteLine("Detail");
         file.WriteLine("\n");
         file.WriteLine("Message " + pException.Message);
         file.WriteLine("\n");
         file.WriteLine("StackTrace " + pException.StackTrace);
         file.WriteLine("\n");
         file.WriteLine("Source " + pException.Source);
         file.WriteLine("\n");
         file.WriteLine("ToString() " + pException.ToString());
         file.WriteLine("------------------------------------------");
         file.WriteLine("\n");
         file.Close();
     }
     catch { }
 }
Пример #28
0
        public static string DumpGossipMenu()
        {
            var file = "GossipMenuLog_" + DateTime.Now.ToString("MM-dd-yyyy-hh-mm-ss") + ".sql";
            var gossip_menus = GossipMenuList.OrderByDescending(t => t.Key);
            using (var sw = new System.IO.StreamWriter(file))
            {
                foreach (var gossip_menu in gossip_menus)
                {
                    sw.WriteLine(gossip_menu.Value.GetDeleteCommand());
                    sw.WriteLine(gossip_menu.Value.GetInsertCommand());
                    if (gossip_menu.Value.creature_template != null)
                    {
                        sw.WriteLine();
                        sw.WriteLine(gossip_menu.Value.creature_template.GetUpdateCommand());
                    }
                    
                    if (gossip_menu.Value.gossip_menu_options != null && gossip_menu.Value.gossip_menu_options.Any())
                    {
                        sw.WriteLine();

                        sw.WriteLine(gossip_menu.Value.gossip_menu_options.First().Value.GetDeleteCommand());

                        foreach (var gossip_menu_option in gossip_menu.Value.gossip_menu_options)
                        {
                            sw.WriteLine(gossip_menu_option.Value.GetInsertCommand());
                        }
                    }
                    sw.WriteLine();
                }
            }

            return file;
        }
Пример #29
0
        static void Main()
        {
            Process self = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(self.ProcessName);
            int selfid = self.Id;
            foreach (Process proc in processes) {
                if (proc.Id != selfid) {
                    NativeMethods.ShowWindow(proc.MainWindowHandle, NativeMethods.SW_NORMAL);
                    NativeMethods.SetForegroundWindow(proc.MainWindowHandle);
                    return;
                }
            }

            Process[] scueduler = Process.GetProcessesByName("cubepower-scheduler");
            foreach (Process proc in scueduler) proc.Kill();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try {
                Application.Run(new MainForm());
            }
            catch (Exception err) {
                System.Reflection.Assembly exec = System.Reflection.Assembly.GetEntryAssembly();
                string dir = System.IO.Path.GetDirectoryName(exec.Location);
                string path = dir + @"\cubepower.log";
                using (System.IO.StreamWriter output = new System.IO.StreamWriter(path)) {
                    output.WriteLine(err.Message);

                    IPowerScheme scheme;
                    if (Environment.OSVersion.Version.Major > 5) scheme = new PowerSchemeVista();
                    else scheme = new PowerSchemeXP();
                    scheme.Dump(output);
                }
            }
        }
Пример #30
0
 public void save()
 {
     System.IO.StreamWriter m_stwSave = new System.IO.StreamWriter(".\\CCDate.dat", false);
     m_stwSave.WriteLine(strCCKey);
     m_stwSave.WriteLine(strSaveKey);
     m_stwSave.Close();
 }
Пример #31
0
        private void CreateGameResultsTable()
        {
            string outputDir = System.IO.Path.Combine(mUniverseData.ExportDirectory, mLeagueID);
            string filename  = System.IO.Path.Combine(outputDir, "game_information_extra.csv");

            AddStatusString("Writing game results and drives");
            System.IO.StreamWriter resultsFile = new System.IO.StreamWriter(filename, false);

            resultsFile.Write("Year,");
            resultsFile.Write("Week,");
            resultsFile.Write("GameID,");
            resultsFile.Write("HomeLeftRushAttempts,");
            resultsFile.Write("HomeLeftRushYards,");
            resultsFile.Write("HomeLongAttempts,");
            resultsFile.Write("HomeLongCompletions,");
            resultsFile.Write("HomeLongYards,");
            resultsFile.Write("HomeMediumAttempts,");
            resultsFile.Write("HomeMediumCompletions,");
            resultsFile.Write("HomeMediumYards,");
            resultsFile.Write("HomeMiddleRushAttempts,");
            resultsFile.Write("HomeMiddleRushYards,");
            resultsFile.Write("HomeOtherAttempts,");
            resultsFile.Write("HomeOtherCompletions,");
            resultsFile.Write("HomeOtherYards,");
            resultsFile.Write("HomeOtherRushAttempts,");
            resultsFile.Write("HomeOtherRushYards,");
            resultsFile.Write("HomeRedZoneAttempts,");
            resultsFile.Write("HomeRedZoneFGs,");
            resultsFile.Write("HomeRedZoneTDs,");
            resultsFile.Write("HomeRightRushAttempts,");
            resultsFile.Write("HomeRightRushYards,");
            resultsFile.Write("HomeScreenAttempts,");
            resultsFile.Write("HomeScreenCompletions,");
            resultsFile.Write("HomeScreenYards,");
            resultsFile.Write("HomeShortAttempts,");
            resultsFile.Write("HomeShortCompletions,");
            resultsFile.Write("HomeShortYards,");
            resultsFile.Write("HomeTimeOfPossession,");
            resultsFile.Write("AwayLeftRushAttempts,");
            resultsFile.Write("AwayLeftRushYards,");
            resultsFile.Write("AwayLongAttempts,");
            resultsFile.Write("AwayLongCompletions,");
            resultsFile.Write("AwayLongYards,");
            resultsFile.Write("AwayMediumAttempts,");
            resultsFile.Write("AwayMediumCompletions,");
            resultsFile.Write("AwayMediumYards,");
            resultsFile.Write("AwayMiddleRushAttempts,");
            resultsFile.Write("AwayMiddleRushYards,");
            resultsFile.Write("AwayOtherAttempts,");
            resultsFile.Write("AwayOtherCompletions,");
            resultsFile.Write("AwayOtherYards,");
            resultsFile.Write("AwayOtherRushAttempts,");
            resultsFile.Write("AwayOtherRushYards,");
            resultsFile.Write("AwayRedZoneAttempts,");
            resultsFile.Write("AwayRedZonefGs,");
            resultsFile.Write("AwayRedZonetDs,");
            resultsFile.Write("AwayRightRushAttempts,");
            resultsFile.Write("AwayRightRushYards,");
            resultsFile.Write("AwayScreenAttempts,");
            resultsFile.Write("AwayScreenCompletions,");
            resultsFile.Write("AwayScreenYards,");
            resultsFile.Write("AwayShortAttempts,");
            resultsFile.Write("AwayShortCompletions,");
            resultsFile.Write("AwayShortYards,");
            resultsFile.Write("AwayTimeOfPossession,");
            resultsFile.Write("TotalCapacity,");
            resultsFile.Write("UpperDeckAttendance,");
            resultsFile.Write("UpperDeckCapacity,");
            resultsFile.Write("EndZoneAttendance,");
            resultsFile.Write("EndZoneCapacity,");
            resultsFile.Write("MezzanineAttendance,");
            resultsFile.Write("MezzanineCapacity,");
            resultsFile.Write("SidelineAttendance,");
            resultsFile.Write("SidelineCapacity,");
            resultsFile.Write("ClubAttendance,");
            resultsFile.Write("ClubCapacity,");
            resultsFile.Write("BoxAttendance,");
            resultsFile.Write("BoxCapacity,");
            resultsFile.WriteLine("PoGID");

            filename = System.IO.Path.Combine(outputDir, "drive_results.csv");
            System.IO.StreamWriter drivesFile = new System.IO.StreamWriter(filename, false);

            drivesFile.Write("Year,");
            drivesFile.Write("GameID,");
            drivesFile.Write("DriveID,");
            drivesFile.Write("EndMinutes,");
            drivesFile.Write("EndQuarter,");
            drivesFile.Write("EndSeconds,");
            drivesFile.Write("PlayCount,");
            drivesFile.Write("StartMinutes,");
            drivesFile.Write("StartQuarter,");
            drivesFile.Write("StartSeconds,");
            drivesFile.Write("StartYardsFromGoal,");
            drivesFile.Write("Team,");
            drivesFile.Write("YardsGained,");
            drivesFile.WriteLine("Result");

            System.IO.StreamWriter statsFile = null;

            int oldYear = 0;

            int gameID = 0;

            foreach (LeagueData.GameWeekRecord gameWeekRec in mLeagueData.AvailableGameWeeks)
            {
                if (gameWeekRec.Year != oldYear)
                {
                    if (statsFile != null)
                    {
                        statsFile.Close();
                    }

                    filename  = System.IO.Path.Combine(outputDir, "player_season_extra_" + gameWeekRec.Year + ".csv");
                    statsFile = new System.IO.StreamWriter(filename, false);

                    statsFile.Write("PlayerID,");
                    statsFile.Write("Week,");
                    statsFile.Write("Team,");
                    statsFile.Write("DoubleCoveragesThrownInto,");
                    statsFile.Write("DoubleCoveragesAvoided,");
                    statsFile.Write("BadPasses,");
                    statsFile.Write("RunsForLoss,");
                    statsFile.Write("RunsOf20YardsPlus,");
                    statsFile.Write("FumblesLost,");
                    statsFile.Write("HasKeyCoverage,");
                    statsFile.Write("ThrownAt,");
                    statsFile.Write("TacklesForLoss,");
                    statsFile.Write("AssistedTacklesForLoss,");
                    statsFile.Write("ReceptionsOf20YardsPlusGivenUp,");
                    statsFile.Write("Kickoffs,");
                    statsFile.Write("KickoffYards,");
                    statsFile.Write("KickoffTouchbacks,");
                    statsFile.Write("TotalFieldPositionAfterKickoff,");
                    statsFile.Write("OffensivePassPlays,");
                    statsFile.Write("OffensiveRunPlays,");
                    statsFile.Write("DefensivePassPlays,");
                    statsFile.Write("DefensiveRunPlays,");
                    statsFile.Write("SuccessfulPasses,");
                    statsFile.Write("SuccessfulCatches,");
                    statsFile.Write("SuccessfulRuns,");
                    statsFile.Write("BadPassesCaught,");
                    statsFile.Write("PlusPlays,");
                    statsFile.Write("MinusPlays,");
                    statsFile.Write("PenaltiesCommitted,");
                    statsFile.WriteLine("PenaltiesAccepted");

                    oldYear = gameWeekRec.Year;
                    gameID  = 0;
                }
                foreach (LeagueData.GameLog curLog in gameWeekRec.GameLogs)
                {
                    resultsFile.Write(gameWeekRec.Year + ",");
                    resultsFile.Write(gameWeekRec.Week + ",");
                    resultsFile.Write(gameID + ",");
                    resultsFile.Write(curLog.HomeRushing.LeftAttempts + ",");
                    resultsFile.Write(curLog.HomeRushing.LeftYards + ",");
                    resultsFile.Write(curLog.HomePassing.LongAttempts + ",");
                    resultsFile.Write(curLog.HomePassing.LongCompletions + ",");
                    resultsFile.Write(curLog.HomePassing.LongYards + ",");
                    resultsFile.Write(curLog.HomePassing.MediumAttempts + ",");
                    resultsFile.Write(curLog.HomePassing.MediumCompletions + ",");
                    resultsFile.Write(curLog.HomePassing.MediumYards + ",");
                    resultsFile.Write(curLog.HomeRushing.MiddleAttempts + ",");
                    resultsFile.Write(curLog.HomeRushing.MiddleYards + ",");
                    resultsFile.Write(curLog.HomePassing.OtherAttempts + ",");
                    resultsFile.Write(curLog.HomePassing.OtherCompletions + ",");
                    resultsFile.Write(curLog.HomePassing.OtherYards + ",");
                    resultsFile.Write(curLog.HomeRushing.OtherAttempts + ",");
                    resultsFile.Write(curLog.HomeRushing.OtherYards + ",");
                    resultsFile.Write(curLog.HomePossessions.RedZoneAttempts + ",");
                    resultsFile.Write(curLog.HomePossessions.RedZoneFieldGoals + ",");
                    resultsFile.Write(curLog.HomePossessions.RedZoneTouchdowns + ",");
                    resultsFile.Write(curLog.HomeRushing.RightAttempts + ",");
                    resultsFile.Write(curLog.HomeRushing.RightYards + ",");
                    resultsFile.Write(curLog.HomePassing.ScreenAttempts + ",");
                    resultsFile.Write(curLog.HomePassing.ScreenCompletions + ",");
                    resultsFile.Write(curLog.HomePassing.ScreenYards + ",");
                    resultsFile.Write(curLog.HomePassing.ShortAttempts + ",");
                    resultsFile.Write(curLog.HomePassing.ShortCompletions + ",");
                    resultsFile.Write(curLog.HomePassing.ShortYards + ",");
                    resultsFile.Write(curLog.HomePossessions.TimeOfPossession + ",");
                    resultsFile.Write(curLog.AwayRushing.LeftAttempts + ",");
                    resultsFile.Write(curLog.AwayRushing.LeftYards + ",");
                    resultsFile.Write(curLog.AwayPassing.LongAttempts + ",");
                    resultsFile.Write(curLog.AwayPassing.LongCompletions + ",");
                    resultsFile.Write(curLog.AwayPassing.LongYards + ",");
                    resultsFile.Write(curLog.AwayPassing.MediumAttempts + ",");
                    resultsFile.Write(curLog.AwayPassing.MediumCompletions + ",");
                    resultsFile.Write(curLog.AwayPassing.MediumYards + ",");
                    resultsFile.Write(curLog.AwayRushing.MiddleAttempts + ",");
                    resultsFile.Write(curLog.AwayRushing.MiddleYards + ",");
                    resultsFile.Write(curLog.AwayPassing.OtherAttempts + ",");
                    resultsFile.Write(curLog.AwayPassing.OtherCompletions + ",");
                    resultsFile.Write(curLog.AwayPassing.OtherYards + ",");
                    resultsFile.Write(curLog.AwayRushing.OtherAttempts + ",");
                    resultsFile.Write(curLog.AwayRushing.OtherYards + ",");
                    resultsFile.Write(curLog.AwayPossessions.RedZoneAttempts + ",");
                    resultsFile.Write(curLog.AwayPossessions.RedZoneFieldGoals + ",");
                    resultsFile.Write(curLog.AwayPossessions.RedZoneTouchdowns + ",");
                    resultsFile.Write(curLog.AwayRushing.RightAttempts + ",");
                    resultsFile.Write(curLog.AwayRushing.RightYards + ",");
                    resultsFile.Write(curLog.AwayPassing.ScreenAttempts + ",");
                    resultsFile.Write(curLog.AwayPassing.ScreenCompletions + ",");
                    resultsFile.Write(curLog.AwayPassing.ScreenYards + ",");
                    resultsFile.Write(curLog.AwayPassing.ShortAttempts + ",");
                    resultsFile.Write(curLog.AwayPassing.ShortCompletions + ",");
                    resultsFile.Write(curLog.AwayPassing.ShortYards + ",");
                    resultsFile.Write(curLog.AwayPossessions.TimeOfPossession + ",");
                    resultsFile.Write(curLog.TotalCapacity + ",");
                    resultsFile.Write(curLog.UpperDeckAttendance + ",");
                    resultsFile.Write(curLog.UpperDeckCapacity + ",");
                    resultsFile.Write(curLog.EndZoneCapacity + ",");
                    resultsFile.Write(curLog.EndZoneAttendance + ",");
                    resultsFile.Write(curLog.MezzanineAttendance + ",");
                    resultsFile.Write(curLog.MezzanineCapacity + ",");
                    resultsFile.Write(curLog.SidelineAttendance + ",");
                    resultsFile.Write(curLog.SidelineCapacity + ",");
                    resultsFile.Write(curLog.ClubAttendance + ",");
                    resultsFile.Write(curLog.ClubCapacity + ",");
                    resultsFile.Write(curLog.BoxAttendance + ",");
                    resultsFile.Write(curLog.BoxCapacity + ",");
                    resultsFile.WriteLine(curLog.PlayerOfTheGamePlayerID);

                    int driveID = 0;
                    foreach (LeagueData.GameDriveInfo homeDriveInfo in curLog.HomeDrives)
                    {
                        drivesFile.Write(gameWeekRec.Year + ",");
                        drivesFile.Write(gameID + ",");
                        drivesFile.Write(driveID + ",");
                        drivesFile.Write(homeDriveInfo.DriveEndMinutes + ",");
                        drivesFile.Write(homeDriveInfo.DriveEndQuarter + ",");
                        drivesFile.Write(homeDriveInfo.DriveEndSeconds + ",");
                        drivesFile.Write(homeDriveInfo.Plays + ",");
                        drivesFile.Write(homeDriveInfo.DriveStartMinutes + ",");
                        drivesFile.Write(homeDriveInfo.DriveStartQuarter + ",");
                        drivesFile.Write(homeDriveInfo.DriveStartSeconds + ",");
                        drivesFile.Write(homeDriveInfo.YardsFromGoalStart + ",");
                        drivesFile.Write(curLog.HomeTeam.TeamIndex + ",");
                        drivesFile.Write(homeDriveInfo.YardsGained + ",");
                        drivesFile.WriteLine(homeDriveInfo.Result);

                        driveID += 1;
                    }
                    foreach (LeagueData.GameDriveInfo awayDriveInfo in curLog.AwayDrives)
                    {
                        drivesFile.Write(gameWeekRec.Year + ",");
                        drivesFile.Write(gameID + ",");
                        drivesFile.Write(driveID + ",");
                        drivesFile.Write(awayDriveInfo.DriveEndMinutes + ",");
                        drivesFile.Write(awayDriveInfo.DriveEndQuarter + ",");
                        drivesFile.Write(awayDriveInfo.DriveEndSeconds + ",");
                        drivesFile.Write(awayDriveInfo.Plays + ",");
                        drivesFile.Write(awayDriveInfo.DriveStartMinutes + ",");
                        drivesFile.Write(awayDriveInfo.DriveStartQuarter + ",");
                        drivesFile.Write(awayDriveInfo.DriveStartSeconds + ",");
                        drivesFile.Write(awayDriveInfo.YardsFromGoalStart + ",");
                        drivesFile.Write(curLog.AwayTeam.TeamIndex + ",");
                        drivesFile.Write(awayDriveInfo.YardsGained + ",");
                        drivesFile.WriteLine(awayDriveInfo.Result);

                        driveID += 1;
                    }

                    foreach (LeagueData.PlayerGameStatsRecord rec in curLog.HomeTeam.PlayerStats)
                    {
                        if (rec.PlayerID < 0)
                        {
                            continue;
                        }
                        statsFile.Write(rec.PlayerID + ",");
                        statsFile.Write((rec.Week - 5) + ",");
                        statsFile.Write(rec.Team + ",");
                        statsFile.Write(rec.DoubleCoveragesThrownInto + ",");
                        statsFile.Write(rec.DoubleCoveragesAvoided + ",");
                        statsFile.Write(rec.BadPasses + ",");
                        statsFile.Write(rec.RunsForLoss + ",");
                        statsFile.Write(rec.RunsOf20YardsPlus + ",");
                        statsFile.Write(rec.FumblesLost + ",");
                        statsFile.Write(rec.HasKeyCoverage + ",");
                        statsFile.Write(rec.ThrownAt + ",");
                        statsFile.Write(rec.TacklesForLoss + ",");
                        statsFile.Write(rec.AssistedTacklesForLoss + ",");
                        statsFile.Write(rec.ReceptionsOf20YardsPlusGivenUp + ",");
                        statsFile.Write(rec.Kickoffs + ",");
                        statsFile.Write(rec.KickoffYards + ",");
                        statsFile.Write(rec.KickoffTouchbacks + ",");
                        statsFile.Write(rec.TotalFieldPositionAfterKickoff + ",");
                        statsFile.Write(rec.OffensivePassPlays + ",");
                        statsFile.Write(rec.OffensiveRunPlays + ",");
                        statsFile.Write(rec.DefensivePassPlays + ",");
                        statsFile.Write(rec.DefensiveRunPlays + ",");
                        statsFile.Write(rec.SuccessfulPasses + ",");
                        statsFile.Write(rec.SuccessfulCatches + ",");
                        statsFile.Write(rec.SuccessfulRuns + ",");
                        statsFile.Write(rec.BadPassesCaught + ",");
                        statsFile.Write(rec.PlusPlays + ",");
                        statsFile.Write(rec.MinusPlays + ",");
                        statsFile.Write(rec.PenaltiesCommitted + ",");
                        statsFile.WriteLine(rec.PenaltiesAccepted);
                    }

                    foreach (LeagueData.PlayerGameStatsRecord rec in curLog.AwayTeam.PlayerStats)
                    {
                        if (rec.PlayerID < 0)
                        {
                            continue;
                        }
                        statsFile.Write(rec.PlayerID + ",");
                        statsFile.Write((rec.Week - 5) + ",");
                        statsFile.Write(rec.Team + ",");
                        statsFile.Write(rec.DoubleCoveragesThrownInto + ",");
                        statsFile.Write(rec.DoubleCoveragesAvoided + ",");
                        statsFile.Write(rec.BadPasses + ",");
                        statsFile.Write(rec.RunsForLoss + ",");
                        statsFile.Write(rec.RunsOf20YardsPlus + ",");
                        statsFile.Write(rec.FumblesLost + ",");
                        statsFile.Write(rec.HasKeyCoverage + ",");
                        statsFile.Write(rec.ThrownAt + ",");
                        statsFile.Write(rec.TacklesForLoss + ",");
                        statsFile.Write(rec.AssistedTacklesForLoss + ",");
                        statsFile.Write(rec.ReceptionsOf20YardsPlusGivenUp + ",");
                        statsFile.Write(rec.Kickoffs + ",");
                        statsFile.Write(rec.KickoffYards + ",");
                        statsFile.Write(rec.KickoffTouchbacks + ",");
                        statsFile.Write(rec.TotalFieldPositionAfterKickoff + ",");
                        statsFile.Write(rec.OffensivePassPlays + ",");
                        statsFile.Write(rec.OffensiveRunPlays + ",");
                        statsFile.Write(rec.DefensivePassPlays + ",");
                        statsFile.Write(rec.DefensiveRunPlays + ",");
                        statsFile.Write(rec.SuccessfulPasses + ",");
                        statsFile.Write(rec.SuccessfulCatches + ",");
                        statsFile.Write(rec.SuccessfulRuns + ",");
                        statsFile.Write(rec.BadPassesCaught + ",");
                        statsFile.Write(rec.PlusPlays + ",");
                        statsFile.Write(rec.MinusPlays + ",");
                        statsFile.Write(rec.PenaltiesCommitted + ",");
                        statsFile.WriteLine(rec.PenaltiesAccepted);
                    }

                    gameID += 1;
                }
            }

            if (statsFile != null)
            {
                statsFile.Close();
            }
            if (drivesFile != null)
            {
                drivesFile.Close();
            }
            if (resultsFile != null)
            {
                resultsFile.Close();
            }
        }
Пример #32
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("No arguments were passed.");
                Console.ReadLine();  // Keep the console open.
                return;
            }

            var filePath = args[0];

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

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

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

                package.Dispose();
            }

            string line;

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

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

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

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

            file.Close();
            bool has = columns.Any(col => col.ColumnName == "Type");

            var datatable = @"let data = datatable (" + appendColumns(columns) + ") [";

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

            logWriter.WriteLine(datatable);
            logWriter.Dispose();
            TextCopy.Clipboard.SetText(datatable);
        }
Пример #33
0
        public virtual void  TestPayloadsPos0()
        {
            for (int x = 0; x < 2; x++)
            {
                Directory   dir    = new MockRAMDirectory();
                IndexWriter writer = new IndexWriter(dir, new TestPayloadAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
                if (x == 1)
                {
                    writer.SetAllowMinus1Position();
                }
                Document doc = new Document();
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.IO.StreamWriter sw = new System.IO.StreamWriter(ms);
                sw.Write("a a b c d e a f g h i j a b k k");
                // flush to stream & reset it's position so it can be read
                sw.Flush();
                ms.Position = 0;
                doc.Add(new Field("content", new System.IO.StreamReader(ms)));
                writer.AddDocument(doc);

                IndexReader r = writer.GetReader();

                TermPositions tp    = r.TermPositions(new Term("content", "a"));
                int           count = 0;
                Assert.IsTrue(tp.Next());
                // "a" occurs 4 times
                Assert.AreEqual(4, tp.Freq());
                int expected;
                if (x == 1)
                {
                    expected = System.Int32.MaxValue;
                }
                else
                {
                    expected = 0;
                }
                Assert.AreEqual(expected, tp.NextPosition());
                if (x == 1)
                {
                    continue;
                }
                Assert.AreEqual(1, tp.NextPosition());
                Assert.AreEqual(3, tp.NextPosition());
                Assert.AreEqual(6, tp.NextPosition());

                // only one doc has "a"
                Assert.IsFalse(tp.Next());

                IndexSearcher is_Renamed = new IndexSearcher(r);

                SpanTermQuery stq1 = new SpanTermQuery(new Term("content", "a"));
                SpanTermQuery stq2 = new SpanTermQuery(new Term("content", "k"));
                SpanQuery[]   sqs  = new SpanQuery[] { stq1, stq2 };
                SpanNearQuery snq  = new SpanNearQuery(sqs, 30, false);

                count = 0;
                bool sawZero = false;
                //System.out.println("\ngetPayloadSpans test");
                Lucene.Net.Search.Spans.Spans pspans = snq.GetSpans(is_Renamed.GetIndexReader());
                while (pspans.Next())
                {
                    //System.out.println(pspans.doc() + " - " + pspans.start() + " - "+ pspans.end());
                    System.Collections.Generic.ICollection <byte[]> payloads = pspans.GetPayload();
                    sawZero |= pspans.Start() == 0;
                    for (System.Collections.IEnumerator it = payloads.GetEnumerator(); it.MoveNext();)
                    {
                        count++;
                        System.Object generatedAux2 = it.Current;
                        //System.out.println(new String((byte[]) it.next()));
                    }
                }
                Assert.AreEqual(5, count);
                Assert.IsTrue(sawZero);

                //System.out.println("\ngetSpans test");
                Lucene.Net.Search.Spans.Spans spans = snq.GetSpans(is_Renamed.GetIndexReader());
                count   = 0;
                sawZero = false;
                while (spans.Next())
                {
                    count++;
                    sawZero |= spans.Start() == 0;
                    //System.out.println(spans.doc() + " - " + spans.start() + " - " + spans.end());
                }
                Assert.AreEqual(4, count);
                Assert.IsTrue(sawZero);

                //System.out.println("\nPayloadSpanUtil test");

                sawZero = false;
                PayloadSpanUtil psu = new PayloadSpanUtil(is_Renamed.GetIndexReader());
                System.Collections.Generic.ICollection <byte[]> pls = psu.GetPayloadsForQuery(snq);
                count = pls.Count;
                for (System.Collections.IEnumerator it = pls.GetEnumerator(); it.MoveNext();)
                {
                    System.String s = new System.String(System.Text.UTF8Encoding.UTF8.GetChars((byte[])it.Current));
                    //System.out.println(s);
                    sawZero |= s.Equals("pos: 0");
                }
                Assert.AreEqual(5, count);
                Assert.IsTrue(sawZero);
                writer.Close();
                is_Renamed.GetIndexReader().Close();
                dir.Close();
            }
        }
Пример #34
0
 public static void writeFile(string PATH, string saida)
 {
     using (System.IO.StreamWriter file = new System.IO.StreamWriter(@PATH, true)){
         file.WriteLine(saida);
     }
 }
Пример #35
0
        public static Duplicati.Library.Interface.IBasicResults Run(IRunnerData data, bool fromQueue)
        {
            var backup = data.Backup;

            Duplicati.Library.Utility.TempFolder tempfolder = null;

            if (backup.Metadata == null)
            {
                backup.Metadata = new Dictionary <string, string>();
            }

            try
            {
                var options = ApplyOptions(backup, data.Operation, GetCommonOptions(backup, data.Operation));
                var sink    = new MessageSink(data.TaskID, backup.ID);
                if (fromQueue)
                {
                    Program.GenerateProgressState = () => sink.Copy();
                    Program.StatusEventNotifyer.SignalNewEvent();
                }

                if (data.ExtraOptions != null)
                {
                    foreach (var k in data.ExtraOptions)
                    {
                        options[k.Key] = k.Value;
                    }
                }

                // Log file is using the internal log-handler
                // so we can display output in the GUI as well as log
                // into the given file
                if (options.ContainsKey("log-file"))
                {
                    var file = options["log-file"];

                    string o;
                    Library.Logging.LogMessageType level;
                    options.TryGetValue("log-level", out o);
                    Enum.TryParse <Library.Logging.LogMessageType>(o, true, out level);

                    options.Remove("log-file");
                    options.Remove("log-level");

                    Program.LogHandler.SetOperationFile(file, level);
                }

                // Pack in the system or task config for easy restore
                if (data.Operation == DuplicatiOperation.Backup && options.ContainsKey("store-task-config"))
                {
                    var all_tasks = string.Equals(options["store-task-config"], "all", StringComparison.InvariantCultureIgnoreCase) || string.Equals(options["store-task-config"], "*", StringComparison.InvariantCultureIgnoreCase);
                    var this_task = Duplicati.Library.Utility.Utility.ParseBool(options["store-task-config"], false);

                    options.Remove("store-task-config");

                    if (all_tasks || this_task)
                    {
                        if (tempfolder == null)
                        {
                            tempfolder = new Duplicati.Library.Utility.TempFolder();
                        }

                        var temppath = System.IO.Path.Combine(tempfolder, "task-setup.json");
                        using (var tempfile = Duplicati.Library.Utility.TempFile.WrapExistingFile(temppath))
                        {
                            object taskdata = null;
                            if (all_tasks)
                            {
                                taskdata = Program.DataConnection.Backups.Where(x => !x.IsTemporary).Select(x => Program.DataConnection.PrepareBackupForExport(Program.DataConnection.GetBackup(x.ID)));
                            }
                            else
                            {
                                taskdata = new [] { Program.DataConnection.PrepareBackupForExport(data.Backup) }
                            };

                            using (var fs = System.IO.File.OpenWrite(tempfile))
                                using (var sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8))
                                    Serializer.SerializeJson(sw, taskdata, true);

                            tempfile.Protected = true;

                            string controlfiles = null;
                            options.TryGetValue("control-files", out controlfiles);

                            if (string.IsNullOrWhiteSpace(controlfiles))
                            {
                                controlfiles = tempfile;
                            }
                            else
                            {
                                controlfiles += System.IO.Path.PathSeparator + tempfile;
                            }

                            options["control-files"] = controlfiles;
                        }
                    }
                }

                using (tempfolder)
                    using (var controller = new Duplicati.Library.Main.Controller(backup.TargetURL, options, sink))
                    {
                        ((RunnerData)data).Controller = controller;

                        switch (data.Operation)
                        {
                        case DuplicatiOperation.Backup:
                        {
                            var filter  = ApplyFilter(backup, data.Operation, GetCommonFilter(backup, data.Operation));
                            var sources =
                                (from n in backup.Sources
                                 let p = SpecialFolders.ExpandEnvironmentVariables(n)
                                         where !string.IsNullOrWhiteSpace(p)
                                         select p).ToArray();

                            var r = controller.Backup(sources, filter);
                            UpdateMetadata(backup, r);
                            return(r);
                        }

                        case DuplicatiOperation.List:
                        {
                            var r = controller.List(data.FilterStrings);
                            UpdateMetadata(backup, r);
                            return(r);
                        }

                        case DuplicatiOperation.Repair:
                        {
                            var r = controller.Repair();
                            UpdateMetadata(backup, r);
                            return(r);
                        }

                        case DuplicatiOperation.Remove:
                        {
                            var r = controller.Delete();
                            UpdateMetadata(backup, r);
                            return(r);
                        }

                        case DuplicatiOperation.Restore:
                        {
                            var r = controller.Restore(data.FilterStrings);
                            UpdateMetadata(backup, r);
                            return(r);
                        }

                        case DuplicatiOperation.Verify:
                        {
                            var r = controller.Test();
                            UpdateMetadata(backup, r);
                            return(r);
                        }

                        case DuplicatiOperation.CreateReport:
                        {
                            using (var tf = new Duplicati.Library.Utility.TempFile())
                            {
                                var r      = controller.CreateLogDatabase(tf);
                                var tempid = Program.DataConnection.RegisterTempFile("create-bug-report", r.TargetPath, DateTime.Now.AddDays(3));

                                if (string.Equals(tf, r.TargetPath, Library.Utility.Utility.ClientFilenameStringComparision))
                                {
                                    tf.Protected = true;
                                }

                                Program.DataConnection.RegisterNotification(
                                    NotificationType.Information,
                                    "Bugreport ready",
                                    "Bugreport is ready for download",
                                    null,
                                    null,
                                    "bug-report:created:" + tempid,
                                    (n, a) => n
                                    );

                                return(r);
                            }
                        }

                        default:
                            //TODO: Log this
                            return(null);
                        }
                    }
            }
            catch (Exception ex)
            {
                Program.DataConnection.LogError(data.Backup.ID, string.Format("Failed while executing \"{0}\" with id: {1}", data.Operation, data.Backup.ID), ex);
                UpdateMetadataError(data.Backup, ex);

                if (!fromQueue)
                {
                    throw;
                }

                return(null);
            }
            finally
            {
                ((RunnerData)data).Controller = null;
                Program.LogHandler.RemoveOperationFile();
            }
        }
Пример #36
0
 /// <summary>
 /// Log the message to the log file, provided the logging was
 /// initialized.
 /// </summary>
 /// <param name="message">The message being logged.</param>
 /// <param name="noTimeStamp">Used to override the default inclusion
 /// of date/time stamp in each logged line.</param>
 /// <param name="staticOutputLocation">Used to set console output to a
 /// fixed location.  This is useful for output such as progress
 /// percentage etc.</param>
 /// <returns>true if logging was successful, false if not.</returns>
 public static bool Log(string message, bool noTimeStamp = false,
                        bool staticOutputLocation        = false, bool includeStackFrame = false,
                        bool overLoaded = false)
 {
     // No logging code should EVER terminate it's parent program
     // through exceptions.
     try
     {
         // Check if caller wants StackFrame info included.
         if (includeStackFrame)
         {
             int frameOffset = 1;
             // Check if an overloaded method is used to call Log().
             if (overLoaded)
             {
                 frameOffset++;
             }
             // Get the StackFrame including FileInfo.
             var stackFrame = new System.Diagnostics.StackTrace(true)
                              .GetFrame(frameOffset);
             // Append the StackFrame info to the message.
             message = string.Format(message +
                                     " --->>> Called from {0} in {1} line {2} column {3}.",
                                     stackFrame.GetMethod().ToString(),
                                     stackFrame.GetFileName(),
                                     stackFrame.GetFileLineNumber(),
                                     stackFrame.GetFileColumnNumber());
         }
         // We use a single & because if we're not logging to the
         // console, it does not matter to what value
         // staticOutputLocation is set.  The use of single & prevents
         // run time evaluation of the value of staticOutputLocation
         // if logToConsole is false thus improving runtime execution
         // performance.
         if (logToConsole & staticOutputLocation)
         {
             // We want static location output so we capture the current
             // cursor location.
             _cursorLeft = Console.CursorLeft;
             _cursorTop  = Console.CursorTop;
         }
         // Write to the log file.
         _writer.WriteLine(prependTimeStamp(message, noTimeStamp));
         // Flush the writer so no messages are stuck in the buffer.
         _writer.Flush();
         // Check if console output is required.
         if (logToConsole)
         {
             // Are we keeping output in a static location?
             if (staticOutputLocation)
             {
                 // Reset the cursor before output.
                 Console.CursorTop  = _cursorTop;
                 Console.CursorLeft = _cursorLeft;
                 // Output the message with a large trailing
                 // blank to clear previous output from the static
                 // console line.
                 Console.WriteLine(
                     prependTimeStamp(message, noTimeStamp) +
                     "                                               " +
                     "                                               " +
                     "                         ");
                 // Reset the cursor after output.
                 Console.CursorTop  = _cursorTop;
                 Console.CursorLeft = _cursorLeft;
             }
             // No static output location is required.
             else
             {
                 // Simply write the message to the console.
                 Console.WriteLine(prependTimeStamp(
                                       message, noTimeStamp));
             }
         }
         if (logToEventLog)
         {
             // Write to Event Log's Application log
             System.Diagnostics.EventLog.WriteEntry("Application",
                                                    prependTimeStamp(message, noTimeStamp),
                                                    logToEventLogEntryType);
         }
     }
     // Something went wrong.
     catch (Exception ex)
     {
         System.Diagnostics.EventLog.WriteEntry("Application",
                                                ex.ToString(), logToEventLogEntryType);
         _outputColor            = Console.ForegroundColor;
         Console.ForegroundColor = ConsoleColor.Red;
         // Check if output is going to the console.
         if (logToConsole)
         {
             // Write console output, stamped if needed.
             Console.WriteLine(
                 prependTimeStamp(ex.ToString(), noTimeStamp));
         }
         // No logging code should EVER terminate it's parent program
         // through exceptions.  Wrap this file output in a try/catch
         // in case file writing throws an exception.
         try
         {
             // Reset the writer to open log file in append mode.
             using (System.IO.StreamWriter writer =
                        new System.IO.StreamWriter(_logPath, true))
             {
                 // Write the exception to the log file, stamped if
                 // needed.
                 writer.WriteLine(
                     prependTimeStamp(ex.ToString(), noTimeStamp));
                 // Flush the file writer buffer.
                 writer.Flush();
             }
         }
         // Have to distinguish between inner and outer exceptions.
         catch (Exception ex2)
         {
             System.Diagnostics.EventLog.WriteEntry("Application",
                                                    ex2.ToString(), logToEventLogEntryType);
             // Write the inner exception error.
             Quix.Core.writeConsoleError(ex2.ToString());
         }
         // Reset the console foreground color.
         Console.ForegroundColor = _outputColor;
         // Return false since something went wrong during logging.
         return(false);
     }
     // Logging succeeded.
     return(true);
 }
Пример #37
0
        private void ProcessGXCommand(MaterialGroup matgroup, byte cmd, ref uint pos)
        {
            VertexList vtxlist = null;

            if (matgroup.m_Geometry.Count > 0)
            {
                vtxlist = matgroup.m_Geometry[matgroup.m_Geometry.Count - 1];
            }

            System.IO.StreamWriter sw = null;
            if (lolol)
            {
                sw = new System.IO.StreamWriter(System.IO.File.Open("hurrdurr.txt", System.IO.FileMode.Append));
            }

            // if (((cmd & 0xF0) == 0x10) && (cmd != 0x14))
            //    throw new Exception(String.Format("MATRIX COMMAND {0:X2}", cmd));

            switch (cmd)
            {
            // nop
            case 0x00: break;

            // matrix commands
            case 0x10: pos += 4; break;

            case 0x11: break;

            case 0x12: pos += 4; break;

            case 0x13: pos += 4; break;

            // matrix restore (used for animation)
            case 0x14:
            {
                uint param = m_File.Read32(pos); pos += 4;

                m_CurVertex.m_MatrixID = param & 0x1F;
            }
            break;

            // more matrix commands
            case 0x15: break;

            case 0x16: pos += 64; break;

            case 0x17: pos += 48; break;

            case 0x18: pos += 64; break;

            case 0x19: pos += 48; break;

            case 0x1A: pos += 36; break;

            case 0x1B: pos += 12; break;

            case 0x1C: pos += 12; break;

            // set color
            case 0x20:
            {
                uint raw = m_File.Read32(pos); pos += 4;

                byte red   = (byte)((raw << 3) & 0xF8);
                byte green = (byte)((raw >> 2) & 0xF8);
                byte blue  = (byte)((raw >> 7) & 0xF8);

                byte alpha = (byte)((matgroup.m_PolyAttribs >> 13) & 0xF8);
                alpha |= (byte)(alpha >> 5);

                m_CurVertex.m_Color = Color.FromArgb(alpha, red, green, blue);
                if (lolol)
                {
                    sw.Write(String.Format("COLOR {0}\n", m_CurVertex.m_Color));
                }
            }
            break;

            // normal
            case 0x21:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short x = (short)((param << 6) & 0xFFC0);
                short y = (short)((param >> 4) & 0xFFC0);
                short z = (short)((param >> 14) & 0xFFC0);
                m_CurVertex.m_Normal = new Vector3((float)x / 32768.0f, (float)y / 32768.0f, (float)z / 32768.0f);
            }
            break;

            // texcoord
            case 0x22:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short s = (short)(param & 0xFFFF);
                short t = (short)(param >> 16);
                m_CurVertex.m_TexCoord = new Vector2((float)s / 16.0f, (float)t / 16.0f);

                Vector2 texsize = new Vector2((float)matgroup.m_Texture.m_Width, (float)matgroup.m_Texture.m_Height);

                if (lolol)
                {
                    sw.Write(String.Format("TEXCOORD {0} (TEXSIZE {1} SCALE {2} TRANS {3})\n",
                                           m_CurVertex.m_TexCoord, texsize, matgroup.m_TexCoordScale, matgroup.m_TexCoordTrans));
                }

                m_CurVertex.m_TexCoord = Vector2.Add((Vector2)m_CurVertex.m_TexCoord, matgroup.m_TexCoordTrans);
                m_CurVertex.m_TexCoord = Vector2.Multiply((Vector2)m_CurVertex.m_TexCoord, matgroup.m_TexCoordScale);

                /* if ((matgroup.m_TexParams & 0xC0000000) != 0)
                 * {
                 *   m_CurVertex.m_TexCoord.Y += matgroup.m_Texture.m_Height;
                 * }*/

                //Vector2 texsize = new Vector2((float)matgroup.m_Texture.m_Width, (float)matgroup.m_Texture.m_Height);
                m_CurVertex.m_TexCoord = Vector2.Divide((Vector2)m_CurVertex.m_TexCoord, texsize);

                // s = s*matrix[0] + t*matrix[4] + matrix[8]/16 + matrix[12]/16
                // t = s*matrix[1] + t*matrix[5] + matrix[9]/16 + matrix[13]/16

                // s = s*sscale + 1/16*(strans*sscale)
                // t = t*tscale + 1/16*(ttrans*tscale)
            }
            break;

            // define vertex
            case 0x23:
            {
                uint param1 = m_File.Read32(pos); pos += 4;
                uint param2 = m_File.Read32(pos); pos += 4;

                short x = (short)(param1 & 0xFFFF);
                short y = (short)(param1 >> 16);
                short z = (short)(param2 & 0xFFFF);
                m_CurVertex.m_Position.X = ((float)x / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Y = ((float)y / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Z = ((float)z / 4096.0f) * m_ScaleFactor;

                vtxlist.m_VertexList.Add(m_CurVertex);
                if (lolol)
                {
                    sw.Write(String.Format("VERTEX {0}\n", m_CurVertex.m_Position));
                }
            }
            break;

            case 0x24:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short x = (short)((param << 6) & 0xFFC0);
                short y = (short)((param >> 4) & 0xFFC0);
                short z = (short)((param >> 14) & 0xFFC0);
                m_CurVertex.m_Position.X = ((float)x / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Y = ((float)y / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Z = ((float)z / 4096.0f) * m_ScaleFactor;

                vtxlist.m_VertexList.Add(m_CurVertex);
                if (lolol)
                {
                    sw.Write(String.Format("VERTEX {0}\n", m_CurVertex.m_Position));
                }
            }
            break;

            case 0x25:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short x = (short)(param & 0xFFFF);
                short y = (short)(param >> 16);
                m_CurVertex.m_Position.X = ((float)x / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Y = ((float)y / 4096.0f) * m_ScaleFactor;

                vtxlist.m_VertexList.Add(m_CurVertex);
                if (lolol)
                {
                    sw.Write(String.Format("VERTEX {0}\n", m_CurVertex.m_Position));
                }
            }
            break;

            case 0x26:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short x = (short)(param & 0xFFFF);
                short z = (short)(param >> 16);
                m_CurVertex.m_Position.X = ((float)x / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Z = ((float)z / 4096.0f) * m_ScaleFactor;

                vtxlist.m_VertexList.Add(m_CurVertex);
                if (lolol)
                {
                    sw.Write(String.Format("VERTEX {0}\n", m_CurVertex.m_Position));
                }
            }
            break;

            case 0x27:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short y = (short)(param & 0xFFFF);
                short z = (short)(param >> 16);
                m_CurVertex.m_Position.Y = ((float)y / 4096.0f) * m_ScaleFactor;
                m_CurVertex.m_Position.Z = ((float)z / 4096.0f) * m_ScaleFactor;

                vtxlist.m_VertexList.Add(m_CurVertex);
                if (lolol)
                {
                    sw.Write(String.Format("VERTEX {0}\n", m_CurVertex.m_Position));
                }
            }
            break;

            case 0x28:
            {
                uint param = m_File.Read32(pos); pos += 4;

                short x = (short)((param << 6) & 0xFFC0);
                short y = (short)((param >> 4) & 0xFFC0);
                short z = (short)((param >> 14) & 0xFFC0);
                m_CurVertex.m_Position.X += (((float)x / 262144.0f) * m_ScaleFactor);
                m_CurVertex.m_Position.Y += (((float)y / 262144.0f) * m_ScaleFactor);
                m_CurVertex.m_Position.Z += (((float)z / 262144.0f) * m_ScaleFactor);

                vtxlist.m_VertexList.Add(m_CurVertex);
                if (lolol)
                {
                    sw.Write(String.Format("VERTEX {0}\n", m_CurVertex.m_Position));
                }
            }
            break;

            case 0x29: pos += 4; break;

            case 0x2A: pos += 4; break;

            case 0x2B: pos += 4; break;

            // lighting commands
            case 0x30: pos += 4; break;

            case 0x31: pos += 4; break;

            case 0x32: pos += 4; break;

            case 0x33: pos += 4; break;

            case 0x34: pos += 128; break;

            // Begin vertex list
            case 0x40:
            {
                uint param = m_File.Read32(pos); pos += 4;

                vtxlist = new VertexList();
                matgroup.m_Geometry.Add(vtxlist);
                vtxlist.m_PolyType   = param & 0x3;
                vtxlist.m_VertexList = new List <Vertex>();
                if (lolol)
                {
                    sw.Write(String.Format("BEGIN {0}\n", param));
                }
            }
            break;

            // End vertex list (dummy)
            case 0x41: if (lolol)
                {
                    sw.Write("END\n");
                }
                break;

            // misc.
            case 0x50: pos += 4; break;

            case 0x60: pos += 4; break;

            case 0x70: pos += 12; break;

            case 0x71: pos += 8; break;

            case 0x72: pos += 4; break;

            default: throw new Exception(String.Format("Unknown GX command {0:X2} in BMD file", cmd));
            }

            if (lolol)
            {
                sw.Close();
            }
        }
Пример #38
0
        static int Main(string[] args)
        {
            if (args.Length > 1 && args.Length < 4)
            {
                int    numberOfSides          = 0;
                double sideLength             = 0;
                RegularPolygonFactory factory = new RegularPolygonFactory();
                RegularPolygon        a       = null;
                double  area        = 0;
                Point[] coordinates = null;

                List <string> tekst  = new List <string>();
                int           choice = 0;

                try
                {
                    numberOfSides = int.Parse(args[0]);

                    sideLength = double.Parse(args[1]);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.ReadKey();
                    return(1);
                }



                try
                {
                    a = factory.GetRegularPolygon(numberOfSides, sideLength);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine(e.Message);
                    Console.ReadKey();
                    return(1);
                }


                area        = a.GetArea();
                coordinates = a.GetCoordinates();


                foreach (Point point in coordinates)
                {
                    tekst.Add(point.ToString());
                }


                tekst.Add("area = " + area.ToString());


                if (args.Length == 3)
                {
                    try
                    {
                        choice = int.Parse(args[2]);
                        if (choice == 1)
                        {
                            using (System.IO.StreamWriter file =
                                       new System.IO.StreamWriter("test.txt"))
                            {
                                foreach (string line in tekst)
                                {
                                    file.WriteLine(line);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        Console.ReadKey();
                        return(1);
                    }
                }
                else
                {
                    foreach (string line in tekst)
                    {
                        Console.WriteLine(line);
                    }
                    Console.ReadKey();
                }
            }
            else
            {
                Console.WriteLine("Error! Must be 2 or 3 arguments!(numberofsides,sidelength,typeofwriting(type 1 if you want to write to file))");
                Console.ReadKey();
                return(1);
            }

            return(0);
        }
Пример #39
0
 /// <summary>
 /// Adds a string to the log file.
 /// </summary>
 /// <param name="text">The string to write.</param>
 public void add(string text)
 {
     System.IO.StreamWriter file = new System.IO.StreamWriter(path, true);
     file.WriteLine("[" + DateTime.Now.ToString() + "] " + text);
     file.Close();
 }
Пример #40
0
        private void btnExportYwsj_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.RestoreDirectory = true;
            dlg.Filter           = "Excel Xml(*.xml)|*.xml";
            //saveFileDialog1.Title = "保存";
            string today = System.DateTime.Today.ToString("yyyy-MM-dd");

            today = "2010-01-28";
            string whereSql = "(A.Created >= '" + today + "' OR A.Updated >= '" + today + "')";

            string[] sqls = new string[] {
                "SELECT A.* FROM 财务_费用实体 A WHERE (A.费用实体类型 = 11 OR A.费用实体类型 = 15 OR A.费用实体类型 = 45) AND " + whereSql,
                "SELECT B.* FROM 业务备案_普通票 B INNER JOIN 财务_费用实体 A ON A.ID = B.ID AND " + whereSql,
                "SELECT B.* FROM 业务备案_进口票 B INNER JOIN 财务_费用实体 A ON A.ID = B.ID AND " + whereSql,
                "SELECT B.* FROM 业务备案_内贸出港票 B INNER JOIN 财务_费用实体 A ON A.ID = B.ID AND " + whereSql,
                "SELECT B.* FROM 业务备案_进口其他业务票 B INNER JOIN 财务_费用实体 A ON A.ID = B.ID AND " + whereSql,
                "SELECT A.* FROM 业务备案_普通箱 A WHERE " + whereSql,
                "SELECT B.* FROM 业务备案_进口箱 B INNER JOIN 业务备案_普通箱 A ON A.ID = B.ID AND " + whereSql,
                "SELECT B.* FROM 业务备案_内贸出港箱 B INNER JOIN 业务备案_普通箱 A ON A.ID = B.ID AND " + whereSql,
                "SELECT B.* FROM 业务备案_进口其他业务箱 B INNER JOIN 业务备案_普通箱 A ON A.ID = B.ID AND " + whereSql,
                "SELECT A.* FROM 业务过程_进口票_转关标志 A WHERE " + whereSql,
                "SELECT B.* FROM 业务过程_进口票_转关 B INNER JOIN 业务过程_进口票_转关标志 A ON A.ID = B.ID AND " + whereSql,
                "SELECT B.* FROM 业务过程_进口票_清关 B INNER JOIN 业务过程_进口票_转关标志 A ON A.ID = B.ID AND " + whereSql,
                "SELECT A.* FROM 参数备案_币制 A WHERE " + whereSql,
                "SELECT A.* FROM 参数备案_人员单位 A WHERE " + whereSql,
                "SELECT A.* FROM 参数备案_箱型 A WHERE " + whereSql,
                "SELECT A.* FROM 信息_角色用途 A WHERE " + whereSql,
                "SELECT A.* FROM 信息_业务类型 A WHERE " + whereSql
            };

            string[] dbTables = new string[] {
                "财务_费用实体",
                "业务备案_普通票",
                "业务备案_进口票",
                "业务备案_内贸出港票",
                "业务备案_进口其他业务票",
                "业务备案_普通箱",
                "业务备案_进口箱",
                "业务备案_内贸出港箱",
                "业务备案_进口其他业务箱",
                "业务过程_进口票_转关标志",
                "业务过程_进口票_转关",
                "业务过程_进口票_清关",
                "参数备案_币制",
                "参数备案_人员单位",
                "参数备案_箱型",
                "信息_角色用途",
                "信息_业务类型"
            };
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter(dlg.FileName, false, Encoding.UTF8);
                ExcelXmlHelper.WriteExcelXmlHead(sw);

                if (dbTables.Length != sqls.Length)
                {
                    throw new ArgumentException("length should be equal!");
                }
                for (int i = 0; i < sqls.Length; ++i)
                {
                    ExcelXmlHelper.WriteExcelXml(Feng.Data.DbHelper.Instance.ExecuteDataTable(sqls[i]), sw, dbTables[i]);
                }
                ExcelXmlHelper.WriteExcelXmlTail(sw);
                sw.Close();
            }
        }
Пример #41
0
        internal static List <string> GenerateDelegateBinding(List <Type> types, string outputPath)
        {
            if (types == null)
            {
                types = new List <Type>(0);
            }

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

            foreach (var i in types)
            {
                var mi           = i.GetMethod("Invoke");
                var miParameters = mi.GetParameters();
                if (mi.ReturnType == typeof(void) && miParameters.Length == 0)
                {
                    continue;
                }

                string clsName, realClsName, paramClsName, paramRealClsName;
                bool   isByRef, paramIsByRef;
                i.GetClassName(out clsName, out realClsName, out isByRef);
                clsNames.Add(clsName);
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/" + clsName + ".cs", false, new UTF8Encoding(false)))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(@"#if USE_HOT
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;

using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;

namespace ILRuntime.Runtime.Generated
{
    unsafe class ");
                    sb.AppendLine(clsName);
                    sb.AppendLine(@"    {
        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
        {");
                    bool first = true;

                    if (mi.ReturnType != typeof(void))
                    {
                        sb.Append("            app.DelegateManager.RegisterFunctionDelegate<");
                        first = true;
                        foreach (var j in miParameters)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                sb.Append(", ");
                            }
                            j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef);
                            sb.Append(paramRealClsName);
                        }
                        if (!first)
                        {
                            sb.Append(", ");
                        }
                        mi.ReturnType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef);
                        sb.Append(paramRealClsName);
                        sb.AppendLine("> ();");
                    }
                    else
                    {
                        sb.Append("            app.DelegateManager.RegisterMethodDelegate<");
                        first = true;
                        foreach (var j in miParameters)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                sb.Append(", ");
                            }
                            j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef);
                            sb.Append(paramRealClsName);
                        }
                        sb.AppendLine("> ();");
                    }
                    sb.AppendLine();

                    sb.Append("            app.DelegateManager.RegisterDelegateConvertor<");
                    sb.Append(realClsName);
                    sb.AppendLine(">((act) =>");
                    sb.AppendLine("            {");
                    sb.Append("                return new ");
                    sb.Append(realClsName);
                    sb.Append("((");
                    first = true;
                    foreach (var j in miParameters)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            sb.Append(", ");
                        }
                        sb.Append(j.Name);
                    }
                    sb.AppendLine(") =>");
                    sb.AppendLine("                {");
                    if (mi.ReturnType != typeof(void))
                    {
                        sb.Append("                    return ((Func<");
                        first = true;
                        foreach (var j in miParameters)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                sb.Append(", ");
                            }
                            j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef);
                            sb.Append(paramRealClsName);
                        }
                        if (!first)
                        {
                            sb.Append(", ");
                        }
                        mi.ReturnType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef);
                        sb.Append(paramRealClsName);
                    }
                    else
                    {
                        sb.Append("                    ((Action<");
                        first = true;
                        foreach (var j in miParameters)
                        {
                            if (first)
                            {
                                first = false;
                            }
                            else
                            {
                                sb.Append(", ");
                            }
                            j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef);
                            sb.Append(paramRealClsName);
                        }
                    }
                    sb.Append(">)act)(");
                    first = true;
                    foreach (var j in miParameters)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            sb.Append(", ");
                        }
                        sb.Append(j.Name);
                    }
                    sb.AppendLine(");");
                    sb.AppendLine("                });");
                    sb.AppendLine("            });");

                    sb.AppendLine("        }");
                    sb.AppendLine("    }");
                    sb.AppendLine("}");
                    sb.AppendLine("#endif");

                    sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n"));
                    sw.Flush();
                }
            }

            return(clsNames);
        }
Пример #42
0
        private static void TestReadFile()
        {
            String dir      = @"D:\temp";
            String filename = "pressione.txt";
            String path     = dir + @"\" + filename;

            String out_temp  = "temperature.txt";
            String out_press = "pressure.txt";

            System.IO.StreamWriter tempOutputFile = new System.IO.StreamWriter(
                System.IO.Path.Combine(dir, out_temp));

            System.IO.StreamWriter pressOutputFile = new System.IO.StreamWriter(
                System.IO.Path.Combine(dir, out_press));

            int    var1 = 1000;
            string s1   = "aaaaaa";

            int    counter = 0;
            string line;

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

            float max_float = float.MaxValue;
            float min_float = float.MinValue;

            float min_temp  = max_float;
            float min_press = max_float;

            float max_temp  = min_float;
            float max_press = min_float;

            float sum_temp  = 0;
            float sum_press = 0;

            char[] chararray = new char[1];
            chararray[0] = '\t'; // ascii code  0x09

            while ((line = file.ReadLine()) != null)
            {
                if (counter > 0)
                {
                    String[] resultArray = line.Split(chararray);

                    tempOutputFile.WriteLine(resultArray[0]);
                    pressOutputFile.WriteLine(resultArray[1]);

                    float temp_float  = float.Parse(resultArray[0], CultureInfo.InvariantCulture);
                    float press_float = float.Parse(resultArray[1], CultureInfo.InvariantCulture);

                    if (temp_float > max_temp)
                    {
                        max_temp = temp_float;
                    }
                    if (temp_float < min_temp)
                    {
                        min_temp = temp_float;
                    }

                    if (press_float > max_press)
                    {
                        max_press = press_float;
                    }
                    if (press_float < min_press)
                    {
                        min_press = press_float;
                    }

                    sum_temp   = sum_temp + temp_float;
                    sum_press += press_float;
                }
                counter++;
            }
            file.Close();
            tempOutputFile.Close();
            pressOutputFile.Close();

            float media_temp  = sum_temp / (counter - 1);
            float media_press = sum_press / (counter - 1);

            System.Console.WriteLine(media_temp);
            System.Console.WriteLine(media_press);

            System.Console.WriteLine("There were {0} lines. {1} and {2}", counter, var1, s1);
            System.Console.WriteLine("Max temperature {0}, Min Temperature {1}", max_temp, min_temp);
            System.Console.WriteLine("Max pressure {0}, Min pressure {1}", max_press, min_press);
            System.Console.ReadLine();
        }
Пример #43
0
        public static void GenerateBindingCode(List <Type> types, string outputPath,
                                               HashSet <MethodBase> excludeMethods = null, HashSet <FieldInfo> excludeFields = null,
                                               List <Type> valueTypeBinders        = null, List <Type> delegateTypes = null)
        {
            if (!System.IO.Directory.Exists(outputPath))
            {
                System.IO.Directory.CreateDirectory(outputPath);
            }
            //string[] oldFiles = System.IO.Directory.GetFiles(outputPath, "*.cs");
            //foreach (var i in oldFiles)
            //{
            //    System.IO.File.Delete(i);
            //}

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

            foreach (var i in types)
            {
                string clsName, realClsName;
                bool   isByRef;
                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
                {
                    continue;
                }
                i.GetClassName(out clsName, out realClsName, out isByRef);
                clsNames.Add(clsName);

                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/" + clsName + ".cs", false, new UTF8Encoding(false)))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(@"#if USE_HOT
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Linq;
using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;

namespace ILRuntime.Runtime.Generated
{
    unsafe class ");
                    sb.AppendLine(clsName);
                    sb.Append(@"    {
        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
        {
");
                    string flagDef    = "            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;";
                    string methodDef  = "            MethodBase method;";
                    string methodsDef = "            MethodInfo[] methods = type.GetMethods(flag).Where(t => !t.IsGenericMethod).ToArray();";
                    string fieldDef   = "            FieldInfo field;";
                    string argsDef    = "            Type[] args;";
                    string typeDef    = string.Format("            Type type = typeof({0});", realClsName);

                    bool              needMethods;
                    MethodInfo[]      methods               = i.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    FieldInfo[]       fields                = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    string            registerMethodCode    = i.GenerateMethodRegisterCode(methods, excludeMethods, out needMethods);
                    string            registerFieldCode     = i.GenerateFieldRegisterCode(fields, excludeFields);
                    string            registerValueTypeCode = i.GenerateValueTypeRegisterCode(realClsName);
                    string            registerMiscCode      = i.GenerateMiscRegisterCode(realClsName, true, true);
                    string            commonCode            = i.GenerateCommonCode(realClsName);
                    ConstructorInfo[] ctors            = i.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
                    string            ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods);
                    string            methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods, valueTypeBinders, null);
                    string            fieldWraperCode  = i.GenerateFieldWraperCode(fields, realClsName, excludeFields, valueTypeBinders, null);
                    string            cloneWraperCode  = i.GenerateCloneWraperCode(fields, realClsName);
                    string            ctorWraperCode   = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods, valueTypeBinders);

                    bool hasMethodCode    = !string.IsNullOrEmpty(registerMethodCode);
                    bool hasFieldCode     = !string.IsNullOrEmpty(registerFieldCode);
                    bool hasValueTypeCode = !string.IsNullOrEmpty(registerValueTypeCode);
                    bool hasMiscCode      = !string.IsNullOrEmpty(registerMiscCode);
                    bool hasCtorCode      = !string.IsNullOrEmpty(ctorRegisterCode);
                    bool hasNormalMethod  = methods.Where(x => !x.IsGenericMethod).Count() != 0;

                    if ((hasMethodCode && hasNormalMethod) || hasFieldCode || hasCtorCode)
                    {
                        sb.AppendLine(flagDef);
                    }
                    if (hasMethodCode || hasCtorCode)
                    {
                        sb.AppendLine(methodDef);
                    }
                    if (hasFieldCode)
                    {
                        sb.AppendLine(fieldDef);
                    }
                    if (hasMethodCode || hasFieldCode || hasCtorCode)
                    {
                        sb.AppendLine(argsDef);
                    }
                    if (hasMethodCode || hasFieldCode || hasValueTypeCode || hasMiscCode || hasCtorCode)
                    {
                        sb.AppendLine(typeDef);
                    }
                    if (needMethods)
                    {
                        sb.AppendLine(methodsDef);
                    }


                    sb.AppendLine(registerMethodCode);
                    sb.AppendLine(registerFieldCode);
                    sb.AppendLine(registerValueTypeCode);
                    sb.AppendLine(registerMiscCode);
                    sb.AppendLine(ctorRegisterCode);
                    sb.AppendLine("        }");
                    sb.AppendLine();
                    sb.AppendLine(commonCode);
                    sb.AppendLine(methodWraperCode);
                    sb.AppendLine(fieldWraperCode);
                    sb.AppendLine(cloneWraperCode);
                    sb.AppendLine(ctorWraperCode);
                    sb.AppendLine("    }");
                    sb.AppendLine("}");
                    sb.AppendLine("#endif");

                    sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n"));
                    sw.Flush();
                }
            }

            var delegateClsNames = GenerateDelegateBinding(delegateTypes, outputPath);

            clsNames.AddRange(delegateClsNames);

            GenerateBindingInitializeScript(clsNames, valueTypeBinders, outputPath);
        }
Пример #44
0
        internal static void GenerateBindingInitializeScript(List <string> clsNames, List <Type> valueTypeBinders, string outputPath)
        {
            if (!System.IO.Directory.Exists(outputPath))
            {
                System.IO.Directory.CreateDirectory(outputPath);
            }

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/CLRBindings.cs", false, new UTF8Encoding(false)))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"#if USE_HOT
using System;
using System.Collections.Generic;
using System.Reflection;

namespace ILRuntime.Runtime.Generated
{
    class CLRBindings
    {");

                if (valueTypeBinders != null)
                {
                    sb.AppendLine();

                    foreach (var i in valueTypeBinders)
                    {
                        string clsName, realClsName;
                        bool   isByRef;
                        i.GetClassName(out clsName, out realClsName, out isByRef);

                        sb.AppendLine(string.Format("        internal static ILRuntime.Runtime.Enviorment.ValueTypeBinder<{0}> s_{1}_Binder = null;", realClsName, clsName));
                    }

                    sb.AppendLine();
                }

                sb.AppendLine(@"        /// <summary>
        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration
        /// </summary>
        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)
        {");
                if (clsNames != null)
                {
                    foreach (var i in clsNames)
                    {
                        sb.Append("            ");
                        sb.Append(i);
                        sb.AppendLine(".Register(app);");
                    }
                }

                if (valueTypeBinders != null)
                {
                    sb.AppendLine();

                    sb.AppendLine("            ILRuntime.CLR.TypeSystem.CLRType __clrType = null;");
                    foreach (var i in valueTypeBinders)
                    {
                        string clsName, realClsName;
                        bool   isByRef;
                        i.GetClassName(out clsName, out realClsName, out isByRef);

                        sb.AppendLine(string.Format("            __clrType = (ILRuntime.CLR.TypeSystem.CLRType)app.GetType (typeof({0}));", realClsName));
                        sb.AppendLine(string.Format("            s_{0}_Binder = __clrType.ValueTypeBinder as ILRuntime.Runtime.Enviorment.ValueTypeBinder<{1}>;", clsName, realClsName));
                    }
                }
                sb.AppendLine(@"        }");

                sb.AppendLine(@"
        /// <summary>
        /// Release the CLR binding, please invoke this BEFORE ILRuntime Appdomain destroy
        /// </summary>
        public static void Shutdown(ILRuntime.Runtime.Enviorment.AppDomain app)
        {");
                if (valueTypeBinders != null)
                {
                    foreach (var i in valueTypeBinders)
                    {
                        string clsName, realClsName;
                        bool   isByRef;
                        i.GetClassName(out clsName, out realClsName, out isByRef);

                        sb.AppendLine(string.Format("            s_{0}_Binder = null;", clsName));
                    }
                }
                sb.AppendLine(@"        }");

                sb.AppendLine(@"    }
}");
                sb.AppendLine("#endif");
                sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n"));
            }
        }
Пример #45
0
        public static string WriteToXml(ExSubjectCard kartaPrzedmiotu)
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + kartaPrzedmiotu.Kod + ".xml";

            System.IO.StreamWriter file = new System.IO.StreamWriter(path);
            XElement kartaXML           = new XElement("Karta");

            kartaXML.Add(new XElement("Nazwa_polska", kartaPrzedmiotu.NazwaPolska));
            kartaXML.Add(new XElement("Nazwa_angielska", kartaPrzedmiotu.NazwaAngielska));
            kartaXML.Add(new XElement("Rodzaj_przedmiotu", kartaPrzedmiotu.RodzajPrzedmiotu));
            kartaXML.Add(new XElement("Grupa_kursow", kartaPrzedmiotu.GrupaKursów));
            kartaXML.Add(new XElement("Forma_studiow", kartaPrzedmiotu.FormaStudiów));
            kartaXML.Add(new XElement("Stopien_studiow", kartaPrzedmiotu.Stopień));
            kartaXML.Add(new XElement("Kod_przedmiotu", kartaPrzedmiotu.Kod));
            kartaXML.Add(new XElement("Kierunek", kartaPrzedmiotu.Kierunek));
            kartaXML.Add(new XElement("Specjalnosc", kartaPrzedmiotu.Specjalność));

            List <Wymaganie_wstępne>     wymagania = DbManager.GetWymagania(kartaPrzedmiotu.Id);
            List <Cel_przedmiotu>        cele      = DbManager.GetCele(1);
            List <Narzędzia_dydaktyczne> narzędzia = DbManager.GetNarzędzia(1);

            XElement tree = new XElement("Wymagania_wstepne");
            int      i    = 0;

            foreach (var element in wymagania)
            {
                i++;
                tree.Add(new XElement("Wymaganie_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            tree = new XElement("Cele_przedmiotu");
            i    = 0;
            foreach (var element in cele)
            {
                i++;
                tree.Add(new XElement("Cel_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            tree = new XElement("Narzędzia_dydaktyczne");
            i    = 0;
            foreach (var element in narzędzia)
            {
                i++;
                tree.Add(new XElement("N_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            List <Literatura> literatura = DbManager.GetLiteratura(kartaPrzedmiotu.Id, 1);

            tree = new XElement("Literatura_podstawowa");
            i    = 0;
            foreach (var element in literatura)
            {
                i++;
                tree.Add(new XElement("L_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            literatura = DbManager.GetLiteratura(kartaPrzedmiotu.Id, 2);
            tree       = new XElement("Literatura_uzupelniajaca");
            i          = 0;
            foreach (var element in literatura)
            {
                i++;
                tree.Add(new XElement("L_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            List <Przedmiotowy_efekt_kształcenia> peki = DbManager.GetPEK(kartaPrzedmiotu.Id, 1);

            tree = new XElement("PEK_z_zakresu_wiedzy");
            i    = 0;
            foreach (var element in peki)
            {
                i++;
                tree.Add(new XElement("PEK_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            peki = DbManager.GetPEK(kartaPrzedmiotu.Id, 2);
            tree = new XElement("PEK_z_zakresu_umiejętności");
            i    = 0;
            foreach (var element in peki)
            {
                i++;
                tree.Add(new XElement("PEK_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            peki = DbManager.GetPEK(kartaPrzedmiotu.Id, 3);
            tree = new XElement("PEK_z_zakresu_kompetencji");
            i    = 0;
            foreach (var element in peki)
            {
                i++;
                tree.Add(new XElement("PEK_" + i.ToString(), element.Nazwa));
            }
            kartaXML.Add(tree);

            List <Treść_programowa> treści = DbManager.GetTreściProgramowe(kartaPrzedmiotu.Id);

            tree = new XElement("Treść_programowa");
            i    = 0;
            foreach (var element in treści)
            {
                i++;

                XElement           tree2  = new XElement("F" + element.FormaZajeć.ToString());
                List <Temat_zajęć> tematy = DbManager.GetTematyZajęć((int)element.FormaZajeć);
                int j = 0;
                foreach (var element2 in tematy)
                {
                    tree2.Add(new XElement("Nr" + element2.NumerZajęć.ToString(), element2.Temat));
                }
                tree.Add(tree2);
            }
            kartaXML.Add(tree);

            file.WriteLine(kartaXML);
            file.Close();

            return(path);
        }
Пример #46
0
        public static void GenerateBindingCode(ILRuntime.Runtime.Enviorment.AppDomain domain, string outputPath,
                                               List <Type> valueTypeBinders = null, List <Type> delegateTypes = null,
                                               params string[] excludeFiles)
        {
            if (domain == null)
            {
                return;
            }
            if (!System.IO.Directory.Exists(outputPath))
            {
                System.IO.Directory.CreateDirectory(outputPath);
            }
            Dictionary <Type, CLRBindingGenerateInfo> infos = new Dictionary <Type, CLRBindingGenerateInfo>(new ByReferenceKeyComparer <Type>());

            CrawlAppdomain(domain, infos);
            string[] oldFiles = System.IO.Directory.GetFiles(outputPath, "*.cs");
            foreach (var i in oldFiles)
            {
                System.IO.File.Delete(i);
            }

            if (valueTypeBinders == null)
            {
                valueTypeBinders = new List <Type>(domain.ValueTypeBinders.Keys);
            }

            HashSet <MethodBase> excludeMethods = null;
            HashSet <FieldInfo>  excludeFields  = null;
            HashSet <string>     files          = new HashSet <string>();
            List <string>        clsNames       = new List <string>();

            foreach (var info in infos)
            {
                if (!info.Value.NeedGenerate)
                {
                    continue;
                }
                Type i = info.Value.Type;

                //CLR binding for delegate is important for cross domain invocation,so it should be generated
                //if (i.BaseType == typeof(MulticastDelegate))
                //    continue;

                string clsName, realClsName;
                bool   isByRef;
                if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
                {
                    continue;
                }
                i.GetClassName(out clsName, out realClsName, out isByRef);
                if (excludeFiles.Contains(clsName))
                {
                    continue;
                }
                if (clsNames.Contains(clsName))
                {
                    clsName = clsName + "_t";
                }
                clsNames.Add(clsName);

                //File path length limit
                string oriFileName = outputPath + "/" + clsName;
                int    len         = Math.Min(oriFileName.Length, 100);
                if (len < oriFileName.Length)
                {
                    oriFileName = oriFileName.Substring(0, len);
                }

                int    extraNameIndex = 0;
                string oFileName      = oriFileName;
                while (files.Contains(oFileName))
                {
                    extraNameIndex++;
                    oFileName = oriFileName + "_t" + extraNameIndex;
                }

                files.Add(oFileName);
                oFileName = oFileName + ".cs";
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(oFileName, false, new UTF8Encoding(false)))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append(@"#if USE_HOT
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;

using ILRuntime.CLR.TypeSystem;
using ILRuntime.CLR.Method;
using ILRuntime.Runtime.Enviorment;
using ILRuntime.Runtime.Intepreter;
using ILRuntime.Runtime.Stack;
using ILRuntime.Reflection;
using ILRuntime.CLR.Utils;

namespace ILRuntime.Runtime.Generated
{
    unsafe class ");
                    sb.AppendLine(clsName);
                    sb.Append(@"    {
        public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app)
        {
");
                    string flagDef    = "            BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;";
                    string methodDef  = "            MethodBase method;";
                    string methodsDef = "            MethodInfo[] methods = type.GetMethods(flag).Where(t => !t.IsGenericMethod).ToArray();";
                    string fieldDef   = "            FieldInfo field;";
                    string argsDef    = "            Type[] args;";
                    string typeDef    = string.Format("            Type type = typeof({0});", realClsName);

                    bool              needMethods;
                    MethodInfo[]      methods               = info.Value.Methods.ToArray();
                    FieldInfo[]       fields                = info.Value.Fields.ToArray();
                    string            registerMethodCode    = i.GenerateMethodRegisterCode(methods, excludeMethods, out needMethods);
                    string            registerFieldCode     = fields.Length > 0 ? i.GenerateFieldRegisterCode(fields, excludeFields) : null;
                    string            registerValueTypeCode = info.Value.ValueTypeNeeded ? i.GenerateValueTypeRegisterCode(realClsName) : null;
                    string            registerMiscCode      = i.GenerateMiscRegisterCode(realClsName, info.Value.DefaultInstanceNeeded, info.Value.ArrayNeeded);
                    string            commonCode            = i.GenerateCommonCode(realClsName);
                    ConstructorInfo[] ctors            = info.Value.Constructors.ToArray();
                    string            ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods);
                    string            methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods, valueTypeBinders, domain);
                    string            fieldWraperCode  = fields.Length > 0 ? i.GenerateFieldWraperCode(fields, realClsName, excludeFields, valueTypeBinders, domain) : null;
                    string            cloneWraperCode  = null;
                    if (info.Value.ValueTypeNeeded)
                    {
                        //Memberwise clone should copy all fields
                        var fs = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
                        cloneWraperCode = i.GenerateCloneWraperCode(fs, realClsName);
                    }

                    bool hasMethodCode    = !string.IsNullOrEmpty(registerMethodCode);
                    bool hasFieldCode     = !string.IsNullOrEmpty(registerFieldCode);
                    bool hasValueTypeCode = !string.IsNullOrEmpty(registerValueTypeCode);
                    bool hasMiscCode      = !string.IsNullOrEmpty(registerMiscCode);
                    bool hasCtorCode      = !string.IsNullOrEmpty(ctorRegisterCode);
                    bool hasNormalMethod  = methods.Where(x => !x.IsGenericMethod).Count() != 0;

                    if ((hasMethodCode && hasNormalMethod) || hasFieldCode || hasCtorCode)
                    {
                        sb.AppendLine(flagDef);
                    }
                    if (hasMethodCode || hasCtorCode)
                    {
                        sb.AppendLine(methodDef);
                    }
                    if (hasFieldCode)
                    {
                        sb.AppendLine(fieldDef);
                    }
                    if (hasMethodCode || hasFieldCode || hasCtorCode)
                    {
                        sb.AppendLine(argsDef);
                    }
                    if (hasMethodCode || hasFieldCode || hasValueTypeCode || hasMiscCode || hasCtorCode)
                    {
                        sb.AppendLine(typeDef);
                    }
                    if (needMethods)
                    {
                        sb.AppendLine(methodsDef);
                    }

                    sb.AppendLine(registerMethodCode);
                    if (fields.Length > 0)
                    {
                        sb.AppendLine(registerFieldCode);
                    }
                    if (info.Value.ValueTypeNeeded)
                    {
                        sb.AppendLine(registerValueTypeCode);
                    }
                    if (!string.IsNullOrEmpty(registerMiscCode))
                    {
                        sb.AppendLine(registerMiscCode);
                    }
                    sb.AppendLine(ctorRegisterCode);
                    sb.AppendLine("        }");
                    sb.AppendLine();
                    sb.AppendLine(commonCode);
                    sb.AppendLine(methodWraperCode);
                    if (fields.Length > 0)
                    {
                        sb.AppendLine(fieldWraperCode);
                    }
                    if (info.Value.ValueTypeNeeded)
                    {
                        sb.AppendLine(cloneWraperCode);
                    }
                    string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods, valueTypeBinders);
                    sb.AppendLine(ctorWraperCode);
                    sb.AppendLine("    }");
                    sb.AppendLine("}");

                    sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n"));
                    sw.Flush();
                }
            }

            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/CLRBindings.cs", false, new UTF8Encoding(false)))
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(@"#if USE_HOT
using System;
using System.Collections.Generic;
using System.Reflection;

namespace ILRuntime.Runtime.Generated
{
    class CLRBindings
    {
        /// <summary>
        /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration
        /// </summary>
        public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app)
        {");
                foreach (var i in clsNames)
                {
                    sb.Append("            ");
                    sb.Append(i);
                    sb.AppendLine(".Register(app);");
                }

                sb.AppendLine(@"        }
    }
}");
                sb.AppendLine(@"#endif");
                sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n"));
            }

            var delegateClsNames = GenerateDelegateBinding(delegateTypes, outputPath);

            clsNames.AddRange(delegateClsNames);

            GenerateBindingInitializeScript(clsNames, valueTypeBinders, outputPath);
        }
Пример #47
0
        /// <summary>
        /// Constructs a new SingleInstance object
        /// </summary>
        /// <param name="basefolder">The folder in which the control file structure is placed</param>
        ///
        public SingleInstance(string basefolder)
        {
            if (!System.IO.Directory.Exists(basefolder))
            {
                System.IO.Directory.CreateDirectory(basefolder);
            }

            m_controldir = System.IO.Path.Combine(basefolder, CONTROL_DIR);
            if (!System.IO.Directory.Exists(m_controldir))
            {
                System.IO.Directory.CreateDirectory(m_controldir);
            }

            m_lockfilename = System.IO.Path.Combine(m_controldir, CONTROL_FILE);
            m_file         = null;

            System.IO.Stream temp_fs = null;

            try
            {
                if (Platform.IsClientPosix)
                {
                    temp_fs = UnixSupport.File.OpenExclusive(m_lockfilename, System.IO.FileAccess.Write);
                }
                else
                {
                    temp_fs = System.IO.File.Open(m_lockfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
                }

                if (temp_fs != null)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(temp_fs);
                    sw.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Id);
                    sw.Flush();
                    //Do not dispose sw as that would dispose the stream
                    m_file = temp_fs;
                }
            }
            catch
            {
                if (temp_fs != null)
                {
                    try { temp_fs.Dispose(); }
                    catch {}
                }
            }

            //If we have write access
            if (m_file != null)
            {
                m_filewatcher                     = new System.IO.FileSystemWatcher(m_controldir);
                m_filewatcher.Created            += new System.IO.FileSystemEventHandler(m_filewatcher_Created);
                m_filewatcher.EnableRaisingEvents = true;

                DateTime startup = System.IO.File.GetLastWriteTime(m_lockfilename);

                //Clean up any files that were created before the app launched
                foreach (string s in SystemIO.IO_OS.GetFiles(m_controldir))
                {
                    if (s != m_lockfilename && System.IO.File.GetCreationTime(s) < startup)
                    {
                        try { System.IO.File.Delete(s); }
                        catch { }
                    }
                }
            }
            else
            {
                //Wait for the initial process to signal that the filewatcher is activated
                int retrycount = 5;
                while (retrycount > 0 && new System.IO.FileInfo(m_lockfilename).Length == 0)
                {
                    System.Threading.Thread.Sleep(500);
                    retrycount--;
                }

                //HACK: the unix file lock does not allow us to read the file length when the file is locked
                if (new System.IO.FileInfo(m_lockfilename).Length == 0)
                {
                    if (!Platform.IsClientPosix)
                    {
                        throw new Exception("The file was locked, but had no data");
                    }
                }

                //Notify the other process that we have started
                string filename = System.IO.Path.Combine(m_controldir, COMM_FILE_PREFIX + Guid.NewGuid().ToString());

                //Write out the commandline arguments
                string[] cmdargs = System.Environment.GetCommandLineArgs();
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Platform.IsClientPosix ? UnixSupport.File.OpenExclusive(filename, System.IO.FileAccess.Write) : new System.IO.FileStream(filename, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None)))
                    for (int i = 1; i < cmdargs.Length; i++) //Skip the first, as that is the filename
                    {
                        sw.WriteLine(cmdargs[i]);
                    }

                //Wait for the other process to delete the file, indicating that it is processed
                retrycount = 5;
                while (retrycount > 0 && System.IO.File.Exists(filename))
                {
                    System.Threading.Thread.Sleep(500);
                    retrycount--;
                }

                //This may happen if the other process is closing as we write the command
                if (System.IO.File.Exists(filename))
                {
                    //Try to clean up, so the other process does not spuriously show this
                    try { System.IO.File.Delete(filename); }
                    catch { }

                    throw new Exception("The lock file was locked, but the locking process did not respond to the start command");
                }
            }
        }
Пример #48
0
 public void dbugStartRecord(System.IO.StreamWriter writer)
 {
     dbug_LexerReport = new dbugLexerReport();
     dbug_LexerReport.Start(writer);
 }
 public void evaluate(System.IO.StreamWriter file)
 {
     this.fit = pheno.Eva(file);
 }
Пример #50
0
        private void ButtonStart_Click(object sender, EventArgs e)
        {
            string sSpawnListFile;
            string sTemp;

            string[] aTemp;

            System.IO.StreamReader inSpawnFile;

            // LOADING npc_pch.txt
            if (System.IO.File.Exists("npc_pch.txt") == false)
            {
                MessageBox.Show("npc_pch.txt not found", "Need npc_pch.txt", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var aNpcPch = new string[40001];

            inSpawnFile = new System.IO.StreamReader("npc_pch.txt", System.Text.Encoding.Default, true, 1);
            ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length);
            ToolStripStatusLabel.Text    = "Loading npc_pch.txt ...";

            while (inSpawnFile.EndOfStream != true)
            {
                sTemp = inSpawnFile.ReadLine().Trim();
                ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position);
                if (!string.IsNullOrEmpty(sTemp) & sTemp.StartsWith("//") == false)
                {
                    // [pet_wolf_a] = 1012077
                    sTemp = sTemp.Replace(" ", "").Replace(Conversions.ToString((char)9), "");
                    aTemp = sTemp.Split(Conversions.ToChar("="));
                    try
                    {
                        aNpcPch[Conversions.ToInteger(aTemp[1]) - 1000000] = aTemp[0].Replace("[", "").Replace("]", "");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error in loading npc_pch.txt. Last reading line:" + Constants.vbNewLine + sTemp);
                        inSpawnFile.Close();
                        return;
                    }
                }
            }
            inSpawnFile.Close();
            ToolStripProgressBar.Value = 0;

            // LOADING item_pch.txt
            if (System.IO.File.Exists("item_pch.txt") == false)
            {
                MessageBox.Show("item_pch.txt not found", "Need item_pch.txt", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var aItemPch = new string[25001];

            inSpawnFile = new System.IO.StreamReader("item_pch.txt", System.Text.Encoding.Default, true, 1);
            ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length);
            ToolStripStatusLabel.Text    = "Loading item_pch.txt ...";

            while (inSpawnFile.EndOfStream != true)
            {
                sTemp = inSpawnFile.ReadLine().Trim();
                ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position);
                if (!string.IsNullOrEmpty(sTemp) & sTemp.StartsWith("//") == false)
                {
                    // [small_sword] = 1
                    sTemp = sTemp.Replace(" ", "").Replace(Conversions.ToString((char)9), "");
                    aTemp = sTemp.Split(Conversions.ToChar("="));
                    try
                    {
                        aItemPch[Conversions.ToInteger(aTemp[1])] = aTemp[0].Replace("[", "").Replace("]", "");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error in loading item_pch.txt. Last reading line:" + Constants.vbNewLine + sTemp);
                        inSpawnFile.Close();
                        return;
                    }
                }
            }
            inSpawnFile.Close();
            ToolStripProgressBar.Value = 0;

            // LOADING merchant_shopids.sql
            if (System.IO.File.Exists("merchant_shopids.sql") == false)
            {
                MessageBox.Show("merchant_shopids.sql not found", "Need merchant_shopids.sql", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var aShopId  = new string[1001];
            var aShopNpc = new string[1001];

            inSpawnFile = new System.IO.StreamReader("merchant_shopids.sql", System.Text.Encoding.Default, true, 1);
            ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length);
            ToolStripStatusLabel.Text    = "Loading merchant_shopids.sql ...";
            int iTempCount = 0;

            while (inSpawnFile.EndOfStream != true)
            {
                sTemp = inSpawnFile.ReadLine().Trim();
                ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position);
                if (sTemp.StartsWith("(") == true)
                {
                    // (3000100,'30001'),
                    // (9029,'gm'),
                    sTemp = sTemp.Substring(Strings.InStr(sTemp, "("), Strings.InStr(sTemp, ")") - Strings.InStr(sTemp, "(") - 1);
                    sTemp = sTemp.Replace("'", "");
                    aTemp = sTemp.Split(Conversions.ToChar(","));

                    Array.Resize(ref aShopId, iTempCount + 1);
                    Array.Resize(ref aShopNpc, iTempCount + 1);
                    aShopId[iTempCount]  = aTemp[0];
                    aShopNpc[iTempCount] = aTemp[1].Replace("'", "").Trim();
                    iTempCount           = iTempCount + 1;
                }
            }
            inSpawnFile.Close();
            ToolStripProgressBar.Value = 0;


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

            OpenFileDialog.Filter = "L2J AI.obj BuySell List config (merchant_buylists.sql)|merchant_buylists.sql|All files|*.*";
            if (OpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            sSpawnListFile = OpenFileDialog.FileName;
            inSpawnFile    = new System.IO.StreamReader(sSpawnListFile, System.Text.Encoding.Default, true, 1);
            var outFile = new System.IO.StreamWriter("ai_buysell_list_l2j.txt", false, System.Text.Encoding.Unicode, 1);

            ToolStripProgressBar.Maximum = Conversions.ToInteger(inSpawnFile.BaseStream.Length);
            ToolStripStatusLabel.Text    = "Loading merchant_buylists.sql...";

            int    iNpcCount    = 0;
            string sCurNpcName  = "";
            string sPrevNpcName = "";
            string sCurShopId   = "";
            string sPrevShopId  = "";
            string sItemPch     = "";
            string sTempItemName;
            string sTempNpcName;

            var aItemMiss = new int[1];
            var aNpcMiss  = new int[1];

            while (inSpawnFile.EndOfStream != true)
            {
                sTemp = inSpawnFile.ReadLine().Trim();
                ToolStripProgressBar.Value = Conversions.ToInteger(inSpawnFile.BaseStream.Position);
                if (!string.IsNullOrEmpty(sTemp) & sTemp.StartsWith("(") == true)
                {
                    sTemp = sTemp.Substring(Strings.InStr(sTemp, "("), Strings.InStr(sTemp, ")") - Strings.InStr(sTemp, "(") - 1);
                    sTemp = sTemp.Replace("'", "");
                    aTemp = sTemp.Split(Conversions.ToChar(","));

                    // 0           1        2       3
                    // `item_id`,`price`,`shop_id`,`order`
                    // (1835,      -1,    13128001,  0),

                    // class 1 asamah : citizen
                    // property_define_begin
                    // buyselllist_begin SellList0
                    // {8764; 35; 0.000000; 0 }
                    // {8763; 35; 0.000000; 0 }
                    // buyselllist_end
                    // buyselllist_begin SellList1
                    // {8764; 35; 0.000000; 0 }
                    // {8763; 35; 0.000000; 0 }
                    // buyselllist_end
                    // property_define_end
                    // handler 4 1362  //  TALK_SELECTED

                    // class asamah : citizen
                    // {
                    // property:
                    // BuySellList SellList0 = {
                    // {"trap_stone"; 35; 0.000000; 0};
                    // {"elrokian_trap"; 35; 0.000000; 0}
                    // };
                    // handler:
                    // EventHandler TALK_SELECTED(talker)

                    if (Array.IndexOf(aShopId, aTemp[2]) == -1)
                    {
                        sTempNpcName = "";
                    }
                    else
                    {
                        sTempNpcName = aShopNpc[Array.IndexOf(aShopId, aTemp[2])];
                        if ((sTempNpcName ?? "") == "gm")
                        {
                            sTempNpcName = "";
                        }
                    }
                    sItemPch   = aTemp[0];
                    sCurShopId = aTemp[2];

                    if (!string.IsNullOrEmpty(sTempNpcName))
                    {
                        // Checking exising npc in NpcPch
                        if (aNpcPch[Conversions.ToInteger(sTempNpcName)] == null)
                        {
                            if (Array.IndexOf(aNpcMiss, sTempNpcName) == -1)
                            {
                                aNpcMiss[aNpcMiss.Length - 1] = Conversions.ToInteger(sTempNpcName);
                                Array.Resize(ref aNpcMiss, aNpcMiss.Length + 1);
                            }

                            sCurNpcName = "[_need_" + sTempNpcName + "_]";
                        }
                        else
                        {
                            sCurNpcName = aNpcPch[Conversions.ToInteger(sTempNpcName)];
                        }
                        if ((sPrevNpcName ?? "") != (sCurNpcName ?? ""))
                        {
                            if (!string.IsNullOrEmpty(sPrevNpcName))
                            {
                                outFile.WriteLine(Constants.vbNewLine + Constants.vbTab + "};");
                            }
                            outFile.WriteLine("class " + sCurNpcName + Constants.vbTab + "// " + sTempNpcName);
                            sPrevNpcName = sCurNpcName;
                            sPrevShopId  = "";
                        }
                        if ((sCurShopId ?? "") != (sPrevShopId ?? ""))
                        {
                            // BuySellList SellList1 = {
                            if (!string.IsNullOrEmpty(sPrevShopId))
                            {
                                outFile.WriteLine(Constants.vbNewLine + Constants.vbTab + "};");
                            }
                            outFile.WriteLine(Constants.vbTab + "BuySellList SellList" + sCurShopId + " = {");
                            sPrevShopId = sCurShopId;
                        }
                        else
                        {
                            outFile.WriteLine(";");
                        }

                        if (aItemPch[Conversions.ToInteger(sItemPch)] == null)
                        {
                            if (Array.IndexOf(aItemMiss, Conversions.ToInteger(sItemPch)) == -1)
                            {
                                aItemMiss[aItemMiss.Length - 1] = Conversions.ToInteger(sItemPch);
                                Array.Resize(ref aItemMiss, aItemMiss.Length + 1);
                            }
                            sTempItemName = "[_need_" + Conversions.ToString(Conversions.ToInteger(Conversions.ToInteger(sItemPch))) + "_]";
                        }
                        else
                        {
                            sTempItemName = aItemPch[Conversions.ToInteger(sItemPch)];
                        }
                        if (Conversions.ToInteger(sItemPch) > 25000)
                        {
                            MessageBox.Show("Wrong item_id [" + sItemPch + "] in line" + Constants.vbNewLine + sTemp);
                            inSpawnFile.Close();
                            outFile.Close();
                            ToolStripProgressBar.Value = 0;
                            return;
                        }

                        outFile.Write(Constants.vbTab + Constants.vbTab + "{\"" + sTempItemName + "\"; 15; 0.000000; 0 }");
                    }
                }
            }
            ToolStripProgressBar.Value = 0;
            inSpawnFile.Close();
            outFile.Close();

            if (aNpcMiss.Length > 0)
            {
                outFile = new System.IO.StreamWriter("npcdata_drop_l2j.log", false, System.Text.Encoding.Unicode, 1);
                outFile.WriteLine("Missed Npc. Required for NpcData drop:");
                var loopTo = aNpcMiss.Length - 2;
                for (iNpcCount = 0; iNpcCount <= loopTo; iNpcCount++)
                {
                    outFile.WriteLine("npc_id=" + Conversions.ToString(aNpcMiss[iNpcCount]));
                }
                outFile.Close();
            }
            if (aItemMiss.Length > 0)
            {
                outFile = new System.IO.StreamWriter("npcdata_drop_l2j.log", true, System.Text.Encoding.Unicode, 1);
                outFile.WriteLine("Missed Items. Required for NpcData drop:");
                var loopTo1 = aItemMiss.Length - 2;
                for (iNpcCount = 0; iNpcCount <= loopTo1; iNpcCount++)
                {
                    outFile.WriteLine("item_id=" + Conversions.ToString(aItemMiss[iNpcCount]));
                }
                outFile.Close();
            }

            MessageBox.Show("Completed. With [" + Conversions.ToString(aItemMiss.Length - 1) + "] missed item's [" + Conversions.ToString(aNpcMiss.Length - 1) + "] missed npc's.");
        }
Пример #51
0
        static void BatchExecute(string TableName)
        {
            const string QUERY_TERM = "\r\n\0\r\n";

            string[] queries;

            Console.WriteLine("Inserting one row...");
            queries = new string[]
            {
                "insert into " + TableName + " values(881,'{C3014915-DC5F-4475-94D7-609F9F6A86F2}',121255,121255,121255);"
            };
            {
                if (!System.IO.Directory.Exists(@"c:\temp"))
                {
                    System.IO.Directory.CreateDirectory(@"c:\temp");
                }
                string befp = @"\\" + System.Net.Dns.GetHostName() + @"\c$\temp\batchexecute-test-" + Guid.NewGuid().ToString() + ".txt";
                using (System.IO.StreamWriter sw = System.IO.File.CreateText(befp))
                {
                    foreach (string q in queries)
                    {
                        sw.Write(q);
                        sw.Write(QUERY_TERM);
                    }
                }
                try
                {
                    Console.WriteLine(QaExec(" BATCHEXECUTE   '" + befp + "'; ").Trim());

                    string outputSelect1 = QaExec("SELECT TOP 1 * FROM " + TableName + " WHERE x = 121255 ORDER BY NUM;");
                    if (-1 == outputSelect1.IndexOf("{C3014915-DC5F-4475-94D7-609F9F6A86F2}"))
                    {
                        Console.Error.WriteLine("Did not find expected batch- inserted values; SELECT output: {0}", outputSelect1.Trim());
                        throw new Exception("Did not find expected batch- inserted values");
                    }
                }
                finally
                {
                    System.IO.File.Delete(befp);
                }
            }

            Console.WriteLine("Inserting multiple rows with an intermixed select...");
            queries = new string[]
            {
                "insert into " + TableName + " values(882,'{2F010B06-144F-490b-BD59-8BE4A6E16E76}',121255,121255,121255);",
                "insert into " + TableName + " values(883,'{777225D8-5E48-4eec-9A39-D39757E3638A}',121255,121255,121255);",
                "select top 50 * from " + TableName + " where x = 121255 ORDER BY NUM;",     // Note: this gets sent to stdout.
                "insert into " + TableName + " values(880,'{39104784-23CA-4929-BB4D-227E1309FEA5}',121255,121255,121255);"
            };
            {
                if (!System.IO.Directory.Exists(@"c:\temp"))
                {
                    System.IO.Directory.CreateDirectory(@"c:\temp");
                }
                string befp = @"\\" + System.Net.Dns.GetHostName() + @"\c$\temp\batchexecute-test-" + Guid.NewGuid().ToString() + ".txt";
                using (System.IO.StreamWriter sw = System.IO.File.CreateText(befp))
                {
                    foreach (string q in queries)
                    {
                        sw.Write(q);
                        sw.Write(QUERY_TERM);
                    }
                }
                try
                {
                    Console.WriteLine(QaExec(" BATCHEXECUTE   '" + befp + "'; ").Trim());

                    string outputSelect1 = QaExec("SELECT TOP 50 * FROM " + TableName + " WHERE x = 121255 ORDER BY NUM;");
                    if (-1 == outputSelect1.IndexOf("{39104784-23CA-4929-BB4D-227E1309FEA5}") || // After!
                        -1 == outputSelect1.IndexOf("{777225D8-5E48-4eec-9A39-D39757E3638A}")    // Before!
                        )
                    {
                        Console.Error.WriteLine("Did not find expected batch- inserted values; SELECT output: {0}", outputSelect1.Trim());
                        throw new Exception("Did not find expected batch- inserted values");
                    }
                }
                finally
                {
                    System.IO.File.Delete(befp);
                }
            }
        }
Пример #52
0
 Output(System.IO.Stream stream)
 {
     _sw = new System.IO.StreamWriter(stream);
 }
Пример #53
0
        static void Main(string[] args)
        {
            string yesnocheck;

            MMCAClass[] bankArray = new MMCAClass[10] {
                new MMCAClass(), new MMCAClass(),
                new MMCAClass(), new MMCAClass(), new MMCAClass(), new MMCAClass(), new MMCAClass(),
                new MMCAClass(), new MMCAClass(), new MMCAClass()
            };
            MMCAClass bankAccount = new MMCAClass();

            //saves the account array information
            System.IO.StreamWriter fileWrite = new System.IO.StreamWriter("accounts.txt");
            //loads the information
            System.IO.StringReader fileRead = new System.IO.StringReader("accounts.txt");
            string freeAccount = "";
            int    freeAccountInt;

            for (int strNumber = 0; strNumber <= bankArray.Length; strNumber++)
            {
                freeAccount         = fileRead.ReadLine();
                freeAccountInt      = int.Parse(freeAccount);
                fileRead.ReadLine() = bankArray[freeAccount].firstNameProps;
                fileRead.ReadLine() = bankArray[freeAccount].lastNameProps;
                fileRead.ReadLine() = bankArray[freeAccount].accountNumberProps;
                fileRead.ReadLine() = bankArray[freeAccount].balanceProps;
            }
            //menu
            Console.WriteLine("Do you have an existing bank account?" + Environment.NewLine +
                              "[1] - Yes" + Environment.NewLine + "[2] - No" + Environment.NewLine);
            yesnocheck = Console.ReadLine();

            if (yesnocheck == "2")
            {
                Console.WriteLine("Would you like to create a bank Account?" + Environment.NewLine +
                                  "[1] - Yes" + Environment.NewLine + "[2] - No" +
                                  Environment.NewLine);
                yesnocheck = Console.ReadLine();
                if (yesnocheck == "1")
                {
                    bankAccount.accountNumberProps = bankAccount.AccountGenerate();
                    Console.WriteLine("Please input your first name:" + Environment.NewLine);
                    bankAccount.firstNameProps = Console.ReadLine();
                    Console.WriteLine("Please input your last name:" + Environment.NewLine);
                    bankAccount.lastNameProps = Console.ReadLine();
                    Console.WriteLine(Environment.NewLine + "First Name: " + bankAccount.firstNameProps
                                      + Environment.NewLine + "Last Name: " + bankAccount.lastNameProps + Environment.NewLine +
                                      "Account Number: " + bankAccount.accountNumberProps + Environment.NewLine);
                    Console.ReadKey();
                    //store the information into a free account
                    int freeAccount = -1;
                    for (int strNumber = 0; strNumber <= bankArray.Length; strNumber++)
                    {
                        if (bankArray[strNumber].accountNumberProps == null)
                        {
                            freeAccount = strNumber;
                        }
                        if (freeAccount == strNumber)
                        {
                            break;
                        }
                    }
                    bankArray[freeAccount].firstNameProps     = bankAccount.firstNameProps;
                    bankArray[freeAccount].lastNameProps      = bankAccount.lastNameProps;
                    bankArray[freeAccount].accountNumberProps = bankAccount.accountNumberProps;
                    fileWrite.WriteLine(freeAccount.ToString(), bankArray[freeAccount].firstNameProps, bankArray[freeAccount].lastNameProps,
                                        bankArray[freeAccount].accountNumberProps, bankArray[freeAccount].balanceProps);
                    Console.WriteLine("What would you like to do?" + Environment.NewLine +
                                      "[1] - check balance" + Environment.NewLine + "[2] - deposit" + Environment.NewLine +
                                      "[3] - withdraw" + Environment.NewLine + "[4] - Calculate interest");
                    yesnocheck = Console.ReadLine();
                    if (yesnocheck == "1")
                    {
                        Console.WriteLine("Your balance is: " + bankArray[freeAccount].balanceProps + " usd");
                        Console.ReadKey();
                    }
                    if (yesnocheck == "2")
                    {
                        string depoString;
                        int    depositValue = 0
                        ;
                        Console.WriteLine("How much would you like to deposit?");
                        try
                        {
                            depoString   = Console.ReadLine();
                            depositValue = int.Parse(depoString);
                        }
                        catch
                        {
                            Console.WriteLine("Please input a numeric value here that you want to deposit");
                        }
                        bankAccount.balanceProps            = bankAccount.balanceProps + depositValue;
                        bankArray[freeAccount].balanceProps = bankAccount.balanceProps;
                        fileWrite.WriteLine(bankArray[freeAccount].balanceProps);
                        Console.WriteLine("Deposit Successful!" + Environment.NewLine + "Current Balance: "
                                          + bankAccount.balanceProps + " usd");
                        Console.ReadKey();
                    }
                    if (yesnocheck == "3")
                    {
                        string withString;
                        int    withdrawValue = 0;
                        Console.WriteLine("How much would you like to withdraw?");
                        try
                        {
                            withString    = Console.ReadLine();
                            withdrawValue = int.Parse(withString);
                        }
                        catch
                        {
                            Console.WriteLine("Please input a numeric value here that you want to withdraw");
                        }
                        bankAccount.balanceProps            = bankAccount.balanceProps - withdrawValue;
                        bankArray[freeAccount].balanceProps = bankAccount.balanceProps;
                        Console.WriteLine("Withdraw Successful!" + Environment.NewLine + "Current Balance: "
                                          + bankAccount.balanceProps + " usd");
                        fileWrite.WriteLine(bankArray[freeAccount].balanceProps);
                        Console.ReadKey();
                    }
                    if (yesnocheck == "4")
                    {
                        Console.WriteLine("Your interest rate is X where X is this bank's interest rate");
                    }
                }
                else
                {
                    Console.WriteLine("There's nothing else to be done here. Have a good day!");
                    Console.ReadKey();
                }
            }
            else
            {
                string accountString;
                Console.WriteLine("What is your account number?");
                accountString = Console.ReadLine();
                int strIndex = 0;
                for (int strNumber = 0; strNumber < bankArray.Length; strNumber++)
                {
                    if (accountString == bankArray[strNumber].accountNumberProps)
                    {
                        bankAccount.accountNumberProps = bankArray[strNumber].accountNumberProps;
                        bankAccount.balanceProps       = bankArray[strNumber].balanceProps;
                        bankAccount.firstNameProps     = bankArray[strNumber].firstNameProps;
                        bankAccount.lastNameProps      = bankArray[strNumber].lastNameProps;
                    }
                    if (strIndex >= 0)
                    {
                        break;
                    }
                }
                Console.WriteLine(Environment.NewLine + Environment.NewLine + "Is this your account?"
                                  + Environment.NewLine + "First Name: " + bankAccount.firstNameProps + Environment.NewLine
                                  + "Last Name: " + bankAccount.lastNameProps + Environment.NewLine + "[1] - Yes" + Environment.NewLine
                                  + "[2] - No");
                yesnocheck = Console.ReadLine();
            }
        }
Пример #54
0
        static void Main(string[] args)
        {
            foreach (var item in System.IO.Directory.GetFiles("./", "*.cs"))
            {
                using (var sw = new System.IO.StreamWriter(item + ".txt"))
                {
                    string sourceCode = System.IO.File.ReadAllText(item);
                    var    lexi       = new CSharpShadingLanguage.Compiler.LexicalAnalyzerCSSLCompiler(sourceCode);
                    var    tokenList  = lexi.Analyze();
                    foreach (var token in tokenList)
                    {
                        //Console.WriteLine(token);
                        sw.WriteLine(token);

                        if (token.TokenType == EnumTokenTypeCSSLCompiler.unknown)
                        {
                            Console.ReadKey(true);
                        }
                    }
                    // find public override void main() { }
                    List <Token <EnumTokenTypeCSSLCompiler> > target = new List <Token <EnumTokenTypeCSSLCompiler> >();
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.identifier, Detail = "public",
                    });
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.identifier, Detail = "override",
                    });
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.identifier, Detail = "void",
                    });
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.identifier, Detail = "main",
                    });
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.token_LeftParentheses_, Detail = "(",
                    });
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.token_RightParentheses_, Detail = ")",
                    });
                    target.Add(new Token <EnumTokenTypeCSSLCompiler>()
                    {
                        TokenType = EnumTokenTypeCSSLCompiler.token_LeftBrace_, Detail = "{",
                    });
                    int index = tokenList.KMP(target, 0, new TokenComparer());
                    if (index < 0)
                    {
                        throw new Exception();
                    }
                    int rightBraceIndex = index + 7; int leftBraceCount = 1;
                    for (; rightBraceIndex < tokenList.Count; rightBraceIndex++)
                    {
                        if (tokenList[rightBraceIndex].TokenType == EnumTokenTypeCSSLCompiler.token_LeftBrace_)
                        {
                            leftBraceCount++;
                        }
                        else if (tokenList[rightBraceIndex].TokenType == EnumTokenTypeCSSLCompiler.token_RightBrace_)
                        {
                            leftBraceCount--;
                            if (leftBraceCount == 0)
                            {
                                break;
                            }
                        }
                    }
                    Console.WriteLine("right brace '}}' for public override void main() {{ is {0}", tokenList[rightBraceIndex]);
                }
            }
        }
Пример #55
0
        public static void Vykdom(int zodis1, int zodis2)
        {
            switch (a)
            {
            case 1:
                Console.WriteLine("Vykdoma komanda GIV");
                if (zodis1 > -1)
                {
                    RealiMasina.memory[zodis1] = zodis2;                     //Cia GIV i rasoma i memory reiksme
                }
                else
                {
                    Console.WriteLine("Priskiriama registro reiksme");                     //Cia GIV i rasoma i registra reiksme (dabar neveikia, sutvarkyk)
                }
                break;

            case 2:
                Console.WriteLine("Vykdoma komanda ADD");
                RealiMasina.memory[zodis1] = RealiMasina.memory[zodis1] + RealiMasina.memory[zodis2];
                break;

            case 3:
                Console.WriteLine("Vykdoma komanda SUB");
                RealiMasina.memory[zodis1] = RealiMasina.memory[zodis1] - RealiMasina.memory[zodis2];
                break;

            case 4:
                Console.WriteLine("Vykdoma komanda MUL");
                RealiMasina.memory[zodis1] = RealiMasina.memory[zodis1] * RealiMasina.memory[zodis2];
                break;

            case 5:
                Console.WriteLine("Vykdoma komanda DIV");
                if (zodis2 == 0)
                {
                    RealiMasina.PI = 1;
                }
                else
                {
                    RealiMasina.memory[zodis1] = RealiMasina.memory[zodis1] / RealiMasina.memory[zodis2];
                }
                break;

            case 6:
                Console.WriteLine("Vykdoma komanda CPM");
                if (RealiMasina.R1 == 0)
                {
                    RealiMasina.C = 1;
                }
                if (RealiMasina.R1 < 0)
                {
                    RealiMasina.C = 0;
                }
                if (RealiMasina.R1 > 0)
                {
                    RealiMasina.C = 2;
                }
                break;

            case 7:
                Console.WriteLine("Vykdoma komanda AND");
                char[] bin1   = Convert.ToString(zodis1, 2).PadLeft(4, '0').ToCharArray();
                char[] bin2   = Convert.ToString(zodis2, 2).PadLeft(4, '0').ToCharArray();
                string result = "";
                for (int i = 0; i < bin1.Length; i++)
                {
                    if ((bin1 [i] == '1') && (bin2 [i] == '1'))
                    {
                        result = result + '1';
                    }
                    else
                    {
                        result = result + '0';
                    }
                }
                int resultint = Convert.ToInt32(result, 2);
                RealiMasina.memory [zodis1] = resultint;
                break;

            case 8:
                Console.WriteLine("Vykdoma komanda OR");
                char[] bin1   = Convert.ToString(zodis1, 2).PadLeft(4, '0').ToCharArray();
                char[] bin2   = Convert.ToString(zodis2, 2).PadLeft(4, '0').ToCharArray();
                string result = "";
                for (int i = 0; i < bin1.Length; i++)
                {
                    if ((bin1 [i] == '0') && (bin2 [i] == '0'))
                    {
                        result = result + '0';
                    }
                    else
                    {
                        result = result + '1';
                    }
                }
                int resultint = Convert.ToInt32(result, 2);
                RealiMasina.memory [zodis1] = resultint;
                break;

            case 9:
                Console.WriteLine("Vykdoma komanda XOR");
                char[] bin1   = Convert.ToString(zodis1, 2).PadLeft(4, '0').ToCharArray();
                char[] bin2   = Convert.ToString(zodis2, 2).PadLeft(4, '0').ToCharArray();
                string result = "";
                for (int i = 0; i < bin1.Length; i++)
                {
                    if ((bin1 [i] + bin2[i]) == '1')
                    {
                        result = result + '1';
                    }
                    else
                    {
                        result = result + '0';
                    }
                }
                int resultint = Convert.ToInt32(result, 2);
                RealiMasina.memory [zodis1] = resultint;
                break;

            case 10:
                Console.WriteLine("Vykdoma komanda INV");
                char[] bin    = Convert.ToString(zodis1, 2).PadLeft(4, '0').ToCharArray();
                string result = "";
                for (int i = 0; i < bin.Length; i++)
                {
                    if (bin[i] == '0')
                    {
                        result = result + '1';
                    }
                    else
                    {
                        result = result + '0';
                    }
                }
                int resultint = Convert.ToInt32(result, 2);
                RealiMasina.memory [zodis1] = resultint;
                break;

            case 11:
                Console.WriteLine("Vykdoma komanda JMP");
                break;

            case 12:
                Console.WriteLine("Vykdoma komanda JL");
                break;

            case 13:
                Console.WriteLine("Vykdoma komanda JE");
                break;

            case 14:
                Console.WriteLine("Vykdoma komanda JNE");
                break;

            case 15:
                Console.WriteLine("Vykdoma komanda JG");
                break;

            case 16:
                Console.WriteLine("Vykdoma komanda GD");
                break;

            case 17:
                Console.WriteLine("Vykdoma komanda PD");
                break;

            case 18:
                Console.WriteLine("Vykdoma komanda GDI");
                break;

            case 19:
                Console.WriteLine("Vykdoma komanda PDI");
                break;

            case 100:               //Show Registers
                Console.WriteLine("Vykdoma komanda Show Reg");
                string allRegisters =
                    "R1:" + RealiMasina.R1 + " R2:" + RealiMasina.R2 + " PTR:" + RealiMasina.PTR + " SI:" + RealiMasina.SI + " PI:" + RealiMasina.PI +
                    " IOI:" + RealiMasina.IOI + " C:" + RealiMasina.C + " CH1:" + RealiMasina.CH1 + " CH2:" + RealiMasina.CH2 + " CH3:" + RealiMasina.CH3 +
                    " CH4:" + RealiMasina.CH4 + " MODE:" + RealiMasina.MODE + " TI:" + RealiMasina.TI + " CS:" + RealiMasina.CS + " DS:" + RealiMasina.DS +
                    " IC:" + RealiMasina.IC;
                System.IO.File.WriteAllText(@"C:\Users\eivgai\Documents\Visual Studio 2015\Projects\OS\RegOut.txt", allRegisters);     //Cia pasikeisk, kad pas tave butu
                break;

            case 101:               //Show Memory
                Console.WriteLine("Vykdoma komanda Show Memory");
                using (System.IO.StreamWriter file =
                           new System.IO.StreamWriter(@"C:\Users\eivgai\Documents\Visual Studio 2015\Projects\OS\MemOut.txt"))              //Cia pasikeisk, kad pas tave butu
                {
                    foreach (int line in RealiMasina.memory)
                    {
                        file.WriteLine(line);
                    }
                }
                break;

            default:
                Console.WriteLine("Įvesta netinkama komanda");
                break;
            }
            RealiMasina.TI--;
        }
Пример #56
0
        private void startRecordingButton_Click(object sender, RoutedEventArgs e)
        {
            lock (recording_lock)
            {
                RecordingButton.IsEnabled = false;
                CompleteButton.IsEnabled  = false;
                PauseButton.IsEnabled     = false;

                recording_objects = new ConcurrentQueue <Tuple <RawImage, bool, List <double> > >();

                recording = true;

                new Thread(() =>
                {
                    Thread.CurrentThread.IsBackground = true;

                    // Start the recording thread
                    //rec_thread = new Thread(RecordingLoop);
                    //rec_thread.Start();

                    double d = seconds_to_record * 1000;

                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();

                    while (d > 1000)
                    {
                        Dispatcher.Invoke(DispatcherPriority.Render, new TimeSpan(0, 0, 0, 0, 200), (Action)(() =>
                        {
                            RecordingButton.Content = ((int)(d / 1000)).ToString() + " seconds remaining";
                        }));

                        System.Threading.Thread.Sleep(1000);

                        d = seconds_to_record * 1000 - stopWatch.ElapsedMilliseconds;
                    }

                    if (d > 0)
                    {
                        System.Threading.Thread.Sleep((int)(d));
                    }

                    recording = false;

                    Dispatcher.Invoke(DispatcherPriority.Render, new TimeSpan(0, 0, 0, 0, 200), (Action)(() =>
                    {
                        RecordingButton.Content = "0 seconds remaining";
                    }));

                    Dispatcher.Invoke(() =>
                    {
                        lock (recording_lock)
                        {
                            // Wait for the recording thread to finish before enabling
                            rec_thread.Join();

                            string messageBoxText   = "Was the tracking successful?";
                            string caption          = "Success of tracking";
                            MessageBoxButton button = MessageBoxButton.YesNo;
                            MessageBoxImage icon    = MessageBoxImage.Question;
                            MessageBoxResult result = MessageBox.Show(messageBoxText, caption, button, icon);

                            if (recording_success_file == null)
                            {
                                recording_success_file = new System.IO.StreamWriter(output_root + "/recording_success.txt", true);
                            }

                            if (result == MessageBoxResult.Yes)
                            {
                                recording_success_file.WriteLine('1');
                            }
                            else
                            {
                                recording_success_file.WriteLine('0');
                            }
                            recording_success_file.Flush();

                            trial_id++;
                            RecordingButton.Content   = "Record trial: " + trial_id;
                            RecordingButton.IsEnabled = true;
                            CompleteButton.IsEnabled  = true;
                            PauseButton.IsEnabled     = true;
                        }
                    });
                }).Start();
            }
        }
Пример #57
0
        private void WriteString(System.IO.StreamWriter statsFile, string item)
        {
            string tmpItem = ((string)item).Replace('"', '\'');

            statsFile.Write("\"" + tmpItem + "\"");
        }
Пример #58
0
        private bool WriteHeaderFile(string outputPrefix)
        {
            DoStatus("Writing header file ...");

            System.IO.StreamWriter sw = null;

            string className = outputPrefix.Split(new char[2] {
                '/', '\\'
            }).Last();
            string compileTime = System.DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'", System.Globalization.CultureInfo.InvariantCulture);

            try
            {
                sw = new System.IO.StreamWriter(outputPrefix + ".h");

                sw.WriteLine("#pragma once");
                sw.WriteLine();
                sw.WriteLine("////////////////////////////////////////////////");
                sw.WriteLine("// AUTOGENERATED FILE, CHANGES WILL GET LOST! //");
                sw.WriteLine("////////////////////////////////////////////////");
                sw.WriteLine();
                sw.WriteLine("// Copyright (c) advancedfx.org");
                sw.WriteLine("//");
                sw.WriteLine("// Last changes:");
                sw.WriteLine("// " + compileTime + " ShaderBuilder (auto)");
                sw.WriteLine("//");
                sw.WriteLine("// First changes:");
                sw.WriteLine("// " + compileTime + " ShaderBuilder (auto)");
                sw.WriteLine();
                sw.WriteLine("class ShaderCombo_" + className);
                sw.WriteLine("{");

                sw.WriteLine("public:");

                foreach (var combo in m_AfxCombos)
                {
                    sw.WriteLine("\tenum " + combo.Name + "_e");
                    sw.WriteLine("\t{");

                    bool first = true;
                    for (int i = combo.Min; i <= combo.Max; ++i)
                    {
                        sw.WriteLine("\t\t" + (first ? "" : ", ") + combo.Name + "_" + i + " = " + i);
                        first = false;
                    }

                    sw.WriteLine("\t};");
                }
                foreach (var combo in m_DynamicCombos)
                {
                    sw.WriteLine("\tenum " + combo.Name + "_e");
                    sw.WriteLine("\t{");

                    bool first = true;
                    for (int i = combo.Min; i <= combo.Max; ++i)
                    {
                        sw.WriteLine("\t\t" + (first ? "" : ", ") + combo.Name + "_" + i + " = " + i);
                        first = false;
                    }

                    sw.WriteLine("\t};");
                }
                foreach (var combo in m_StaticCombos)
                {
                    sw.WriteLine("\tenum " + combo.Name + "_e");
                    sw.WriteLine("\t{");

                    bool first = true;
                    for (int i = combo.Min; i <= combo.Max; ++i)
                    {
                        sw.WriteLine("\t\t" + (first ? "" : ", ") + combo.Name + "_" + i + " = " + i);
                        first = false;
                    }

                    sw.WriteLine("\t};");
                }

                {
                    sw.WriteLine("\tstatic int GetCombo(");

                    bool first = true;

                    foreach (var combo in m_AfxCombos)
                    {
                        sw.WriteLine("\t\t" + (first ? "" : ", ") + combo.Name + "_e a_" + combo.Name);
                        first = false;
                    }
                    foreach (var combo in m_DynamicCombos)
                    {
                        sw.WriteLine("\t\t" + (first ? "" : ", ") + combo.Name + "_e a_" + combo.Name);
                        first = false;
                    }
                    foreach (var combo in m_StaticCombos)
                    {
                        sw.WriteLine("\t\t" + (first ? "" : ", ") + combo.Name + "_e a_" + combo.Name);
                        first = false;
                    }
                    sw.WriteLine("\t\t)");

                    sw.WriteLine("\t{");

                    int scale = 1;

                    sw.WriteLine("\t\treturn 0");
                    foreach (var combo in m_AfxCombos)
                    {
                        sw.WriteLine("\t\t\t+(a_" + combo.Name + " - " + combo.Min + ") * " + scale);
                        scale *= combo.Max - combo.Min + 1;
                    }
                    foreach (var combo in m_DynamicCombos)
                    {
                        sw.WriteLine("\t\t\t+(a_" + combo.Name + " - " + combo.Min + ") * " + scale);
                        scale *= combo.Max - combo.Min + 1;
                    }
                    foreach (var combo in m_StaticCombos)
                    {
                        sw.WriteLine("\t\t\t+(a_" + combo.Name + " - " + combo.Min + ") * " + scale);
                        scale *= combo.Max - combo.Min + 1;
                    }
                    sw.WriteLine("\t\t\t;");

                    sw.WriteLine("\t}");
                }

                sw.WriteLine("};");

                sw.Close();
            }
            catch (System.IO.IOException e)
            {
                DoError("Error writing header file: " + e);
                if (null != sw)
                {
                    sw.Close();
                }

                return(false);
            }

            return(true);
        }
Пример #59
0
 /// <summary>
 /// Writes sVal to sFile, works with norwegian letters ae oo aa
 /// </summary>
 /// <param name="sFile"></param>
 /// <param name="sVal"></param>
 public void FileWrite(string sFile, string sVal)
 {
     System.IO.FileStream   fs = new System.IO.FileStream(sFile, System.IO.FileMode.Create);
     System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, Encoding.GetEncoding("iso-8859-1"));
     sw.Write(sVal); sw.Close(); sw.Dispose();
 }
Пример #60
0
        public void Save()
        {
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter(this.m_filename, false, Encoding.Unicode))
            {
                // header
                writer.Write("Name");
                if (this.m_locales != null)
                {
                    foreach (string locale in this.m_locales)
                    {
                        writer.Write("\tName(");
                        writer.Write(locale);
                        writer.Write(")\tDescription(");
                        writer.Write(locale);
                        writer.Write(")");
                    }
                }
                writer.WriteLine();

                // blank line separates row data
                writer.WriteLine();

                // split into two lists alphabetically for easier translation
                SortedList <string, DocObject> sortlistEntity = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistType   = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistPset   = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistQset   = new SortedList <string, DocObject>();
                SortedList <string, DocObject> sortlistEnum   = new SortedList <string, DocObject>();

                // rows
                foreach (DocSection docSection in this.m_project.Sections)
                {
                    foreach (DocSchema docSchema in docSection.Schemas)
                    {
                        foreach (DocEntity docEntity in docSchema.Entities) // have attributes
                        {
                            sortlistEntity.Add(docEntity.Name, docEntity);
                        }

                        foreach (DocType docEntity in docSchema.Types) //docEnumeration docConstant
                        {
                            sortlistType.Add(docEntity.Name, docEntity);
                        }

                        foreach (DocPropertyEnumeration docPE in docSchema.PropertyEnums) //docPropertyConstant
                        {
                            sortlistEnum.Add(docPE.Name, docPE);
                        }

                        foreach (DocPropertySet docPset in docSchema.PropertySets) //Property
                        {
                            sortlistPset.Add(docPset.Name, docPset);
                        }

                        foreach (DocQuantitySet docQset in docSchema.QuantitySets) //Quantities
                        {
                            sortlistQset.Add(docQset.Name, docQset);
                        }
                    }
                }

                WriteList(writer, sortlistEntity);
                WriteList(writer, sortlistType);
                WriteList(writer, sortlistPset);
                WriteList(writer, sortlistEnum);
                WriteList(writer, sortlistQset);
            }
        }