Advertisement
ncosentino

IronPython: WinForms Introduction - MainForm.cs

Apr 6th, 2014
1,380
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.20 KB | None | 0 0
  1. /**
  2.  * Blog Post:
  3.  * http://devleader.ca/2014/04/07/ironpython-quick-winforms-introduction
  4.  *
  5.  * MainForm.Designer.cs: http://pastebin.com/chaBwVTY
  6.  * MainForm.cs: http://pastebin.com/29w3Bw6C
  7.  */
  8. using System;
  9. using System.Collections.Generic;
  10. using System.ComponentModel;
  11. using System.Data;
  12. using System.Drawing;
  13. using System.Text;
  14. using System.Windows.Forms;
  15. using System.IO;
  16.  
  17. using IronPython.Hosting;
  18.  
  19. namespace DevLeader.IronPython.WinForms
  20. {
  21.     /// <summary>
  22.     /// A form that allows users to execute Python scripts from a file or from
  23.     /// entering them manually on the form.
  24.     /// </summary>
  25.     public partial class MainForm : Form
  26.     {
  27.         #region Constructors
  28.         /// <summary>
  29.         /// Initializes a new instance of the <see cref="MainForm"/> class.
  30.         /// </summary>
  31.         public MainForm()
  32.         {
  33.             InitializeComponent();
  34.         }
  35.         #endregion
  36.  
  37.         #region Internal Members
  38.         /// <summary>
  39.         /// Raises the <see cref="E:System.Windows.Forms.Form.Load" /> event.
  40.         /// </summary>
  41.         /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
  42.         protected override void OnLoad(EventArgs e)
  43.         {
  44.             base.OnLoad(e);
  45.             radInputFromFile.Checked = true;
  46.         }
  47.  
  48.         private void ExecuteScript(string scriptBody, Stream outputStream)
  49.         {
  50.             var py = Python.CreateEngine();
  51.             py.Runtime.IO.SetOutput(outputStream, Encoding.GetEncoding(1252));
  52.  
  53.             try
  54.             {
  55.                 py.Execute(scriptBody);                
  56.             }
  57.             catch (Exception ex)
  58.             {
  59.                 using (var writer = new StreamWriter(outputStream))
  60.                 {
  61.                     writer.WriteLine(
  62.                         "Oops! There was an exception while running the script:\r\n" +
  63.                         ex.Message + "\r\n\r\n" + ex.StackTrace);
  64.                 }
  65.             }
  66.         }
  67.         #endregion
  68.  
  69.         #region Event Handlers
  70.         private void RadInputFromFile_CheckedChanged(object sender, EventArgs e)
  71.         {
  72.             bool optionEnabled = ((RadioButton)sender).Checked;
  73.             txtInputScriptPath.Enabled = optionEnabled;
  74.             cmdBrowseScript.Enabled = optionEnabled;
  75.         }
  76.  
  77.         private void RadInputFromForm_CheckedChanged(object sender, EventArgs e)
  78.         {
  79.             bool optionEnabled = ((RadioButton)sender).Checked;
  80.             txtInputScript.Enabled = optionEnabled;
  81.         }
  82.  
  83.         private void CmdRunScript_Click(object sender, EventArgs e)
  84.         {
  85.             string scriptBody;
  86.             if (radInputFromForm.Checked)
  87.             {
  88.                 scriptBody = txtInputScript.Text;
  89.             }
  90.             else if (radInputFromFile.Checked)
  91.             {
  92.                 var inputFilePath = txtInputScriptPath.Text;
  93.                 if (!File.Exists(inputFilePath))
  94.                 {
  95.                     MessageBox.Show(
  96.                         "The file '" + inputFilePath + "' does not exist.",
  97.                         Application.ProductName);
  98.                     txtInputScriptPath.Focus();
  99.                     txtInputScriptPath.SelectAll();
  100.                     return;
  101.                 }
  102.  
  103.                 try
  104.                 {
  105.                     using (var reader = new StreamReader(inputFilePath))
  106.                     {
  107.                         scriptBody = reader.ReadToEnd();
  108.                     }
  109.                 }
  110.                 catch (IOException ex)
  111.                 {
  112.                     MessageBox.Show(
  113.                         "An exception was caught while opening '" + inputFilePath + "':\r\n\r\n" +
  114.                         ex.Message + "\r\n\r\n" + ex.StackTrace,
  115.                         Application.ProductName);
  116.                     return;
  117.                 }
  118.             }
  119.             else
  120.             {
  121.                 throw new NotImplementedException("The option for executing scripts has not been implemented.");
  122.             }
  123.  
  124.             // run our script and print the output
  125.             txtOutput.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":\r\n";
  126.             using (var outStream = new ScriptOutputStream(txtOutput))
  127.             {
  128.                 ExecuteScript(scriptBody, outStream);
  129.             }
  130.  
  131.             txtOutput.Text += "\r\n";
  132.  
  133.             // scroll to the end of the output
  134.             txtOutput.SelectionLength = 0;
  135.             txtOutput.SelectionStart = txtOutput.Text.Length - 1;
  136.             txtOutput.ScrollToCaret();
  137.         }
  138.  
  139.         private void CmdClearOutput_Click(object sender, EventArgs e)
  140.         {
  141.             txtOutput.Clear();
  142.         }
  143.  
  144.         private void CmdBrowseScript_Click(object sender, EventArgs e)
  145.         {
  146.             using (var ofd = new OpenFileDialog()
  147.             {
  148.                 Title = "Select a Python script file.",
  149.                 Multiselect = false,
  150.                 Filter = "Python Script|*.py|All Files|*.*"
  151.             })
  152.             {
  153.                 if (ofd.ShowDialog() != DialogResult.OK)
  154.                 {
  155.                     return;
  156.                 }
  157.  
  158.                 txtInputScriptPath.Text = ofd.FileName;
  159.                 txtInputScriptPath.SelectAll();
  160.             }
  161.         }
  162.         #endregion
  163.  
  164.         #region Classes
  165.         private class ScriptOutputStream : Stream
  166.         {
  167.             #region Fields
  168.             private readonly TextBox _control;
  169.             #endregion
  170.  
  171.             #region Constructors
  172.             public ScriptOutputStream(TextBox control)
  173.             {
  174.                 _control = control;
  175.             }
  176.             #endregion
  177.  
  178.             #region Properties
  179.             public override bool CanRead
  180.             {
  181.                 get { return false; }
  182.             }
  183.  
  184.             public override bool CanSeek
  185.             {
  186.                 get { return false; }
  187.             }
  188.  
  189.             public override bool CanWrite
  190.             {
  191.                 get { return true; }
  192.             }
  193.  
  194.             public override long Length
  195.             {
  196.                 get { throw new NotImplementedException(); }
  197.             }
  198.  
  199.             public override long Position
  200.             {
  201.                 get { throw new NotImplementedException(); }
  202.                 set { throw new NotImplementedException(); }
  203.             }
  204.             #endregion
  205.  
  206.             #region Exposed Members
  207.             public override void Flush()
  208.             {
  209.             }
  210.  
  211.             public override int Read(byte[] buffer, int offset, int count)
  212.             {
  213.                 throw new NotImplementedException();
  214.             }
  215.  
  216.             public override long Seek(long offset, SeekOrigin origin)
  217.             {
  218.                 throw new NotImplementedException();
  219.             }
  220.  
  221.             public override void SetLength(long value)
  222.             {
  223.                 throw new NotImplementedException();
  224.             }
  225.  
  226.             public override void Write(byte[] buffer, int offset, int count)
  227.             {
  228.                 _control.Text += Encoding.GetEncoding(1252).GetString(buffer, offset, count);
  229.             }
  230.             #endregion
  231.         }
  232.         #endregion
  233.     }
  234. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement