Click here to Skip to main content
15,891,976 members
Articles / Programming Languages / C#

Universal Framework for Science and Engineering - Part 6: Determination of Orbits of Artificial Satellites

Rate me:
Please Sign up or sign in to vote.
4.88/5 (28 votes)
8 Jul 2011CPOL19 min read 82.5K   6.6K   82  
An article on framework applications to determine the orbits of artificial satellites
��using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters;

using System.Runtime.Serialization.Formatters.Binary;

using System.Xml;

using System.Xml.Xsl;

using System.Resources;

using System.Collections;

using System.Reflection;

using System.Diagnostics;









using DiagramUI;

using DiagramUI.Operations;

using DiagramUI.Utils;

using Diagram.UI.Factory;

using DiagramUI.Factory;

using DiagramUI.Interfaces;

using Diagram.UI.Interfaces;



using DiagramUI.Forms;



using DataPerformer;



using DataWarehouse;

using DataWarehouse.Interfaces;



using ResourceService;



using DockableControls;

using DockableControls.Forms;



using BasicEngineeringUIFactory;

using BasicEngineeringUIFactory.Interfaces;



using ToolBox;



using DataWarehouse.Forms;



using WindowsExtensions;

using DataPerformer.Interfaces;

using DataWarehouse.Advanced.Forms;









namespace BasicEngineeringUIFactory.Advanced.Forms

{

    public partial class FormMain : Form, IBlob, IErrorHandler, IProcess, IStartStop

    {



        #region Fields

        private PanelDesktop active;

        ToolsDiagram tools;

        EngineeringUIFactory factory;

        DatabaseInterface data;

       // private string text;

        private FormContainerDesigner formContainer;



        private FormDatabaseTree formData;

        FormTools formTools;



        string fn = "";



        FormDockableTree formTree;



        private DockManager dockManager;



        private FormDesktop desktop;



        private IApplicationCreator creator;





        Panel docPanel;





        private Dictionary<string, object>[] resources;



        private bool isChecked = true;





 



        #endregion



        #region Ctor



        private FormMain()

        {

            InitializeComponent();

        }



        internal FormMain(IApplicationCreator creator)

            : this()

        {

            this.creator = creator;

            if (creator.DatabaseCoordinator == null)

            {

                databaseToolStripMenuItem.Visible = false;

                savetodatabaseToolStripMenuItem.Visible = false;

                loadfromdatabaseToolStripMenuItem.Visible = false;

            }

            if (creator.Log != null)

            {

                toolStripButtonTest.Visible = true;

                Action close = () => { creator.Log.Flush(); creator.Log.Close(); };

                Application.ThreadExit += (object o, EventArgs e) => { close(); };

 

            }

            Text = creator.Text;

            // creator.

            creator.LoadResources();

            Dictionary<string, object>[] standardResources = Common.UI.Resources.Utils.ControlUtilites.Resources;

            if (DiagramUI.Utils.ControlUtilites.Resources == null)

            {

                DiagramUI.Utils.ControlUtilites.Resources =

                    standardResources;

            }

            resources = Localizator.CreateResources(new Dictionary<string, object>[][]

            {

                creator.Resources,

                Common.Engineering.Localization.Utils.ControlUtilites.Resources,

                standardResources

            }

            );

            this.Icon = creator.Icon;

            filename = creator.Filename;

            if (filename == null)

            {

                filename = "";

            }

            this.LoadControlResources(resources);

            toolStripComboBoxCheckDetails.SelectedIndex = StaticExtension.CheckLevel;

            formTree = new FormDockableTree();

            formTree.OnHide += delegate()

            {

                StaticExtension.ShowTree = false;

                StaticExtension.Save();

            };

            SetSettings();

        }



 

       /* public FormMain(PureDesktopPeer edit)

            : this()

        {

            this.edit = edit;

            prepare();

        }*/



        #endregion



        #region IErrorHandler Members



        public void ShowError(Exception e)

        {

            ControlUtilites.ShowError(this, e, resources);

        }



        public void ShowMessage(string message)

        {

            MessageBox.Show(this, message);

        }



        #endregion



        #region IProcess Members



        void IProcess.Start()

        {

            try

            {

                double[] d = ControlDouble;

                int[] i = ControlInt;

                IStartStop ss = this;

                ss.Action(null, true);

                toolStripButtonStop.Enabled = true;

                creator.Start(d[0], i[0], i[1], d[1], i[2], active);



            }

            catch (Exception ex)

            {

                ex.Log();

                ShowError(ex);

            }

        }



        /// <summary>

        /// Pauses process

        /// </summary>

        void IProcess.Pause()

        {

        }



        /// <summary>

        /// Terminates process

        /// </summary>

        void IProcess.Terminate()

        {

            factory.StopWorker();

        }



        /// <summary>

        /// Shows status of process

        /// </summary>

        /// <param name="status">Status</param>

        void IProcess.ShowStatus(double status)

        {

        }



        /// <summary>

        /// Time of start

        /// </summary>

        double IProcess.StartTime

        {

            get

            {

                return 0;

            }

            set

            {

            }

        }



