/// <summary>
        /// Returns a clone of the object.
        /// </summary>
        /// <param name="argsDefinition"> The ScriptingApplicationArgs to clone.</param>
        /// <returns> A clone of the object.</returns>
        public static object Clone(ScriptingApplicationArgs argsDefinition)
        {
            if ( serializer == null )
            {
                // Initiate serializer.
                ScriptingApplicationArgsSerializer init = new ScriptingApplicationArgsSerializer();
            }

            XmlNode node = serializer.WriteXmlNode(typeof(ScriptingApplicationArgs), argsDefinition, "ScriptingApplicationArgs");
            XmlNode clone = node.Clone();
            return serializer.ReadXmlNode(typeof(ScriptingApplicationArgs), clone, "ScriptingApplicationArgs");
        }
 /// <summary>
 /// Creates a new ScriptingApplicationArgumentForm.
 /// </summary>
 /// <param name="file"> The scripting application package to run.</param>
 //        public ScriptingApplicationArgumentForm(string file) : this()
 //        {
 //            FileInfo fileInfo = new FileInfo(file);
 //            this.Text = "Scripting Application Form - " + fileInfo.Name.Replace(fileInfo.Extension, "");
 //            _packageFile = file;
 //            RunScriptingApplication(file);
 //        }
 /// <summary>
 /// Creates a new ScriptingApplicationArgumentForm.
 /// </summary>
 /// <param name="application"> The ScriptingApplication type.</param>
 /// <param name="arguments"> The ScriptingApplicationArgs type.</param>
 public ScriptingApplicationArgumentForm(ScriptingApplication application, ScriptingApplicationArgs arguments)
     : this()
 {
     if ( arguments == null )
     {
         _args = new ScriptingApplicationArgs();
     }
     else
     {
         _args = arguments;
     }
     _scrapp = application;
 }
        /// <summary>
        /// Shows the scripting arguments designer.
        /// </summary>
        internal void ShowScriptingArgumentsDesigner()
        {
            if ( _scriptingArgumentsDef == null )
            {
                _scriptingArgumentsDef = _scriptingData.CreateArgumentDefinition();
            }
            else
            {
                _scriptingArgumentsDef = _scriptingData.UpdateArgumentDefinition(_scriptingArgumentsDef);
            }

            if ( _scriptingArgumentsDef.WebRequestArguments.Length > 0 )
            {
                // Load designer
                ScriptingApplicationArgumentDesignerForm designer = new ScriptingApplicationArgumentDesignerForm(_scriptingArgumentsDef);

                if( designer.ShowDialog() == DialogResult.OK )
                {
                    _scriptingArgumentsDef = designer.ScriptingApplicationArgs;
                }
            }
            else
            {
                // Display message
                MessageBox.Show("There are no arguments assigned for this scripting application.", AppLocation.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        internal void ExportApplicationToXml()
        {
            // send this to disk
            System.IO.Stream stream = null;

            dlgSaveFile.InitialDirectory = Application.UserAppDataPath;
            dlgSaveFile.RestoreDirectory = true;
            dlgSaveFile.Filter = "XML (*.xml)|*.xml";
            dlgSaveFile.Title = "Export Scripting Application to XML";

            if ( dlgSaveFile.ShowDialog() == DialogResult.OK )
            {
                Application.DoEvents();
                tempCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;

                // file
                stream = dlgSaveFile.OpenFile();
                if ( stream != null )
                {
                    try
                    {
                        _scriptingData.ToXmlDocument().Save(stream);

                        if ( _scriptingArgumentsDef == null )
                        {
                            _scriptingArgumentsDef = _scriptingData.CreateArgumentDefinition();
                        }
                        else
                        {
                            _scriptingArgumentsDef = _scriptingData.UpdateArgumentDefinition(_scriptingArgumentsDef);
                        }

                        if ( _scriptingArgumentsDef.WebRequestArguments.Length > 0 )
                        {
                            string fileName = dlgSaveFile.FileName.Substring(0,dlgSaveFile.FileName.Length-4) + "_args.xml";
                            _scriptingArgumentsDef.ToXmlDocument().Save(fileName);
                        }
                    }
                    catch ( Exception ex )
                    {
                        ExceptionHandler.RegisterException(ex);
                        MessageBox.Show("Error while saving the web unit test template file.", AppLocation.ApplicationName, MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
            }

            if (stream != null)
            {
                Cursor.Current = tempCursor;
                stream.Close();
            }
        }
        /// <summary>
        /// Loads a scripting file.
        /// </summary>
        /// <param name="fileName"> The file name to load.</param>
        public void LoadFile(string fileName)
        {
            string contentType = AppLocation.GetMIMEType(fileName);

            // xml file
            if ( contentType.IndexOf("xml") > -1 )
            {
                _scriptingData.Load(fileName);
            }
            else
            {
                ScriptingApplicationPackage package
                    = new ScriptingApplicationPackage(fileName);
                _scriptingData = package.ScriptingApplication;
                _scriptingArgumentsDef = package.ScriptingApplicationArguments;
            }
        }
        /// <summary>
        /// Runs the scripting application as a Windows Form application.
        /// </summary>
        /// <param name="file"> The ScriptingApplication or ScriptingApplicationPackage to run.</param>
        public void RunScriptingApplication(string file)
        {
            FileInfo fileInfo = new FileInfo(file);
            _packageFile = file;
            this.Text = "Scripting Application Form - " + fileInfo.Name.Replace(fileInfo.Extension, "");
            string contentType = AppLocation.GetMIMEType(file);

            if ( contentType.IndexOf("xml") == -1 )
            {
                ScriptingApplicationPackage package = new ScriptingApplicationPackage(file);
                _args = package.ScriptingApplicationArguments;
                _scrapp = package.ScriptingApplication;
            }
        }
        /// <summary>
        /// Updates a ScriptingApplicationArgs.
        /// </summary>
        /// <returns>A ScriptingApplicationArgs type.</returns>
        public ScriptingApplicationArgs UpdateArgumentDefinition(ScriptingApplicationArgs existingApplicationArgs)
        {
            ScriptingApplicationArgs saArguments = new ScriptingApplicationArgs();

            if ( this.WebRequests.Length > 0 )
            {

                Hashtable lookupTable = new Hashtable();
                foreach ( WebRequestArgs wbr in existingApplicationArgs.WebRequestArguments )
                {
                    foreach ( Argument a in wbr.Arguments )
                    {
                        lookupTable.Add(a.Name, a);
                    }
                }

                int i = 0;
                for (int j=0;j<this.WebRequests.Length;j++)
                {
                    WebRequest request = this.WebRequests[j];

                    if ( request.InputTransforms.Length > 0 ||  request.OutputTransforms.Length > 0)
                    {
                        // Create WebRequestArgs, if values are enabled.
                        WebRequestArgs webRequestArgs = new WebRequestArgs();
                        webRequestArgs.WebRequestIndex = j;

                        foreach ( WebTransform t in request.InputTransforms )
                        {
                            Argument[] args = t.GetArguments();

                            if ( args != null )
                            {
                                foreach ( Argument newArgument in args )
                                {
                                    if ( lookupTable.ContainsKey(newArgument.Name) )
                                    {
                                        newArgument.DesignProperty = ((Argument)lookupTable[newArgument.Name]).DesignProperty;
                                    }
                                }
                                webRequestArgs.AddArguments(args);
                            }
                            i++;
                        }

                        i = 0;
                        foreach ( WebTransform t in request.OutputTransforms )
                        {
                            Argument[] args = t.GetArguments();

                            if ( args != null )
                            {
                                foreach ( Argument newArgument in args )
                                {
                                    if ( lookupTable.ContainsKey(newArgument.Name) )
                                    {
                                        newArgument.DesignProperty = ((Argument)lookupTable[newArgument.Name]).DesignProperty;
                                    }
                                }
                                webRequestArgs.AddArguments(args);
                            }
                            i++;
                        }

                        // Add WebRequestArgs to ScriptingApplicationArgs.
                        saArguments.AddWebRequestArgs(webRequestArgs);
                    }
                }
            }

            return saArguments;
        }
        /// <summary>
        /// Loads a ScriptingApplicationArgs.
        /// </summary>
        /// <returns>A ScriptingApplicationArgs type.</returns>
        public void LoadArgumentDefinition(ScriptingApplicationArgs arguments)
        {
            XmlDocument document = this.ToXmlDocument();

            XmlNamespaceManager manager = new XmlNamespaceManager(document.NameTable);
            manager.AddNamespace("scr", "http://schemas.ecyware.com/2005/01/Ecyware-GreenBlue-ScriptingApplication");
            manager.AddNamespace("xsd","http://www.w3.org/2001/XMLSchema");
            manager.AddNamespace("xsi","http://www.w3.org/2001/XMLSchema-instance");

            if ( this.WebRequests.Length > 0 )
            {
                int webRequestIndex = 1;
                int webRequestArgsIndex = 0;
                foreach ( WebRequest request in WebRequests )
                {
                    if ( request.InputTransforms.Length > 0 || request.OutputTransforms.Length > 0 )
                    {
                        WebRequestArgs webRequestArgs = arguments.WebRequestArguments[webRequestArgsIndex];

                        string query = "//scr:WebRequests/*[" + webRequestIndex + "]//*[scr:EnabledInputArgument='true']";

                        XmlNodeList defaultTransformValues =
                            document.SelectNodes(query, manager);

                        if ( defaultTransformValues.Count > 0 )
                        {
                            int i = 0;
                            foreach ( XmlNode defaultTransformValue in defaultTransformValues )
                            {
                                XmlNode value =  defaultTransformValue.SelectSingleNode("scr:Value",manager);
                                value.InnerText =  webRequestArgs.Arguments[i].Value;
                                i++;
                            }
                        }

                        webRequestArgsIndex++;
                    }

                    webRequestIndex++;
                }

                // update input transforms
                ScriptingApplication scrapp = (ScriptingApplication)serializer.Create(document.DocumentElement.OuterXml);
                this._list.Clear();
                this.WebRequests = scrapp.WebRequests;
            }
        }
        /// <summary>
        /// Creates a ScriptingApplicationArgs.
        /// </summary>
        /// <returns>A ScriptingApplicationArgs type.</returns>
        public ScriptingApplicationArgs CreateArgumentDefinition()
        {
            ScriptingApplicationArgs saArguments = new ScriptingApplicationArgs();

            if ( this.WebRequests.Length > 0 )
            {
                for (int i=0;i<this.WebRequests.Length;i++)
                {
                    WebRequest request = this.WebRequests[i];

                    if ( request.InputTransforms.Length > 0 )
                    {
                        // Create WebRequestArgs, if values are enabled.
                        WebRequestArgs webRequestArgs = new WebRequestArgs();
                        webRequestArgs.WebRequestIndex = i;

                        foreach ( WebTransform t in request.InputTransforms )
                        {
                            Argument[] args = t.GetArguments();

                            if ( args != null )
                            {
                                webRequestArgs.AddArguments(args);
                            }
                        }

                        // Add WebRequestArgs to ScriptingApplicationArgs.
                        saArguments.AddWebRequestArgs(webRequestArgs);
                    }
                }
            }

            return saArguments;
        }
 /// <summary>
 /// Creates a new ScriptingApplicationArgumentDesignerForm.
 /// </summary>
 /// <param name="args"> The arguments to load.</param>
 public ScriptingApplicationArgumentDesignerForm(ScriptingApplicationArgs args)
     : this()
 {
     _applicationArgs = args;
     LoadArguments();
 }
        /// <summary>
        /// Creates a new ScriptingApplicationPackage.
        /// </summary>
        /// <param name="application"> The scripting application.</param>
        /// <param name="arguments"> The application arguments.</param>
        /// <param name="filePath"> The output file path.</param>
        /// <param name="doEncrypt"> Sets the encrypttion setting for a scripting application.</param>
        public static void CreatePackage(ScriptingApplication application, ScriptingApplicationArgs arguments, string filePath, bool doEncrypt)
        {
            try
            {
                if ( application.Header.ApplicationID == null )
                {
                    application.Header.ApplicationID = System.Guid.NewGuid().ToString();
                }

                // Get all FileReference elements.
                FileReference[] fileReferences = application.GetFileReferences();
                string applicationPath = System.Windows.Forms.Application.UserAppDataPath;

                string temp = applicationPath + "/temp/";

                if ( !Directory.Exists(temp) )
                {
                    Directory.CreateDirectory(temp);
                }

                C1.C1Zip.C1ZipFile zipFile = new C1.C1Zip.C1ZipFile();
                zipFile.Create(filePath);
                zipFile.Open(filePath);

                string argumentsFileName = application.Header.ApplicationID + "-applicationArguments.xml";

                FileReference argumentsFileReference = new FileReference(argumentsFileName);
                application.Header.ScriptingApplicationArgumentsReference = argumentsFileReference;

                // Add Scripting Application
                string xml = string.Empty;
                if ( doEncrypt )
                {
                    xml = application.Encrypt();
                }
                else
                {
                    xml = application.ToXml();
                }

                MemoryStream mem = new MemoryStream(System.Text.Encoding.UTF8.GetByteCount(xml));
                StreamWriter writer =  new StreamWriter(mem, System.Text.Encoding.UTF8);
                writer.Write(xml);
                writer.Flush();
                mem.Position = 0;
                zipFile.Entries.Add(writer.BaseStream, application.Header.ApplicationID);
                writer.Close();

                string argsXml = "None";
                if ( arguments != null )
                {
                    // Add Scripting Application Arguments
                    argsXml = arguments.ToXml();
                }
                mem = new MemoryStream(System.Text.Encoding.UTF8.GetByteCount(argsXml));
                writer =  new StreamWriter(mem, System.Text.Encoding.UTF8);
                writer.Write(argsXml);
                writer.Flush();
                mem.Position = 0;
                zipFile.Entries.Add(writer.BaseStream, argumentsFileName);
                writer.Close();

                FileReference[] customTransforms = application.GetCustomTransforms();

                // add custom transforms
                foreach ( FileReference reference in customTransforms )
                {
                    if ( File.Exists(reference.FileName) )
                    {
                        FileInfo fileInfo = new FileInfo(reference.FileName);
                        zipFile.Entries.Add(reference.FileName, fileInfo.Name);
                    }
                }

                MemoryStream stream = new MemoryStream();
                stream.Write(new byte[] {0}, 0, 1);
                zipFile.Entries.Add(stream, "CustomTransformsSeparator");
                stream.Close();

                // add file references that are not custom transforms
                foreach ( FileReference reference in fileReferences )
                {
                    if ( File.Exists(reference.FileName) )
                    {
                        FileInfo fileInfo = new FileInfo(reference.FileName);
                        zipFile.Entries.Add(reference.FileName, fileInfo.Name);
                    }
                }

                zipFile.Close();
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// Opens a package from a web instance.
        /// </summary>
        /// <param name="fileName"> The package file name.</param>
        public void OpenPackageWeb(string fileName)
        {
            C1ZipFile zipFile = new C1ZipFile();
            //  package = new ScriptingApplicationPackage();

            try
            {
                zipFile.Open(fileName);

                // Application
                C1ZipEntry entry = zipFile.Entries[0];
                // Get entry name and convert to guid
                // if invalid GUID, throw exception
                string name = entry.FileName;
                string applicationXml = string.Empty;
                string applicationArgumentsXml = string.Empty;

                // Get Scripting Application Xml.
                Guid g = new Guid(name);
                StreamReader reader = new StreamReader(entry.OpenReader(),System.Text.Encoding.UTF8);
                applicationXml= reader.ReadToEnd();
                reader.Close();

                if ( zipFile.Entries.Count > 1 )
                {
                    // Arguments
                    entry = zipFile.Entries[1];
                    reader = new StreamReader(entry.OpenReader(),System.Text.Encoding.UTF8);
                    applicationArgumentsXml = reader.ReadToEnd();

                    if ( applicationArgumentsXml.ToLower() != "none" )
                    {
                        _arguments = ScriptingApplicationArgs.FromXml(applicationArgumentsXml);
                    }
                    else
                    {
                        _arguments = null;
                    }

                    reader.Close();
                }

                // Get Custom Transforms
                int start = 2;
                for ( int i=2;i<zipFile.Entries.Count;i++ )
                {
                    entry = zipFile.Entries[i];

                    if ( entry.FileName == "CustomTransformsSeparator" )
                    {
                        start = i+1;
                        break;
                    }

                    // Add File References to Application Startup
                    // string location = System.Windows.Forms.Application.StartupPath + Path.DirectorySeparatorChar + entry.FileName;
            //					if ( !File.Exists(location) )
            //					{
            //						zipFile.Entries.Extract(i, location);
            //					}
                    // Add WebTransform Entry in Configuration.
                    // if exists don't add.
                    // RegisterWebTransform(location);
                    // ScriptingApplicationSerializer.UpdateSerializer();
                }

                // Generate scripting application.
                XmlDocument document = new XmlDocument();
                document.LoadXml(applicationXml);
                _application = ScriptingApplication.Decrypt(document);
                //	_application = ScriptingApplication.FromXml(applicationXml);
            //
            //				for ( int i=start;i<zipFile.Entries.Count;i++ )
            //				{
            //					entry = zipFile.Entries[i];
            //
            //					// Add File References to Internet Cache
            //					string location = Utils.AppLocation.InternetTemp + Path.DirectorySeparatorChar + _application.Header.ApplicationID + Path.DirectorySeparatorChar + entry.FileName;
            //					if ( File.Exists(location) )
            //					{
            //						File.Delete(location);
            //					}
            //					zipFile.Entries.Extract(i, location);
            //				}
            }
            catch
            {
                throw;
            }
            finally
            {
                zipFile.Close();
            }
        }