/// <summary>
        /// Loads the application from file.
        /// </summary>
        /// <param name="publisher"> The publisher username.</param>
        /// <param name="message"> The WebStoreRequestMessage message.</param>
        public static string LoadApplication(string publisher, WebStoreRequestMessage message)
        {
            // format is http://www.ecyware.com/WebStore/username/applicationID
            string parentPath = System.Web.HttpContext.Current.Server.MapPath("~/WebStore");
            string userStore = parentPath + "\\" + publisher;

            StringBuilder url = new StringBuilder();
            url.Append(parentPath);
            url.Append("\\");
            url.Append(publisher);
            url.Append("\\");
            url.Append(message.ApplicationID);
            url.Append(".gbscr");

            string file = url.ToString();
            string result = string.Empty;

            if ( File.Exists(file) )
            {
                FileInfo info = new FileInfo(file);
                FileStream fs = new FileStream(file, FileMode.Open,FileAccess.Read);
                byte[] data = new byte[info.Length];
                fs.Read(data,0,data.Length);
                fs.Flush();
                fs.Close();

                // Convert to base64
                result = Convert.ToBase64String(data, 0, data.Length);
            }

            return result;
        }
        /// <summary>
        /// Adds the application.
        /// </summary>
        /// <param name="username"> The username.</param>
        /// <param name="message"> The WebStoreRequestMessage message.</param>
        public void AddApplicationToWebStore(string username, WebStoreRequestMessage message)
        {
            SqlParameter[] param = new SqlParameter[5];

            param[0] = new SqlParameter("@ApplicationID", SqlDbType.UniqueIdentifier);
            param[0].Value = new Guid(message.ApplicationID);

            param[1] = new SqlParameter("@Description", SqlDbType.VarChar, 500);
            param[1].Value = message.Description;

            param[2] = new SqlParameter("@Keywords", SqlDbType.VarChar, 300);
            param[2].Value = message.Keywords;

            param[3] = new SqlParameter("@Publisher", SqlDbType.VarChar, 20);
            param[3].Value = username;

            param[4] = new SqlParameter("@ApplicationName", SqlDbType.VarChar, 50);
            param[4].Value = message.ApplicationName;

            int affectedRows = SqlHelper.ExecuteNonQuery(_connectionString,CommandType.StoredProcedure, "AddApplicationToWebStore",param);

            if ( affectedRows > 0 )
            {
                // Add File
                WebStoreFileManager.SaveApplication(username,message);
            }
        }
        /// <summary>
        /// Removes the application to file.
        /// </summary>
        /// <param name="publisher"> The publisher username.</param>
        /// <param name="message"> The WebStoreRequestMessage message.</param>
        public static void RemoveApplication(string publisher, WebStoreRequestMessage message)
        {
            // format is http://www.ecyware.com/WebStore/username/applicationID
            string parentPath = System.Web.HttpContext.Current.Server.MapPath("~/WebStore");
            string userStore = parentPath + "\\" + publisher;

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

            StringBuilder url = new StringBuilder();
            url.Append(parentPath);
            url.Append("\\");
            url.Append(publisher);
            url.Append("\\");
            url.Append(message.ApplicationID);
            url.Append(".gbscr");

            if ( File.Exists(url.ToString()) )
            {
                File.Delete(url.ToString());
            }
        }
        public WebStoreResultMessage UpdateScriptingApplicationToWebStore(WebStoreRequestMessage message)
        {
            UsernameToken token = SecurityHelper.GetLicenseToken(RequestSoapContext.Current);

            WebStoreResultMessage result = new WebStoreResultMessage();

            // Validate license (application limit)
            if ( userDatabaseManager.ValidateApplicationLicenseLimit(token.Username) )
            {
                bool exists = userDatabaseManager.RegisteredApplicationExists(token.Username, message.ApplicationID);
                if ( exists )
                {
                    // Update to web store db
                    userDatabaseManager.UpdateApplicationToWebStore(token.Username, message);

                    result.Message = "Application registered and saved into web store.";
                    result.IsApplicationRegistered = true;
                }
                else
                {
                    #region Add Application
                    // Register application in database.
                    bool inserted = userDatabaseManager.RegisterApplication(token.Username, message.ApplicationID);

                    if ( inserted )
                    {
                        // Registered succesfully, continue adding the application to web store.
                        // Add to web store db
                        userDatabaseManager.AddApplicationToWebStore(token.Username, message);

                        result.Message = "Application registered and saved into web store.";
                        result.IsApplicationRegistered = true;
                    }
                    else
                    {
                        // Send message warning.
                        result.IsApplicationRegistered = false;
                        result.Message = "Either the application id is invalid or the application already exists on web store.";
                    }
                    #endregion
                }
            }
            else
            {
                // Send message warning.
                result.IsApplicationRegistered = false;
                result.Message = "Your application license limit doesn't allow more applications to be registered. Please purchase additional licenses.";
            }

            return result;
        }
        public WebStoreResultMessage RemoveScriptingApplication(WebStoreRequestMessage message)
        {
            UsernameToken token = SecurityHelper.GetLicenseToken(RequestSoapContext.Current);
            WebStoreResultMessage result = new WebStoreResultMessage();

            bool exists = userDatabaseManager.RegisteredApplicationExists(token.Username, message.ApplicationID);
            if ( exists )
            {
                userDatabaseManager.RemoveScriptingApplication(token.Username, message);
                result.Message = "Scripting application removed.";
            }
            else
            {
                result.Message = "Scripting application not found.";
            }

            return result;
        }
        public WebStoreResultMessage RateApplication(WebStoreRequestMessage message)
        {
            UsernameToken token = SecurityHelper.GetLicenseToken(RequestSoapContext.Current);

            WebStoreResultMessage result = new WebStoreResultMessage();
            result.Message = "Rating complete";
            userDatabaseManager.RateApplication(message);

            return result;
        }
        public WebStoreResultMessage DownloadApplication(WebStoreRequestMessage message)
        {
            UsernameToken token = SecurityHelper.GetLicenseToken(RequestSoapContext.Current);

            WebStoreResultMessage result = new WebStoreResultMessage();

            bool exists = userDatabaseManager.RegisteredApplicationExists(token.Username, message.ApplicationID);

            if ( exists )
            {
                // Update to web store db
                string applicationData = userDatabaseManager.GetApplication(message);

                result.Message = "Application downloaded.";
                result.IsApplicationRegistered = true;
                result.ApplicationData = applicationData;
            }
            else
            {
                // Send message warning.
                result.IsApplicationRegistered = false;
                result.Message = "This application cannot be found in the system.";
            }

            return result;
        }
        public WebStoreResultMessage UpdateScriptingApplicationToWebStore(WebStoreRequestMessage message)
        {
            SoapEnvelope envelope = new SoapEnvelope();
            envelope.Context.Security.Tokens.AddRange(_security.Tokens);
            envelope.SetBodyObject(message);

            return (WebStoreResultMessage)base.SendRequestResponse("UpdateScriptingApplicationToWebStore",envelope).GetBodyObject(typeof(WebStoreResultMessage));
        }
        public IAsyncResult BeginUpdateScriptingApplicationToWebStore(WebStoreRequestMessage message, MessageResultHandler callback, object state)
        {
            SoapEnvelope envelope = new SoapEnvelope();
            envelope.Context.Security.Tokens.AddRange(_security.Tokens);
            envelope.SetBodyObject(message);

            _clientHandler = callback;
            return base.BeginSendRequestResponse("UpdateScriptingApplicationToWebStore",envelope,new AsyncCallback(EndMessageResultHandler),typeof(WebStoreResultMessage));
        }
        /// <summary>
        /// Publish a scripting application to a web store.
        /// </summary>
        private void PublishApplication()
        {
            _selectedApplicationFilePath =
                GetSelectedApplicationFilePath();

            LicenseServiceClient client = Utils.ServicesProxy.GetClientProxy();

            ScriptingApplicationMetadataDialog publishDialog = new ScriptingApplicationMetadataDialog();

            if ( publishDialog.ShowDialog() == DialogResult.OK )
            {
                WebStoreRequestMessage message = new WebStoreRequestMessage();

            //				ScriptingApplicationPackage package = new ScriptingApplicationPackage();
            //				package.OpenPackage(_selectedApplicationFilePath);
            //				ScriptingApplicationPackage.CreatePackage(package.ScriptingApplication, package.ScriptingApplicationArguments, "

                message.ApplicationData = Utils.ServicesProxy.ReadFileToBase64String(_selectedApplicationFilePath);
                message.ApplicationID = ScriptingApplicationPackage.ReadApplicationID(_selectedApplicationFilePath);
                message.ApplicationName = publishDialog.ApplicationName;
                message.Description = publishDialog.Description;
                message.Keywords = publishDialog.Keywords;
                message.Rating = 0;

                MessageResultHandler callback = new MessageResultHandler(UpdateScriptingApplicationResultInvoker);
                client.BeginUpdateScriptingApplicationToWebStore(message, callback, null);
                StartProgress("Uploading Scripting Application...Please wait");
            }
        }
        /// <summary>
        /// Removes the application.
        /// </summary>
        /// <param name="username"> The username.</param>
        /// <param name="message"> The WebStoreRequestMessage message.</param>
        public void RemoveScriptingApplication(string username, WebStoreRequestMessage message)
        {
            SqlParameter[] param = new SqlParameter[2];

            param[0] = new SqlParameter("@ApplicationID", SqlDbType.UniqueIdentifier);
            param[0].Value = new Guid(message.ApplicationID);

            param[1] = new SqlParameter("@Publisher", SqlDbType.VarChar, 20);
            param[1].Value = username;

            int affectedRows = SqlHelper.ExecuteNonQuery(_connectionString,CommandType.StoredProcedure, "RemoveApplication",param);

            if ( affectedRows > 0 )
            {
                // Add File
                WebStoreFileManager.RemoveApplication(username,message);
            }
        }
        /// <summary>
        /// Rates the application.
        /// </summary>
        /// <param name="message"> A WebStoreRequestMessage type.</param>
        public void RateApplication(WebStoreRequestMessage message)
        {
            SqlParameter[] param = new SqlParameter[5];

            param[0] = new SqlParameter("@ApplicationID", SqlDbType.UniqueIdentifier);
            param[0].Value = new Guid(message.ApplicationID);

            param[1] = new SqlParameter("@Rating", SqlDbType.Int);
            param[1].Value = message.Rating;

            int affectedRows = SqlHelper.ExecuteNonQuery(_connectionString,CommandType.StoredProcedure, "RateApplication",param);
        }
        /// <summary>
        /// Gets the application from the web store.
        /// </summary>
        /// <param name="message"> The WebStoreRequestMessage type.</param>
        public string GetApplication(WebStoreRequestMessage message)
        {
            Guid appid = new Guid(message.ApplicationID);

            // Get Application Info
            DataSet application = SqlHelper.ExecuteDataset(_connectionString,"GetApplication", appid);
            DataTable table = application.Tables[0];
            string publisher = Convert.ToString(table.Rows[0]["Publisher"]);

            // Load Application from file
            string applicationData = WebStoreFileManager.LoadApplication(publisher, message);
            SqlHelper.ExecuteNonQuery(_connectionString, "UpdateApplicationDownloadCount", appid);

            return applicationData;
        }
        /// <summary>
        /// Saves the application to file.
        /// </summary>
        /// <param name="publisher"> The publisher username.</param>
        /// <param name="message"> The WebStoreRequestMessage message.</param>
        public static void SaveApplication(string publisher, WebStoreRequestMessage message)
        {
            // format is http://www.ecyware.com/WebStore/username/applicationID
            string parentPath = System.Web.HttpContext.Current.Server.MapPath("~/WebStore");
            string userStore = parentPath + "\\" + publisher;

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

            StringBuilder url = new StringBuilder();
            url.Append(parentPath);
            url.Append("\\");
            url.Append(publisher);
            url.Append("\\");
            url.Append(message.ApplicationID);
            url.Append(".gbscr");

            FileStream fs = new FileStream(url.ToString(), FileMode.Create,FileAccess.ReadWrite);
            byte[] data = Convert.FromBase64String(message.ApplicationData);
            fs.Write(data,0,data.Length);
            fs.Flush();
            fs.Close();
        }