        /// <summary>

        /// Step

        /// </summary>

        double IProcess.Step

        {

            get

            {

                return 0;

            }

            set

            {

            }

        }



        /// <summary>

        /// Number of steps

        /// </summary>

        int IProcess.Count

        {

            get

            {

                return 0;

            }

            set

            {

            }

        }





        #endregion



        #region IBlob Members



        byte[] IBlob.Bytes

        {

            get

            {

                MemoryStream stream = new MemoryStream();

                SaveAll(stream);

                return stream.GetBuffer();

            }

            set

            {

                MemoryStream stream = new MemoryStream(value);

                LoadFromStream(stream, ".cfa");

            }

        }



        string IBlob.Extention

        {

            get { return "cfa"; }

            set { }

        }



        #endregion



        #region IDesktopPostLoad Members



        void PostLoad(IDesktop desktop)

        {

            update();

            PanelDesktop pd = desktop as PanelDesktop;

            ICollection<object> coll = active.AllComponents;

            foreach (object o in coll)

            {

                if (o is IStartStopConsumer)

                {

                    IStartStopConsumer ssc = o as IStartStopConsumer;

                    ssc.StartStop = this;

                }

            }

        }



        #endregion



        #region IStartStop Members



        void IStartStop.Action(object type, bool start)

        {

            if (start)

            {

                this.InvokeIfNeeded(StartPrivate);

            }

            else

            {

                this.InvokeIfNeeded(StopPrivate);

            }

        }



        #endregion



        #region LoadSave



        public bool SaveAll(Stream stream)

        {

            try

            {

                check();

                active.SaveAll(stream);

                isChecked = false;

                return true;

            }

            catch (Exception ex)

            {

                ex.Log();

                isChecked = false;

                this.ShowError(ex, resources);

            }

            return false;

        }



        public bool LoadFromStream(Stream stream, string ext)

        {

            bool b = active.LoadFromStream(stream, PureDesktopPeer.Binders, ext, ".cfa");

            if (!b)

            {

                return false;

            }

             return true;

        }



        private void check()

        {

            if (!isChecked)

            {

                isChecked = true;

                active.Check();

            }

        }



        #endregion



        #region Init



        protected void Prepare()

        {

            factory = creator.Factory as EngineeringUIFactory;

            factory.CancelProcess += () => {this.InvokeIfNeeded(StopAll); };

            creator.ApplicationInitializer.InitializeApplication();

            if (creator.Log != null)

            {

                factory.ErrorHandler = new DiagramUI.ErrorHandlers.TextWriterErrorHandler(creator.Log);

            }

            else

            {

                factory.ErrorHandler = this;

            }

            ResourceService.Resources.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            Environment.CurrentDirectory = ResourceService.Resources.CurrentDirectory + "";

//            tools = new ToolsDiagram(factory);

            CommonOperations.CreateArrowControl(panelToolLeft, tools);

            ButtonWrapper.Add(creator.Buttons, tabControlControls, tools, new Size(25, 25), resources, true);

            ContainerPerformerUI.InitContainers(AppDomain.CurrentDomain.BaseDirectory, tools, tabControlControls,

                resources);



        }



        void StopAll()

        {

            StopEnable();

            IStartStop ss = this;

            ss.Action(null, false);

        }



        private void initAll()

        {

            DataPerformer.StaticExtension.Desktop = active;

            active.PostLoad += PostLoad;

            initTools();

            initContainers();

        }



        private void initTools()

        {

            EditorReceiver.AddEditorDrag(active);

            PictureReceiver.AddImageDrag(active);

        }







        private void initContainers()

        {

            Assembly ass = typeof(FormMain).Assembly;

            string path = Path.GetDirectoryName(ass.Location);

           // ContainerPerformerUI.InitContainers(path, tools, tabControlControls);

        }



        private void createDockMan()

        {

            if (dockManager == null)

            {

                dockManager = new DockManager();

                docPanel = this.panel1;

                //                dockManager.ActiveDocumentChanged += dockManager_ActiveDocumentChanged;

                this.dockManager.ActiveAutoHideContent = null;

                this.dockManager.Dock = System.Windows.Forms.DockStyle.Fill;

                this.dockManager.Location = new System.Drawing.Point(0, 28);

                this.dockManager.Name = "dockManager";

                this.dockManager.Size = new System.Drawing.Size(853, 600);

                this.dockManager.TabIndex = 1;

                docPanel.Controls.Add(dockManager);

                if (StaticExtension.LeftPortion > 0)

                {

                    dockManager.DockLeftPortion = StaticExtension.LeftPortion;

                    dockManager.DockRightPortion = StaticExtension.RightPortion;

                }



            }

        }









        #endregion



        #region Work with files





        private string filename

        {

            get

            {

                return fn;

            }

            set

            {

                fn = value;

                string t = ResourceService.Resources.GetControlResource(creator.Text, resources);

                if (fn == null)

                {

                    Text = t;

                }

                else

                {

                    if (fn.Length > 0)

                    {

                        Text = t + " [" + filename + "]";

                    }

                }

            }

        }



        private void saveas()

        {

            try

            {

                check();

                saveFileDialogScn.InitialDirectory = ResourceService.Resources.CurrentDirectory + "scn";

                if (saveFileDialogScn.ShowDialog() != DialogResult.OK)

                {

                    return;

                }

                save(saveFileDialogScn.FileName);

            }

            catch (Exception ex)

            {

                ex.Log();

                ControlUtilites.ShowError(this, ex, resources);

            }

        }



        private void save(string filename)

        {

            try

            {

                /* Dictionary<string, object> d = PureDesktop.GetAllAliases(active);

                 MemoryStream ms = new MemoryStream();

                 PureDesktopPeer.SaveAllAliases(active, ms);

                 ms.Position = 0;

                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =

                     new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                Dictionary<string, object> dd = bf.Deserialize(ms) as Dictionary<string, object>;

                 double a = 0;

                 foreach (string s in d.Keys)

                 {

                     dd[s] = a;

                 }

                 PureDesktop.SetAliases(active, dd);

                 Dictionary<string, object> ddd = PureDesktop.GetAllAliases(active);*/

                check();

                Stream stream = File.Open(filename, FileMode.Create);

                SaveAll(stream);

                stream.Close();

                this.filename = filename;

            }

            catch (Exception ex)

            {

                ex.Log();

                ControlUtilites.ShowError(this, ex, resources);

            }

        }



        private void save()

        {

            if (filename == null)

            {

                saveas();

                return;

            }

            if (filename.Length == 0)

            {

                saveas();

                return;

            }

           // check();

            save(filename);

        }





        void LoadContainer(Stream stream)

        {

        }



        void Open()

        {

            //openFileDialogScn.InitialDirectory = ResourceService.Resources.CurrentDirectory + "scn";

            if (openFileDialogScn.ShowDialog(this) != DialogResult.OK)

            {

                return;

            }

            log(openFileDialogScn.FileName);

            string ext = Path.GetExtension(openFileDialogScn.FileName);

            Stream stream = File.OpenRead(openFileDialogScn.FileName);

         /*   if (ext.Equals("*.cont"))

            {

                LoadContainer(stream);

                return;

            }*/

            LoadFromStream(stream, ext);

            stream.Close();

            if (ext.ToLower().Equals(creator.Ext))

            {

                filename = openFileDialogScn.FileName + "";

            }

            else

            {

                filename = "";

            }

        }





        void log(string filename)

        {

            return;

          /*  string dir = AppDomain.CurrentDomain.BaseDirectory;

            if (dir[dir.Length - 1] != Path.DirectorySeparatorChar)

            {

                dir += Path.DirectorySeparatorChar;

            }

            StreamWriter wr = new StreamWriter(dir + "log.log", true, Encoding.UTF8);

            wr.WriteLine(filename);

            wr.WriteLine(DateTime.Now + "");

            wr.WriteLine("+++++++++++++++");

            Stream stream = File.OpenRead(filename);

            byte[] b = new byte[stream.Length];

            try

            {

                List<Exception> l = PureDesktopPeer.Check(b);

                if (l != null)

                {

                    foreach (Exception e in l)

                    {

                        wr.WriteLine(e.Message);

                        wr.WriteLine("------------");

                        wr.WriteLine(e.StackTrace);

                        wr.WriteLine("============");

                    }

                }

            }

            catch (Exception ex)

            {

                wr.WriteLine(ex.Message);

                wr.WriteLine("------------");

                wr.WriteLine(ex.StackTrace);

                wr.WriteLine("============");

            }

            wr.Flush();

            wr.Close();

            stream.Close();*/

        }





        #endregion



        #region Relicts



        #region Tests



        void testPerf()

        {

            /*   int n = 100;

               PureDesktopPeer d = new PureDesktopPeer();

               Stream stream = File.OpenRead(AppDomain.CurrentDomain.BaseDirectory +

                   "0.cfa");

               bool b = d.Load(stream, null);

               stream.Close();

               BitmapConsumer.IBitmapConsumer cons =

                   PureDesktop.GetAssociatedObject<BitmapConsumer.IBitmapConsumer>(d, "Picture map");

               StreamWriter wr = new StreamWriter("0.txt", false);

               DateTime t0 = DateTime.Now;

               wr.WriteLine(t0.ToLongTimeString());

               for (int i = 0; i < n; i++)

               {

                   cons.Process();

               }

               DateTime t1 = DateTime.Now;

               wr.WriteLine(t1.ToLongTimeString());

               TimeSpan dt = t1 - t0;

               double s = (60 * (double)dt.Minutes + (double)dt.Seconds + (double)dt.Milliseconds / 1000) / n;

               wr.WriteLine(s);

               wr.Close();*/

        }





 

        #endregion



        #region Sandcastle



        void setEnvProps(XmlDocument doc)

        {

            XmlNodeList l = doc.GetElementsByTagName("property");

            foreach (XmlElement e in l)

            {

                string name = e.Attributes["name"].Value;

                string value = e.Attributes["value"].Value;

                Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.User);

            }

        }



        string systemReplace(string str)

        {

            string s = str;

            while (true)

            {

                if (!s.Contains("$"))

                {

                    break;

                }

                int n = s.IndexOf('$');

                IDictionary d = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User);

                foreach (object o in d.Keys)

                {

                    string ss = "${" + o + "}";

                    if (s.Contains(ss))

                    {

                        s = s.Replace(ss, d[o] + "");

                    }

                }

            }

            return s; ;

        }



        void copy(XmlDocument doc)

        {

            XmlNodeList l = doc.GetElementsByTagName("copy");

            foreach (XmlElement e in l)

            {

                copy(e);

            }

        }



        void copy(XmlElement e)

        {

            string inFile = systemReplace(e.Attributes["file"].Value);

            string outFile = systemReplace(e.Attributes["tofile"].Value);

            StreamReader r = new StreamReader(inFile);

            StreamWriter w = new StreamWriter(outFile);

            XmlNodeList l = e.GetElementsByTagName("replacestring");

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

            foreach (XmlElement el in l)

            {

                d[el.Attributes["from"].Value] = el.Attributes["to"].Value;

            }

            while (true)

            {

                string s = r.ReadLine();

                if (s == null)

                {

                    break;

                }

                foreach (string p in d.Keys)

                {

                    s = s.Replace(p, systemReplace(d[p]));

                }

                w.Write(s);

            }

            r.Close();

            w.Close();

        }





        private void exec(XmlDocument doc)

        {

            XmlNodeList l = doc.GetElementsByTagName("exec");

            exec(l[0] as XmlElement);

        }



        private void xmlToXsl(XmlDocument doc, string workDir)

        {

            string sxsl = "/xsl:";

            string sout = "/out:";



            XmlNodeList l = doc.GetElementsByTagName("arg");

            string[] s = new string[3];

            for (int i = 0; i < 3; i++)

            {

                int k = 0;



                string pref = null;

                XmlElement e = l[i] as XmlElement;

                string str = e.GetAttribute("value");

                if (str.Contains(sxsl))

                {

                    k = 1;

                    pref = sxsl;

                }

                if (str.Contains(sout))

                {

                    pref = sout;

                    k = 2;

                }

                if (pref != null)

                {

                    str = str.Substring(pref.Length);

                }

                str = systemReplace(str);

                if (str[0] == '\"' & str[str.Length - 1] == '\"')

                {

                    str = str.Substring(1, str.Length - 2);

                }

                if (File.Exists(workDir + str))

                {

                    str = workDir + str;

                }

                s[k] = str;

            }



            /*XslTransform xsl = new XslTransform();

            xsl.Load(s[1]);

            xsl.Transform(s[0], s[2]);*/



        }



        private void exec(XmlElement e)

        {

            string program = systemReplace(e.GetAttribute("program"));

            string workingDir = systemReplace(e.GetAttribute("workingdir"));

            string args = "";

            if (e.Attributes["commandline"] != null)

            {

                args = " " + e.GetAttribute("commandline");

            }

            XmlNodeList l = e.GetElementsByTagName("arg");

            foreach (XmlElement el in l)

            {

                string arg = systemReplace(el.GetAttribute("value"));

                args += " " + arg;

            }

            ProcessStartInfo info = new ProcessStartInfo(program, args);

            info.WorkingDirectory = workingDir;

            info.RedirectStandardOutput = true;

            info.RedirectStandardInput = true;

            info.RedirectStandardError = true;

            info.UseShellExecute = false;

            info.CreateNoWindow = true;

            Process p = new Process();

            p.StartInfo = info;

            p.Start();

            p.WaitForExit();

            StreamWriter wr = new StreamWriter("1.txt");

            while (true)

            {

                string s = p.StandardOutput.ReadLine();

                if (s == null)

                {

                    break;

                }

                wr.WriteLine(s);

            }

            wr.Close();

        }



        #endregion





        #endregion



        #region Event Handlers



        #region Open & Close Window



        private void FormMain_Load(object sender, EventArgs e)

        {

            if (creator.Holder != null)

            {

               // e

            }

            ShowDesktop();

            if (StaticExtension.ShowTools)

            {

                ShowTools();

            }

            if (StaticExtension.ShowTree)

            {

                ShowTree();

            }

            if (StaticExtension.ShowDatabase)

            {

                ShowData();

            }

           /* if (StaticExtension.ShowControl)

            {

                ShowControl();

            }*/

            initAll();

            try

            {

                Prepare();

                ByteHolder holder = creator.Holder;

                if (holder != null)

                {

                    IDesktop edit = holder.Desktop;

                    active.Load(edit);

                }

                else

                {



                    char[] cb = StaticExtension.SavedState.ToCharArray();

                    byte[] b = new byte[cb.Length];

                    for (int i = 0; i < b.Length; i++)

                    {

                        b[i] = (byte)cb[i];

                    }

                    MemoryStream ms = null;

                    if (b.Length > 1)

                    {

                        ms = new MemoryStream(b);

                    }

                    Stream stream = ms;

                    if (filename != null)

                    {

                        if (filename.Length != 0)

                        {

                            log(filename);

                            stream = File.OpenRead(filename);

                            // ext = Path.GetExtension(filename);

                        }

                    }

                    if (stream != null)

                    {

                        LoadFromStream(stream, creator.Ext);

                        stream.Close();

                    }

                }

            }

            catch (Exception ex)

            {

                ex.Log();

            }

        }





        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (!SaveSettings())

            {

                e.Cancel = true;

            }

        }



        #endregion



        #region Click Control Events



        private void clearallToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.RemoveAll();

            active.Redraw();

            active.Refresh();



        }



        private void clearselectedToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.RemoveSelected();

            active.Redraw();

            active.Refresh();



        }





        private void deletecommentsToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.DeleteComments();

        }





        private void toolStripButtonOpen_Click(object sender, EventArgs e)

        {

            openToolStripMenuItem_Click(sender, e);

        }





        private void toolStripButtonRefresh_Click(object sender, EventArgs e)

        {

            try

            {

                check();

                active.RefreshObjects();

                //update();



                GC.Collect();

            }

            catch (Exception ex)

            {

                ex.Log();

                ControlUtilites.ShowError(this, ex, resources);

            }

        }



        private void toolStripButtonFont_Click(object sender, EventArgs e)

        {

            try

            {

                TextBox box = ControlPanel.GetActiveTextBox(active);

                if (box == null)

                {

                    return;

                }

                FontDialog dlg = new FontDialog();

                dlg.ShowDialog(this);

                Font font = dlg.Font;

                box.Font = font;

            }

            catch (Exception ex)

            {

                ex.Log();

                ControlUtilites.ShowError(this, ex, resources);

            }



        }



        private void toolStripButtonClear_Click(object sender, EventArgs e)

        {

            active.TempDelete();

        }





        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.SelectAll(true);

        }



        private void unselectAllToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.SelectAll(false);

        }



        private void toolStripButtonCut_Click(object sender, EventArgs e)

        {

            cutToolStripMenuItem_Click(sender, e);

        }



        private void toolStripButtonCopy_Click(object sender, EventArgs e)

        {

            copyToolStripMenuItem_Click(sender, e);

        }



        private void toolStripButtonPaste_Click(object sender, EventArgs e)

        {

            pasteToolStripMenuItem_Click(sender, e);

        }



        private void connectToolStripMenuItem_Click(object sender, EventArgs e)

        {

            StaticExtension.Server = "";

            data = null;

            prepareData();

        }



        private void toolStripButtonStart_Click(object sender, EventArgs e)

        {

            Start();

        }



        private void toolStripButtonStop_Click(object sender, EventArgs e)

        {

            Stop();

        }







        private void readWriteToolStripMenuItem_Click(object sender, EventArgs e)

        {

            if (!prepareData())

            {

                return;

            }

            FormDatabase form = new FormDatabase(

                new StandardStarter(ResourceService.Resources.CurrentDirectory + "Temp\\"),

                data, true);

            form.ShowDialog(this);



        }





        private void saveToolStripMenuItem_Click(object sender, EventArgs e)

        {

            if (filename.Length == 0)

            {

                saveasToolStripMenuItem_Click(sender, e);

                return;

            }

            try

            {

                Stream stream = File.Open(filename, FileMode.Create);

                SaveAll(stream);

                stream.Close();

            }

            catch (Exception ex)

            {

                ex.Log();

                ControlUtilites.ShowError(this, ex, resources);

            }

        }



        private void loadfromdatabaseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            loadFromDatabase();

        }





        private void toolStripButtonLoadFromDatabase_Click(object sender, EventArgs e)

        {

            loadFromDatabase();

        }



        private void changeorderofselectedToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Form form = new FormOrder(active);

            form.ShowDialog(this);



        }



        private void updateToolStripMenuItem_Click(object sender, EventArgs e)

        {

            update();

        }



        private void savetodatabaseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            saveToDatabase();

        }



        private void openToolStripButton_Click(object sender, EventArgs e)

        {

           Open();

        }



        private void copyToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Stream stream = new MemoryStream();

            active.SaveSelected(stream);

            Clipboard.SetData("AstroFrame", stream);

        }



        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)

        {

            object o = Clipboard.GetData("AstroFrame");

            if (o == null)

            {

                return;

            }

            Stream stream = o as Stream;

            LoadFromStream(stream, creator.Ext);

        }



        private void cutToolStripMenuItem_Click(object sender, EventArgs e)

        {

            clearselectedToolStripMenuItem_Click(sender, e);

        }



        private void saveasToolStripMenuItem_Click(object sender, EventArgs e)

        {

            saveas();

        }



        private void openToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Open();

        }



        private void toolStripButtonStrict_Click(object sender, EventArgs e)

        {

            if (toolStripButtonStrict.Checked)

            {

                DiagramUI.StaticExtension.SetStrictErrorHandler();

            }

            else

            {

                DiagramUI.StaticExtension.LogHandler = null;

            }

        }









        private void ActionPrivate(bool start)

        {

            if (start)

            {

                StartDisable();

            }

            else

            {

                StopEnable();

            }

            StaticFactoryPerformer.Action(active, null, start);

        }



        void StartPrivate()

        {

            ActionPrivate(true);

        }



        void StopPrivate()

        {

            ActionPrivate(false);

        }



        private void saveToolStripButton_Click(object sender, EventArgs e)

        {

            save();

        }



        private void derivationCalculatorToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Form f = new DataPerformerUI.FormDerivationCalculator("xyzt");

            f.Show();

        }



        private void containerDesignerToolStripMenuItem_Click(object sender, EventArgs e)

        {

            showContainerDesigner();

        }



        private void toolStripButtonTest_Click(object sender, EventArgs e)

        {

            TestCategory.UI.TestPerformerUI perf = new TestCategory.UI.TestPerformerUI();

            perf.TestData(data, null, active, "cfa", "cfa", creator.Log);

            PureDesktopPeer d = new PureDesktopPeer();

            active.Copy(d);

            MemoryStream ms = new MemoryStream();

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(ms, d);

            MemoryStream str = new MemoryStream(ms.GetBuffer());

            d = bf.Deserialize(str) as PureDesktopPeer;

            clearallToolStripMenuItem_Click(null, null);

            active.Load(d);



        }

        private void toolStripButtonSync_Click(object sender, EventArgs e)

        {

            update();

        }



        private void dataToolStripMenuItem_Click(object sender, EventArgs e)

        {

            ShowData();

        }



       /* private void controlToolStripMenuItem_Click(object sender, EventArgs e)

        {

            ShowControl();

        }*/



        private void objectTreelBarToolStripMenuItemObjects_Click(object sender, EventArgs e)

        {

            ShowTree();

        }



        private void toolboxToolStripMenuItem_Click(object sender, EventArgs e)

        {

            ShowTools();

        }



        private void toolStripComboBoxCheckDetails_SelectedIndexChanged(object sender, EventArgs e)

        {

            SetCheckLevel();

        }





        #endregion



        #endregion



        #region Work with database



        private bool prepareData()

        {

            if (data != null)

            {

                return true;

            }

            string ser = "";

            try

            {

                ser = server;

                if (ser.Length == 0)

                {

                    connect();

                    if (server.Length == 0)

                    {

                        return false;

                    }

                    ser = server;

                }

                if (formData != null)

                {

                    formData.Hide();

                    formData = null;

                }

                IDatabaseInterface inter = //ReportingServer.ReportingInterface.GetService("");

                       DataWarehouse.DatabaseInterface.Coordinator[ser];



                IUser user = new User("", "", null);

                data = new DatabaseInterface(user, inter);

                ShowData();

                return true;

            }

            catch (Exception ex)

            {

                ex.Log();

                if (StaticExtension.ConnectionStrings.Contains(ser))

                {

                    StaticExtension.ConnectionStrings.Remove(ser);

                }

                StaticExtension.Server = "";

                StaticExtension.Save();

                // loadfromdatabaseToolStripMenuItem.Visible = false;

                // savetodatabaseToolStripMenuItem.Visible = false;

                /*toolStripButtonLoadFromDatabase.Visible = false;

                databaseToolStripMenuItem.Visible = false;*/

            }

            return false;

        }





        private void connect()

        {

            /*

            FormConnectToDatabase form = new FormConnectToDatabase();

            form.ShowDialog(this);*/

            System.Collections.Specialized.StringCollection str = StaticExtension.ConnectionStrings;



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

            foreach (string s in str)

            {

                l.Add(s);

            }

            l.Sort();

            string serv = server + "";

            FormConnectionString form = new FormConnectionString(l, server);

            if (form.ShowDialog(this) != DialogResult.OK)

            {

                server = "";

                return;

            }

            serv = form.ConnectionString;

            if (!l.Contains(serv))

            {

                StaticExtension.ConnectionStrings.Add(serv);

                StaticExtension.Save();

            }

            server = serv;

        }



        private string server

        {

            get

            {



                // StaticExtension.Server = "3d-monstr";

                // StaticExtension.Save();

                string s = StaticExtension.Server;

                if (s.Length == 0)

                {

                    // dataToolStripMenuItem.Visible = false;

                }

                return StaticExtension.Server;

            }

            set

            {

                StaticExtension.Server = value;

                /*if (value.Length == 0)

                {

                    dataToolStripMenuItem.Visible = false;

                }

                else

                {

                    dataToolStripMenuItem.Visible = false;

                }*/

                StaticExtension.Save();

            }

        }







        void loadFromDatabase()

        {

            if (!prepareData())

            {

                return;

            }

            try

            {

                FormDatabase form = new FormDatabase(this, data, true);

                form.ShowDialog(this);

            }

            catch (Exception e)

            {

                e.Log();

                MessageBox.Show(e.Message);

            }

        }







        void saveToDatabase()

        {

            if (!prepareData())

            {

                return;

            }

            FormDatabase form = new FormDatabase(this, data, false);

            form.ShowDialog(this);

        }



        #endregion



        #region Shows Child Windows



        private void showContainerDesigner()

        {



            DiagramUI.Forms.FormContainerDesigner.Show(active, ref formContainer);

        }





        private void ShowDesktop()

        {

            createDockMan();



            if (desktop == null)

            {

                tools = new ToolsDiagram(creator.Factory);

                desktop = new FormDesktop(tools, creator.Ext);

                desktop.Desktop.AddStreamCreator("DataWarehouse.DatabaseStreamCreator");

                tools.Tree = formTree.Tree;

                //tools.Active = desktop.Desktop;

            }

            desktop.Show(dockManager);

            active = desktop.Desktop;

        }



        private void ShowTree()

        {

            createDockMan();

            formTree.Show(dockManager);

            StaticExtension.ShowTree = true;

            StaticExtension.Save();

        }



        private void ShowControl()

        {

            toolStripTextBoxStart.Text = StaticExtension.StartTime + "";

            toolStripTextBoxStep.Text = StaticExtension.Step + "";

            toolStripTextBoxPause.Text = StaticExtension.Pause + "";

            toolStripTextBoxStartStep.Text = StaticExtension.StartStep + "";

            toolStripTextBoxStepCount.Text = StaticExtension.StepCount + "";

        }







        void ShowTools()

        {

            if (formTools == null)

            {

                formTools = new FormTools();

                Content c = formTools;

                formTools.OnHide += delegate()

                {

                    StaticExtension.ShowTools = false;

                    StaticExtension.Save();

                };

            }

            StaticExtension.ShowTools = true;

            StaticExtension.Save();

            formTools.Show(dockManager);

        }





        void ShowData()

        {

            if (creator.DatabaseCoordinator == null)

            {

                return;

            }

            createDockMan();

            if (formData == null)

            {

                if (data == null)

                {

                    try

                    {

                        string ser = server;

                        if (ser.Length == 0)

                        {

                            return;

                        }

                        IDatabaseInterface inter = //ReportingServer.ReportingInterface.GetService("");

                       DatabaseInterface.Coordinator[ser];



                        IUser user = new User("", "", null);

                        data = new DatabaseInterface(user, inter);

                        EngineeringUIFactory.Data = data;

                    }

                    catch (Exception ex)

                    {

                        ex.Log();

                        server = "";

                        return;

                    }

                }

                try

                {

                    formData = new FormDatabaseTree(data, creator.Ext, creator.Icon.ToBitmap());

                    formData.OnHide += delegate()

                    {

                        StaticExtension.ShowDatabase = false;

                        StaticExtension.Save();

                    };

                }

                catch (Exception exc)

                {

                    exc.Log();

                    MessageBox.Show(exc.Message);

                    StaticExtension.ShowDatabase = false;

                    StaticExtension.Save();

                    return;

                }

            }

            StaticExtension.ShowDatabase = true;

            StaticExtension.Save();

            formData.Show(dockManager);

        }





        #endregion



        #region Members



        #region Public Members



        public IApplicationCreator Creator

        {

            get

            {

                return creator;

            }

        }



        #endregion



        #region Nonpublic Members



        void Start()

        {

            StartDisable();

            toolStripButtonStop.Enabled = true;

            IProcess p = this;

            p.Start();



        }

        

        void Stop()

        {

            IProcess p = this;

            p.Terminate();

        }



        void StartDisable()

        {

            ToolStripItemCollection coll = toolStripMain.Items;

            foreach (ToolStripItem it in coll)

            {

                it.Enabled = false;

            }

            active.AllowDrop = false;

            menuStripMain.Enabled = false;

            tabControlControls.Enabled = false;

           // toolStripButtonStop.Enabled = true;

        }



        void StopEnable()

        {

            ToolStripItemCollection coll = toolStripMain.Items;

            foreach (ToolStripItem it in coll)

            {

                it.Enabled = true;

            }

            active.AllowDrop = true;

            menuStripMain.Enabled = true;

            tabControlControls.Enabled = true;

            toolStripButtonStop.Enabled = false;

        }



        private void update()

        {

            try

            {

                using (TimeProviderBackup backup = new TimeProviderBackup(active, 0))

                {

                    IDataPerformerRuntime r = backup.Runtime;

                    r.Refresh();

                    r.StartAll(StartTime);

                    r.TimeProvider.Time = StartTime;

                    r.UpdateAll();

                }

            }

            catch (Exception ex)

            {

                ex.Log();

                ShowError(ex);

            }

        }



        void SetSettings()

        {

            WindowState = StaticExtension.FullScreen ? FormWindowState.Maximized : FormWindowState.Normal;

            Left = StaticExtension.Left = Left;

            Top = StaticExtension.Top = Top;

            if (StaticExtension.Width > 0)

            {

                Width = StaticExtension.Width;

                Height = StaticExtension.Height;

            }

            toolStripComboBoxCheckDetails.SelectedIndex = StaticExtension.CheckLevel;

            SetCheckLevel();

            toolStripComboBoxCheckDetails.SelectedIndexChanged += toolStripComboBoxCheckDetails_SelectedIndexChanged;

            ShowControl();

        }





        private double StartTime

        {

            get

            {

                return GetDouble(toolStripTextBoxStart, StaticExtension.StartTime);

            }

        }





        private double GetDouble(ToolStripTextBox tb, double def)

        {

            try

            {

                return Double.Parse(tb.Text);

            }

            catch (Exception ex)

            {

                ex.Log();

            }

            return def;

        }

        

        private int GetInt(ToolStripTextBox tb, int def)

        {

            try

            {

                return Int32.Parse(tb.Text);

            }

            catch (Exception ex)

            {

                ex.Log();

            }

            return def;

        }



        private double[] GetDouble(ToolStripTextBox[] tb, double[] def)

        {

            double[] d = new double[tb.Length];

            for (int i = 0; i < d.Length; i++)

            {

                d[i] = GetDouble(tb[i], d[i]);

            }

            return d;

        }

        

        private int[] GetInt(ToolStripTextBox[] tb, int[] def)

        {

            int[] d = new int[tb.Length];

            for (int i = 0; i < d.Length; i++)

            {

                d[i] = GetInt(tb[i], d[i]);

            }

            return d;

        }





        double[] ControlDouble

        {

            get

            {

             double[] d = new double[]{StaticExtension.StartTime,

                StaticExtension.StartStep};

            double[] dx = GetDouble(new ToolStripTextBox[]

            {

                toolStripTextBoxStart,

                toolStripTextBoxStep

            }, d);

                return dx;

           }

        }





        int[] ControlInt

        {

get

{

      ToolStripTextBox[] tb = new ToolStripTextBox[]

      {

            toolStripTextBoxPause,

            toolStripTextBoxStartStep,

            toolStripTextBoxStepCount

      };



    int[] i = new int[]

    {

           StaticExtension.Pause,

           StaticExtension.StartStep,

           StaticExtension.StepCount





    };

    return GetInt(tb, i);

        }

        }









        bool SaveSettings()

        {



            if (creator.Holder != null)

            {

                DialogResult dr = MessageBox.Show(

                    ResourceService.Resources.GetControlResource("Save data?", DiagramUI.Utils.ControlUtilites.Resources),

                    ResourceService.Resources.GetControlResource(creator.Text, DiagramUI.Utils.ControlUtilites.Resources),

                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                if (dr == DialogResult.Cancel)

                {

                    return false;

                }

                if (dr == DialogResult.No)

                {

                    return true;

                }



            }



            StaticExtension.FullScreen = (WindowState == FormWindowState.Maximized);

            StaticExtension.Left = Left;

            StaticExtension.Top = Top;

            StaticExtension.Width = Width;

            StaticExtension.Height = Height;

            if (dockManager != null)

            {

                dockManager.SetLayouot();

                StaticExtension.LeftPortion = dockManager.DockLeftPortion;

                StaticExtension.RightPortion = dockManager.DockRightPortion;

            }

            MemoryStream ms = new MemoryStream();

            if (!SaveAll(ms))

            {

                return false;

            }

            double[] d = ControlDouble;

            StaticExtension.StartTime = d[0];

            StaticExtension.Step = d[1];

            int[] ii = ControlInt;

            StaticExtension.Pause = ii[0];

            StaticExtension.StartStep = ii[1];

            StaticExtension.StepCount = ii[2];

            if (creator.Holder == null)

            {

                byte[] b = ms.GetBuffer();

                char[] cb = new char[b.Length];

                for (int k = 0; k < b.Length; k++)

                {

                    cb[k] = (char)b[k];

                }

                string str = new string(cb);

                StaticExtension.SavedState = str;

                StaticExtension.Save();

            }

            else

            {

                PureDesktopPeer edit = new PureDesktopPeer();

                active.Copy(edit);

                ByteHolder holder = new ByteHolder();

                holder.Bytes = edit.Content;

                creator.Holder = holder;

            }

            return true;

        }



        private void SetCheckLevel()

        {

            int i = toolStripComboBoxCheckDetails.SelectedIndex;

            if (i == 0)

            {

                DataPerformer.FormulaMeasure.CheckValue =

                    DataPerformer.FormulaMeasure.Check;

            }

            else

            {

                DataPerformer.FormulaMeasure.CheckValue =

                    DataPerformer.FormulaMeasure.EmptyCheck;

            }

            StaticExtension.CheckLevel = i;

            StaticExtension.Save();

        }



        #endregion



 



        #endregion



    }

}





By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Russian Federation Russian Federation
Ph. D. Petr Ivankov worked as scientific researcher at Russian Mission Control Centre since 1978 up to 2000. Now he is engaged by Aviation training simulators http://dinamika-avia.com/ . His additional interests are:

1) Noncommutative geometry

http://front.math.ucdavis.edu/author/P.Ivankov

2) Literary work (Russian only)

http://zhurnal.lib.ru/editors/3/3d_m/

3) Scientific articles
http://arxiv.org/find/all/1/au:+Ivankov_Petr/0/1/0/all/0/1

Comments and Discussions