void OkButton_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = "Creating new BasicServiceApplication1 Application";
                operation.Begin();
                try
                {
                    SPFarm farm = SPFarm.Local;
                    BasicServiceApplication1Service service = farm.Services.GetValue<BasicServiceApplication1Service>();
                    BasicServiceApplication1ServiceProxy serviceProxy = farm.ServiceProxies.GetValue<BasicServiceApplication1ServiceProxy>();

                    string title = nameField.Text;
                    BasicServiceApplication1ServiceApplication application = BasicServiceApplication1ServiceApplication.Create(
                        title, service);
                    application.Provision();
                    BasicServiceApplication1ServiceApplicationProxy applicationProxy = BasicServiceApplication1ServiceApplicationProxy.Create(
                        title, serviceProxy, application.Id);
                    applicationProxy.Provision();
                    if (defaultProxyField.Checked)
                    {
                        SPServiceApplicationProxyGroup.Default.Add(applicationProxy);
                    }
                }
                finally
                {
                    operation.EndScript("window.frameElement.commitPopup();");
                }
            }
        }
Beispiel #2
0
        private void SetupNodeServiceApp()
        {
            // create a long running op..
            using (SPLongOperation op = new SPLongOperation(this))
            {
                op.Begin();

                try
                {
                    // get reference to the installed service
                    NodeService service = SPFarm.Local.Services.GetValue <NodeService>();

                    // create the service application
                    NodeServiceApplication serviceApp = CreateServiceApplication(service);

                    // if the service instance isn't running, start it up
                    StartServiceInstances();

                    // create service app proxy
                    CreateServiceApplicationProxy(serviceApp);
                }
                catch (Exception e)
                {
                    throw new SPException("Error creating Glyma Node service application.", e);
                }
            }
        }
        void BtnGetMailClick(object sender, EventArgs e)
        {
            using (var longOperation = new SPLongOperation(Page))
            {
                longOperation.LeadingHTML  = SPSResources.GetResourceString("SPS_FetchMail_Message");
                longOperation.TrailingHTML = SPSResources.GetResourceString("SPS_FetchMail_Message2");
                longOperation.Begin();

                int port;
                Int32.TryParse(_mailPort, out port);

                var fetchMail = new FetchMail(_login,
                                              _password,
                                              _mailServer,
                                              port,
                                              _ssl,
                                              _listGuid);

                fetchMail.GetMessages();

                _error = fetchMail.GetErrorMessage();

                if (!string.IsNullOrEmpty(_error))
                {
                    SPUtility.TransferToErrorPage(_error);
                }
                else
                {
                    longOperation.End(Page.Request.Url.ToString());
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonOk_Click(object sender, EventArgs e)
        {
            // Validate
            this.Validate();

            if (!this.IsValid)
            {
                return;
            }

            // We are valid
            // Register the database
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                //TODO Save
                string nummer     = tbx_bondsnummer.Text.Trim();
                string voornaam   = tbx_voornaam.Text.Trim();
                string achternaam = tbx_achternaam.Text.Trim();
                string email      = tbx_email.Text.Trim();
                string vereniging = ddl_vereniging.SelectedItem.Value;
                ClubCloud.Model.ClubCloud_Gebruiker gebruiker = new Model.ClubCloud_Gebruiker {
                    Bondsnummer = nummer, Volledigenaam = voornaam + achternaam, Voornaam = voornaam, Achternaam = achternaam, EmailKNLTB = email, VerenigingId = Guid.Parse(vereniging)
                };

                ServiceClient.CreateGebruiker(gebruiker);


                operation.End(string.Format(CultureInfo.InvariantCulture, "/_admin/ClubCloud.Service/ManageUsers.aspx?id={0}", SPHttpUtility.UrlKeyValueEncode(this.ServiceApplication.Id)));
            }
        }
Beispiel #5
0
        private void SetupNodeServiceApp()
        {
            // create a long running op..
            using (SPLongOperation op = new SPLongOperation(this))
            {
                op.Begin();

                try
                {
                    // get reference to the installed service
                    NodeService service = SPFarm.Local.Services.GetValue<NodeService>();

                    // create the service application
                    NodeServiceApplication serviceApp = CreateServiceApplication(service);

                    // if the service instance isn't running, start it up
                    StartServiceInstances();

                    // create service app proxy
                    CreateServiceApplicationProxy(serviceApp);
                }
                catch (Exception e)
                {
                    throw new SPException("Error creating Glyma Node service application.", e);
                }
            }
        }
        private void SetupBaristaServiceApp()
        {
            // create a long running op..
            using (var op = new SPLongOperation(this))
            {
                op.Begin();

                try
                {
                    // get reference to the installed service
                    var service = BaristaHelper.GetBaristaService(SPFarm.Local);

                    // create the service application
                    var serviceApp = CreateServiceApplication(service);

                    // if the service instance isn't running, start it up
                    StartServiceInstances();

                    // create service app proxy
                    CreateServiceApplicationProxy(serviceApp);
                }
                catch (Exception e)
                {
                    throw new SPException("Error creating Barista service application.", e);
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonTrigger_Click(object sender, EventArgs e)
        {
            // Validate
            this.Validate();

            if (!this.IsValid)
            {
                return;
            }

            // We are valid
            // Register the database
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                try
                {
                    ServiceClient.TriggerMetaData("12073385", true);
                }
                catch { };

                operation.End(string.Format(CultureInfo.InvariantCulture, "/_admin/ClubCloud.Service/ManageMetaData.aspx?id={0}", SPHttpUtility.UrlKeyValueEncode(this.ServiceApplication.Id)));
            }
        }
Beispiel #8
0
        protected void generateButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                String   reportSavePath         = SPContext.Current.Web.Url;
                DateTime dtStartDate            = startDateCalendar.SelectedDate;
                DateTime dtEndDate              = endDateCalendar.SelectedDate;
                String   strDocumentLibraryName = documentLibrariesDropDown.SelectedValue.Trim();

                if (!String.IsNullOrEmpty(strDocumentLibraryName))
                {
                    SPLongOperation.Begin(delegate(SPLongOperation longOperation)
                    {
                        _ecAuditReportBuilder.StartDate           = dtStartDate;
                        _ecAuditReportBuilder.EndDate             = dtEndDate;
                        _ecAuditReportBuilder.DocumentLibraryName = strDocumentLibraryName;
                        Boolean bSuccessfulProcess = _ecAuditReportBuilder.ProcessAuditReport();

                        if ((bSuccessfulProcess) &&
                            _ecAuditReportBuilder.ReportSavePath != null &&
                            _ecAuditReportBuilder.ReportSavePath != String.Empty)
                        {
                            reportSavePath = _ecAuditReportBuilder.ReportSavePath;
                        }

                        longOperation.End(reportSavePath);
                    }
                                          );
                }
            }
        }
        protected void WaitForJobs(SPLongOperation longOp)
        {
            SPJobDefinitionCollection jobs = SPContext.Current.Site.WebApplication.JobDefinitions;
            int _seconds = 10;

            foreach (SPJobDefinition job in jobs)
            {
                if (job.Name == WebSiteControllerRuleWorkItem.WorkItemJobDisplayName)
                {
                    TimeSpan now  = new TimeSpan(DateTime.Now.Ticks);
                    TimeSpan last = new TimeSpan(job.LastRunTime.Ticks);
                    TimeSpan past = now.Subtract(last);
                    int      next = 60 - past.Seconds;

                    _seconds += next;
                    break;
                }
            }

            longOp.TrailingHTML = "This may take few seconds. " + _seconds.ToString() + " seconds actually.";
            longOp.Begin();

            Thread.Sleep(_seconds * 1000);

            return;
        }
 /// <summary>
 /// UpdateServiceApp method implementation
 /// </summary>
 private void UpdateServiceApp()
 {
     using (var operation = new SPLongOperation(this))
     {
         operation.Begin();
         NetworkCredential cred = null;
         string            name = null;
         try
         {
             name = this.txtServiceApplicationName.Text.Trim();
             ContentDatabaseSection db = this.DatabaseSection;
             if (db.UseWindowsAuthentication)
             {
                 cred = CredentialCache.DefaultNetworkCredentials;
             }
             else
             {
                 cred = new NetworkCredential(db.DatabaseUserName, db.DatabasePassword);
             }
             SPIisWebServiceApplicationPool ap = (this.ApplicationPoolSection == null) ? null : this.ApplicationPoolSection.GetOrCreateApplicationPool();
             Utilities.UpdateServiceApplicationAndProxy(true, this.ServiceApplication, name, ap, db.DatabaseName.Trim(), db.DatabaseServer.Trim(), db.FailoverDatabaseServer, cred, false, CBReplaceDB.Checked);
             Utilities.CreateUpdateDeleteClaimProvider(name, this.InputClaimProviderDropBox.SelectedValue, this.txtInputFormDisplayClaimName.Text, this.txtInputFormTextClaimDesc.Text, this.visibilityCB.Checked, this.CanUpdateProvider());
         }
         catch (Exception ex)
         {
             // new SPException(String.Format("Failed to update service applicaton {0}", name), ex);
             RedirectToErrorPage(String.Format("Failed to create service applicaton {0} \n Execption : {1}", name, ex.Message));
         }
     }
 }
Beispiel #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SPLongOperation.Begin(delegate(SPLongOperation longOperation)
            {
                longOperation.TrailingHTML = "Please wait while your data is being exported...";
                try
                {
                    if (Request.QueryString["items"] != null && Request.QueryString["source"] != null && Request.QueryString["sourceurl"] != null)
                    {
                        string source     = Request.QueryString["source"];
                        string[] items    = Request.QueryString["items"].ToString().Split('|');
                        string currentWeb = Request.QueryString["sourceurl"].Replace("'", string.Empty);

                        source        = source.Substring(1, source.Length - 2).ToLower();
                        Guid sourceId = new Guid(source);

                        SPWeb web = SPContext.Current.Web;
                        SPDocumentLibrary sourceDocLibrary = (SPDocumentLibrary)web.Lists[sourceId];
                        SPFolder folder = null;
                        itemsToExport   = new List <SPListItem>();

                        //start at 1 due to items split containing a leading empty value
                        for (int i = 1; i < items.Length; i++)
                        {
                            SPListItem currentListItem = sourceDocLibrary.GetItemById(int.Parse(items[i]));
                            itemsToExport.Add(currentListItem);
                            folder = currentListItem.File.ParentFolder;
                        }

                        // build a memory stream of our file contents
                        MemoryStream exportStream = BuildStreamToExport(itemsToExport);
                        // save our export file to our doc libary
                        web.AllowUnsafeUpdates = true;
                        SaveFile(exportStream, folder);
                        web.AllowUnsafeUpdates = false;

                        //close the modal
                        //Response.Write(string.Format(CultureInfo.InvariantCulture, "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, '{0}');</script>", itemsToExport.Count));
                        //Response.Flush();
                        //Response.End();
                        if (SPContext.Current.IsPopUI)
                        {
                            longOperation.EndScript("window.frameElement.commitPopup();");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Error while loading documents for metadata export.", ex, DiagnosticsCategories.eCaseWeb);
                }
            }
                                  );
        }
        /// <summary>
        /// TODO: Add comment
        /// </summary>
        /// <param name="sender">Sender of the event</param>
        /// <param name="e">Arguments of the event</param>
        private void BtnOk_Click(object sender, EventArgs e)
        {
            string strPackageFileName       = Path.GetFileName(fup_wsp.PostedFile.FileName);
            string strPackageServerFileName = strTempPath + strPackageFileName;

            //lblErrorMessage.ForeColor = Color.Red;

            try
            {
                //Checking if the file selected...
                if (fup_wsp.FileName == "")
                {
                    //lblErrorMessage.Text = "Please select the solution file";
                    return;
                }

                //Checking if the package already existed in the Farm Solutions.
                if (SPFarm.Local.Solutions[strPackageFileName] != null)
                {
                    //lblErrorMessage.Text = "Please retract and remove the solution before uploading it";
                    return;
                }

                using (SPLongOperation operation = new SPLongOperation(this.Page))
                {
                    operation.LeadingHTML  = "Uploading the solution package";
                    operation.TrailingHTML = "Adding " + strPackageFileName + " to the solution store..";
                    operation.Begin();

                    //Deleting the file if its already existed.
                    if (File.Exists(strPackageServerFileName))
                    {
                        File.Delete(strPackageServerFileName);
                    }

                    //Saving a copy of the Package.
                    fup_wsp.PostedFile.SaveAs(strPackageServerFileName);



                    //Adding the Package to the Store.
                    SPFarm.Local.Solutions.Add(strPackageServerFileName);

                    //Thread.Sleep(0x1770);
                    operation.End(SPContext.Current.Site.Url + "/_admin/operations.aspx");
                }
            }
            catch (Exception ex)
            {
                throw new SPException(ex.Message);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonRemoveService_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ManageServiceRemoveOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ManageServiceRemoveOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                ClubCloudService.RemoveService();

                operation.End("/_admin/ClubCloud.Service/ManageService.aspx");
            }
        }
Beispiel #14
0
        /// <summary>
        /// Creates the service application.
        /// </summary>
        private void CreateApplication()
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "CreateOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "CreateOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                try
                {
                    ClubCloudService      service      = ClubCloudService.GetOrCreateService();
                    ClubCloudServiceProxy serviceProxy = ClubCloudServiceProxy.GetOrCreateServiceProxy();

                    // Create the application pool
                    IisWebServiceApplicationPoolSection applicationPoolSectionCasted = this.applicationPoolSection as IisWebServiceApplicationPoolSection;
                    SPIisWebServiceApplicationPool      applicationPool = applicationPoolSectionCasted.GetOrCreateApplicationPool();

                    // Create the service application
                    ClubCloudServiceApplication application = new ClubCloudServiceApplication(
                        this.textBoxServiceName.Text.Trim(),
                        service,
                        applicationPool);
                    application.Update();
                    application.Provision();

                    // Create the service application proxy
                    ClubCloudServiceApplicationProxy proxy = new ClubCloudServiceApplicationProxy(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ServiceApplicationProxyNameTemplate", CultureInfo.CurrentCulture).ToString(),
                            this.textBoxServiceName.Text.Trim()),
                        serviceProxy,
                        application.Uri);
                    proxy.Update();
                    proxy.Provision();

                    if (this.checkBoxIncludeInDefaultProxy.Checked)
                    {
                        SPServiceApplicationProxyGroup group = SPServiceApplicationProxyGroup.Default;
                        group.Add(proxy);
                        group.Update();
                    }

                    operation.EndScript("window.frameElement.commitPopup();");
                }
                catch (Exception ex)
                {
                    SPUtility.TransferToErrorPage(ex.ToString());
                }
            }
        }
 protected void ButtonSave_Click(object sender, EventArgs e) {
     using (SPLongOperation longOperation = new SPLongOperation(this.Page)) {
         longOperation.LeadingHTML = "请稍等,这不会花费很长的时间...";
         longOperation.TrailingHTML = "请稍等,这不会花费很长的时间...";
         longOperation.Begin();
         var issue = GetIssue();
         issue["是否追责"] = true;
         issue.Update();
         var blaming = CreateBlaming();
         var redirectURL = string.Format("{0}listform.aspx?ListId={1}&PageType=4&ID={2}",
                 SPUtility.GetWebLayoutsFolder(blaming.ParentList.ParentWeb), blaming.ParentList.ID, blaming.ID);
         longOperation.End(redirectURL);
     }
 }
Beispiel #16
0
 protected void EndOperation(SPLongOperation operation, string result)
 {
     HttpContext context = HttpContext.Current;
     if (context.Request.QueryString["IsDlg"] != null)
     {
         context.Response.Write("<script type='text/javascript'>alert('" + result + "'); window.frameElement.commitPopup();</script>");
         context.Response.Flush();
         context.Response.End();
     }
     else
     {
         string url = SPContext.Current.Web.Url;
         operation.End(url, SPRedirectFlags.CheckUrl, context, string.Empty);
     }
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                {
                    longOperation.LeadingHTML  = "Pasting items from your work box clipboard";
                    longOperation.TrailingHTML = "If you are pasting a lot of items this might take some time.";

                    longOperation.Begin();


                    String folderPath = Request.QueryString["RootFolder"];
                    if (String.IsNullOrEmpty(folderPath))
                    {
                        folderPath = "";
                    }

                    String docLibraryFolderPath = WorkBox.Web.ServerRelativeUrl + "/" + WorkBox.DocumentLibrary.RootFolder.Url;

                    WBLogging.Generic.Unexpected("Root folder was: " + folderPath + "     in : " + WorkBox.DocumentLibrary.RootFolder.Url);
                    WBLogging.Generic.Unexpected("docLibraryFolderPath =  " + docLibraryFolderPath);

                    folderPath = folderPath.Replace(docLibraryFolderPath, "");

                    WBLogging.Generic.Unexpected("Now using folder path: " + folderPath);


                    WBUser user = new WBUser(WorkBox);

                    String clipboardAction = user.PasteClipboard(WorkBox, folderPath);

                    /*
                     * String justReturnOK = "Pasted items are still on clipboard to be copied again.";
                     * if (clipboardAction == WBUser.CLIPBOARD_ACTION__CUT)
                     * {
                     *  justReturnOK = "Pasted items removed from original location and clipboard.";
                     * }
                     */

                    string okPageUrl   = "WorkBoxFramework/GenericOKPage.aspx";
                    string queryString = "justRefreshOK=True";

                    longOperation.End(okPageUrl, SPRedirectFlags.RelativeToLayoutsPage, Context, queryString);
                }
            }
        }
Beispiel #18
0
        protected void ButtonGebruikers_Click(object sender, EventArgs e)
        {
            // Validate
            this.Validate();

            if (!this.IsValid)
            {
                return;
            }

            // We are valid
            // Register the database
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                string nummer = tbx_verenigingsnummer.Text;
                if (!string.IsNullOrWhiteSpace(nummer))
                {
                    int  pageNum     = 1;
                    bool moreRecords = true;
                    while (moreRecords)
                    {
                        try
                        {
                            moreRecords = ServiceClient.GebruikersUpdate("12073385", nummer, pageNum, true);
                            pageNum++;
                        }
                        catch (Exception)
                        {
                            moreRecords = true;
                        }
                    }

                    try
                    {
                        ClubCloud_Vereniging vereniging = ServiceClient.GetVerenigingByNummer("12073385", nummer, true);
                        ServiceClient.LidmaatschappenUpdate("12073385", vereniging.Id, true);
                    }
                    catch { }
                }

                operation.End(string.Format(CultureInfo.InvariantCulture, "/_admin/ClubCloud.Service/ManageMetaData.aspx?id={0}", SPHttpUtility.UrlKeyValueEncode(this.ServiceApplication.Id)));
            }
        }
Beispiel #19
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void OkButton_Click(object sender, EventArgs e)
        {
            this.Validate();

            if (this.IsValid)
            {
                using (SPLongOperation operation = new SPLongOperation(this))
                {
                    operation.Begin();
                    this.ServiceApplication.Name = this.textBoxServiceName.Text.Trim();
                    IisWebServiceApplicationPoolSection iisSection = this.applicationPoolSection as IisWebServiceApplicationPoolSection;
                    this.ServiceApplication.ApplicationPool = iisSection.GetOrCreateApplicationPool();
                    this.ServiceApplication.Update();
                    operation.EndScript("window.frameElement.commitPopup();");
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonInstallServiceInstances_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ManageServiceInstallServiceInstancesOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ManageServiceInstallServiceInstancesOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                // Get the service
                ClubCloudService service = ClubCloudService.GetOrCreateService();

                // Create the service instances
                ClubCloudServiceInstance.CreateServiceInstances(service);

                operation.End("/_admin/ClubCloud.Service/ManageService.aspx");
            }
        }
Beispiel #21
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonInstallServiceInstances_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = HttpContext.GetGlobalResourceObject("NVRConfigService.ServiceAdminResources", "ManageServiceInstallServiceInstancesOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("NVRConfigService.ServiceAdminResources", "ManageServiceInstallServiceInstancesOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                // Get the service
                NVRConfigService service = NVRConfigService.GetOrCreateService();

                // Create the service instances
                ConfigServiceInstance.CreateServiceInstances(service);

                operation.End("/_admin/NVRConfigService/ManageService.aspx");
            }
        }
Beispiel #22
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonInstallService_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = HttpContext.GetGlobalResourceObject("NVRConfigService.ServiceAdminResources", "ManageServiceInstallOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("NVRConfigService.ServiceAdminResources", "ManageServiceInstallOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                // Install the service
                NVRConfigService service = NVRConfigService.GetOrCreateService();

                // Install the service instances but do not start (provision) them (let the admin do this on the services on server screen).
                ConfigServiceInstance.CreateServiceInstances(service);

                // Install the service proxy
                ConfigServiceProxy.GetOrCreateServiceProxy();

                operation.End("/_admin/NVRConfigService/ManageService.aspx");
            }
        }
        /// <summary>
        /// Sets the inital values of controls
        /// </summary>
        /// <param name="e">Event arguments</param>
        protected override void OnLoad(EventArgs e)
        {
            try
            {
                using (SPLongOperation longOp = new SPLongOperation(this.Page))
                {
                    longOp.LeadingHTML = "Provisioning your WebSite";
                    //longOp.TrailingHTML = "This may take few seconds.";

                    WaitForJobs(longOp);

                    EndOperation(longOp);
                }
            }
            catch (ThreadAbortException) { /* Thrown when redirected */ }
            catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(ex.ToString());
            }
        }
Beispiel #24
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonInstallService_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ManageServiceInstallOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "ManageServiceInstallOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                // Install the service
                ClubCloudService service = ClubCloudService.GetOrCreateService();

                // Install the service instances but do not start (provision) them (let the admin do this on the services on server screen).
                ClubCloudServiceInstance.CreateServiceInstances(service);

                // Install the service proxy
                ClubCloudServiceProxy.GetOrCreateServiceProxy();

                operation.End("/_admin/ClubCloud.Service/ManageService.aspx");
            }
        }
        private void UpdateServiceAppProxy()
        {
            Log.Info(LogCategory.ServiceApplication, "Update MyCorp Service Application Proxy");
            using (var operation = new SPLongOperation(this))
            {
                operation.Begin();
                try
                {
                    if (SPFarm.Local == null)
                    {
                        throw new NullReferenceException("SPFarm.Local");
                    }

                    var service = MCServiceUtility.GetLocalService(true);

                    // Retrieve the service applicaton
                    var serviceApplicationProxy = MCServiceUtility.GetApplicationProxyById(ServiceAppProxyId);
                    if (serviceApplicationProxy == null)
                    {
                        throw new SPException("Unable to find application proxy to edit");
                    }

                    var newName      = this.txtServiceApplicationProxyName.Text.Trim();
                    var newProxyName = newName.Replace(" Proxy", "") + " Proxy";

                    serviceApplicationProxy.Name                 = newProxyName;
                    serviceApplicationProxy.CloseTimeout         = TimeSpan.FromSeconds(Convert.ToDouble(txtCloseChannelTimeout.Text));
                    serviceApplicationProxy.OpenTimeout          = TimeSpan.FromSeconds(Convert.ToDouble(txtOpenChannelTimeout.Text));
                    serviceApplicationProxy.ReceiveTimeout       = TimeSpan.FromSeconds(Convert.ToDouble(txtReceiveChannelTimeout.Text));
                    serviceApplicationProxy.SendTimeout          = TimeSpan.FromSeconds(Convert.ToDouble(txtSendChannelTimeout.Text));
                    serviceApplicationProxy.MaximumExecutionTime = Convert.ToUInt32(txtMaximumExecutionTime.Text);
                    serviceApplicationProxy.Update();
                }
                catch (Exception ex)
                {
                    Log.ErrorFormat(LogCategory.ServiceApplication, "Updating service application proxy error: {0}", ex.Message);
                    Log.Exception(LogCategory.ServiceApplication, ex);
                    throw new SPException("Failed to update service applicaton proxy", ex);
                }
            }
        }
 protected void EndOperation(SPLongOperation operation)
 {
     try
     {
         HttpContext context = HttpContext.Current;
         if (context.Request.QueryString["IsDlg"] != null)
         {
             context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
             context.Response.Flush();
             context.Response.End();
         }
         else
         {
             string url = SPContext.Current.Web.Url;
             operation.End(url, SPRedirectFlags.CheckUrl, context, string.Empty);
         }
     }
     catch (ThreadAbortException) { /* Thrown when redirected */ }
     catch (Exception ex)
     {
         SPUtility.TransferToErrorPage(ex.ToString());
     }
 }
        protected void BtnSave_Click(object sender, EventArgs e) {
            using (SPLongOperation longOperation = new SPLongOperation(this.Page)) {
                longOperation.LeadingHTML = "Working on it...";
                longOperation.TrailingHTML = "Working on it...";
                longOperation.Begin();

                if (!string.IsNullOrEmpty(JsonString.Value)) {
                    var pageLayouts = JsonHelper.JsonDeserialize<IEnumerable<FabricPageLayout>>(JsonString.Value);
                    Set(SPControlMode.New, pageLayouts.FirstOrDefault());
                    //Set(SPControlMode.Edit, pageLayouts.FirstOrDefault());
                    //Set(SPControlMode.Display, pageLayouts.FirstOrDefault());
                }

                var redirectURL = HttpContext.Current.Request.Url.AbsoluteUri;
                longOperation.End(redirectURL);
            }
        }
Beispiel #28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["selectedItemsIDsString"] != null && Request.QueryString["selectedListGUID"] != null)
                {
                    String clipboardAction = Request.QueryString["clipboardAction"];
                    if (String.IsNullOrEmpty(clipboardAction))
                    {
                        clipboardAction = WBUser.CLIPBOARD_ACTION__COPY;
                    }

                    using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                    {
                        string justReturnOK = "Copied to clipboard";
                        longOperation.LeadingHTML = "Copying details to the clipboard";

                        if (clipboardAction == WBUser.CLIPBOARD_ACTION__CUT)
                        {
                            justReturnOK = "Cut to clipboard";
                            longOperation.LeadingHTML = "Cutting details to the clipboard";
                        }

                        longOperation.TrailingHTML = "";

                        longOperation.Begin();

                        string   selectedListGUID = Request.QueryString["selectedListGUID"];
                        string[] selectedItemsIDs = Request.QueryString["selectedItemsIDsString"].ToString().Split('|');

                        WBUtils.logMessage("The list GUID was: " + selectedListGUID);
                        selectedListGUID = selectedListGUID.Substring(1, selectedListGUID.Length - 2).ToLower();

                        // Guid sourceListGuid = new Guid(selectedListGUID);
                        //ListGUID.Value = sourceListGuid.ToString();
                        //ItemID.Value = selectedItemsIDs[1].ToString();

                        //WBUtils.logMessage("The ListGUID was: " + ListGUID.Value);
                        //WBUtils.logMessage("The ItemID was: " + ItemID.Value);
                        // SPDocumentLibrary sourceDocLib = (SPDocumentLibrary)WorkBox.Web.Lists[sourceListGuid];

                        WBUser user = new WBUser(WorkBox);

                        WorkBox.Web.AllowUnsafeUpdates = true;
                        String error = user.AddToClipboard(clipboardAction, WorkBox, selectedItemsIDs, false);
                        WorkBox.Web.AllowUnsafeUpdates = false;

                        string okPageUrl   = "WorkBoxFramework/GenericOKPage.aspx";
                        string queryString = "justReturnOK=" + justReturnOK;

                        if (!String.IsNullOrEmpty(error))
                        {
                            queryString = "justReturnError=" + error;
                        }

                        longOperation.End(okPageUrl, SPRedirectFlags.RelativeToLayoutsPage, Context, queryString);
                    }

                    RenderClipboard();
                }
                else
                {
                    ItemsOnClipboard.Text = "There was an error with the passed through values";
                }

                closeButton.Focus();
            }
        }
Beispiel #29
0
        public int SendMail()
        {
            int processed = 0;

            using (SPLongOperation operation = new SPLongOperation(this.Parent))
            {
                operation.Begin();

                using (new SPMonitoredScope("Mailing SendMail"))
                {
                    if (SPContext.Current.Web.CurrentUser != null)
                    {
                        try
                        {
                            if (ZimbraConfiguration == null)
                            {
                                return(0);
                            }

                            SmtpClient client = new SmtpClient(ZimbraConfiguration.Server.SendMailHost, zimbraconfiguration.Server.SendMailPort);
                            client.Credentials    = new System.Net.NetworkCredential(ZimbraConfiguration.Server.SendMailUserName, ZimbraConfiguration.Server.SendMailPassword);
                            client.DeliveryMethod = SmtpDeliveryMethod.Network;
                            client.DeliveryFormat = SmtpDeliveryFormat.International;
                            //client.SendCompleted += client_SendCompleted;

                            bool more          = true;
                            int  startRowIndex = SelectOnlineVersions() - 10;
                            int  maximumRows   = 200;
                            int  totalrows     = 0;

                            List <Parameter>          collection  = new List <Parameter>();
                            ClubCloud_Vereniging_View queryresult = null;

                            while (more)
                            {
                                try
                                {
                                    queryresult = Client.GetVerenigingenByQuery("00000000", Guid.NewGuid(), new DataSourceSelectArguments {
                                        MaximumRows = maximumRows, StartRowIndex = startRowIndex, RetrieveTotalRowCount = true, SortExpression = ""
                                    }, collection);

                                    if (queryresult != null && queryresult.ClubCloud_Vereniging != null)
                                    {
                                        totalrows = queryresult.TotalRowCount;

                                        foreach (ClubCloud_Vereniging vereniging in queryresult.ClubCloud_Vereniging)
                                        {
                                            if (vereniging.Nummer == "09399" || vereniging.Nummer == "61424")
                                            {
                                                continue;
                                            }

                                            try
                                            {
                                                int nummer;
                                                if (int.TryParse(vereniging.Nummer, out nummer))
                                                {
                                                    MailMessage message = BuidMailMessage(vereniging);

                                                    if (message == null)
                                                    {
                                                        continue;
                                                    }

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

                                                    if (!string.IsNullOrWhiteSpace(vereniging.EmailKNLTB))
                                                    {
                                                        emails.Add(vereniging.EmailKNLTB);
                                                    }

                                                    if (!string.IsNullOrWhiteSpace(vereniging.EmailOverig))
                                                    {
                                                        emails.Add(vereniging.EmailKNLTB);
                                                    }

                                                    if (!string.IsNullOrWhiteSpace(vereniging.EmailWebSite))
                                                    {
                                                        emails.Add(vereniging.EmailWebSite);
                                                    }

                                                    foreach (string email in emails.Distinct())
                                                    {
                                                        try
                                                        {
                                                            //message.To.Add(new MailAddress("*****@*****.**","Rutger Hemrika", Encoding.UTF8));
                                                            message.To.Add(new MailAddress(email.ToLower(), vereniging.Naam, Encoding.UTF8));
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message);
                                                        }
                                                    }

                                                    message.CC.Add(new MailAddress("*****@*****.**", "ClubCloud"));
                                                    message.From   = new MailAddress("*****@*****.**", "ClubCloud");
                                                    message.Sender = new MailAddress("*****@*****.**", "ClubCloud");
                                                    message.ReplyToList.Add(new MailAddress("*****@*****.**", "ClubCloud"));
                                                    message.Priority = MailPriority.Normal;
                                                    message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess | DeliveryNotificationOptions.Delay;

                                                    message.Subject = string.Format("ClubCloud : De slimme keuze voor {0}", vereniging.Naam);

                                                    try
                                                    {
                                                        HostingEnvironment.QueueBackgroundWorkItem(ct => Email.SendAsync(message, client));
                                                        //Email.Send(message, client);
                                                        Thread.Sleep(100);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message);
                                                    }
                                                    finally
                                                    {
                                                        //message.Dispose();
                                                    }

                                                    Thread.Sleep(200);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message);
                                            }
                                        }
                                    }

                                    processed     += maximumRows;
                                    startRowIndex += maximumRows;

                                    if (processed >= totalrows || (queryresult != null && queryresult.ClubCloud_Vereniging.Count == 0))
                                    {
                                        more = false;
                                    }

                                    //more = false;
                                }
                                catch (Exception ex)
                                {
                                    Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message);
                                }
                                //selectArgs = new DataSourceSelectArguments { MaximumRows = maximumRows, StartRowIndex = startRowIndex, RetrieveTotalRowCount = false, SortExpression = "" };
                                //queryresult = Client.GetVerenigingenByQuery("00000000", Guid.NewGuid(), new DataSourceSelectArguments { MaximumRows = maximumRows, StartRowIndex = startRowIndex, RetrieveTotalRowCount = false, SortExpression = "" }, collection);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.WriteLog(Logger.Category.Unexpected, ex.Source, ex.Message);
                        }
                    }
                }
                operation.End(this.Parent.Request.Url.AbsolutePath);
            }
            return(processed);
        }
Beispiel #30
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonOk_Click(object sender, EventArgs e)
        {
            // Validate
            this.Validate();

            if (!this.IsValid)
            {
                return;
            }

            // We are valid
            // Register the database
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML  = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("ClubCloud.Service.ServiceAdminResources", "UsersSettingsCreateOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                var name = fup_package.PostedFile.FileName.Split('\\').Last();

                string[] parts           = name.Split('_');
                string   applicationName = parts[0];
                string   verion          = parts[1];
                string   cpu             = parts[2];

                ClubCloud.Model.ApplicationInfo applicationInfo = ServiceClient.GetApplicationInfoByName(applicationName);

                if (applicationInfo == null)
                {
                    applicationInfo = new Model.ApplicationInfo {
                        ApplicationName = applicationName, MajorVersion = verion, CreationDate = DateTime.Now, OperationDate = DateTime.Now, Status = ApplicationStatus.Published
                    };
                }
                else
                {
                    applicationInfo.MajorVersion  = verion;
                    applicationInfo.OperationDate = DateTime.Now;
                }

                Stream uploadstream = fup_package.PostedFile.InputStream;
                fup_package.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
                byte[] fileData = new byte[fup_package.PostedFile.ContentLength];
                uploadstream.Read(fileData, 0, fup_package.PostedFile.ContentLength);

                byte[] package     = null;
                byte[] certificate = null;
                byte[] symbols     = null;

                ApplicationVersion applicationVersion = new ApplicationVersion();
                ApplicationProcessorArchitecture applicationProcessorArchitecture = new ApplicationProcessorArchitecture();

                using (ZipArchive archive = new ZipArchive(uploadstream, ZipArchiveMode.Read))
                {
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        byte[] buffer = null;
                        using (BinaryReader reader = new BinaryReader(entry.Open()))
                        {
                            buffer = reader.ReadBytes((int)entry.Length);
                        }

                        if (entry.FullName.EndsWith("appx"))
                        {
                            package = buffer;
                            PackageAnalyzeResult result = PackageAnalyzer.GetPackageInfo(entry.Open());
                            applicationVersion = result.ApplicationVersion;
                            applicationProcessorArchitecture = result.ApplicationProcessorArchitecture;
                        }

                        if (entry.FullName.EndsWith("cer"))
                        {
                            certificate = buffer;
                        }

                        if (entry.FullName.EndsWith("appxsym"))
                        {
                            symbols = buffer;
                        }
                    }
                }
                applicationProcessorArchitecture.Certificate = certificate;
                applicationProcessorArchitecture.Package     = package;
                applicationProcessorArchitecture.Symbols     = symbols;

                //applicationVersion.ApplicationProcessorArchitectures.Add(applicationProcessorArchitecture);
                //applicationInfo.ApplicationVersions.Add(applicationVersion);

                applicationInfo = ServiceClient.SetApplicationInfo(applicationInfo);
                applicationVersion.ApplicationInfoId = applicationInfo.Id;
                applicationVersion = ServiceClient.SetApplicationVersion(applicationInfo.Id, applicationVersion);
                applicationProcessorArchitecture.ApplicationVersionId = applicationVersion.Id;
                applicationProcessorArchitecture = ServiceClient.SetApplicationProcessorArchitecture(applicationVersion.Id, applicationProcessorArchitecture);

                operation.End("/_admin/ClubCloud.Service/ManagePackage.aspx");//string.Format(CultureInfo.InvariantCulture, "/_admin/ClubCloud.Service/ManageApplication.aspx?id={0}", SPHttpUtility.UrlKeyValueEncode(this.ServiceApplication.Id)));
            }
        }
        /// <summary>
        /// Creates the service application.
        /// </summary>
        private void CreateApplication()
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = HttpContext.GetGlobalResourceObject("NVRRepoService.ServiceAdminResources", "CreateOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("NVRRepoService.ServiceAdminResources", "CreateOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                try
                {
                    RepoService service = RepoService.GetOrCreateService();
                    RepoServiceProxy serviceProxy = RepoServiceProxy.GetOrCreateServiceProxy();

                    // Create the application pool
                    IisWebServiceApplicationPoolSection applicationPoolSectionCasted = this.applicationPoolSection as IisWebServiceApplicationPoolSection;
                    SPIisWebServiceApplicationPool applicationPool = applicationPoolSectionCasted.GetOrCreateApplicationPool();

                    // Create the service application
                    RepoServiceApplication application = new RepoServiceApplication(
                        this.textBoxServiceName.Text.Trim(),
                        service,
                        applicationPool);
                    application.Update();
                    application.Provision();

                    // Create the service application proxy
                    RepoServiceApplicationProxy proxy = new RepoServiceApplicationProxy(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            HttpContext.GetGlobalResourceObject("NVRRepoService.ServiceAdminResources", "ServiceApplicationProxyNameTemplate", CultureInfo.CurrentCulture).ToString(),
                            this.textBoxServiceName.Text.Trim()),
                        serviceProxy,
                        application.Uri);
                    proxy.Update();
                    proxy.Provision();

                    if (this.checkBoxIncludeInDefaultProxy.Checked)
                    {
                        SPServiceApplicationProxyGroup group = SPServiceApplicationProxyGroup.Default;
                        group.Add(proxy);
                        group.Update();
                    }

                    operation.EndScript("window.frameElement.commitPopup();");
                }
                catch (Exception ex)
                {
                    SPUtility.TransferToErrorPage(ex.ToString());
                }
            }
        }
Beispiel #32
0
        private void onSave(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                try
                {
                    SaveButton      btnSave  = sender as SaveButton;
                    StringBuilder   sbErrors = new StringBuilder();
                    SPLongOperation longOp   = new SPLongOperation(this.Page);
                    longOp.LeadingHTML = "Please wait while the new case data is saved.";
                    longOp.Begin();
                    try
                    {
                        //SaveButton.SaveItem(btnSave.ItemContext, false, "");
                        bool isSaveSuccessful = false;
                        isSaveSuccessful = SaveButton.SaveItem(btnSave.ItemContext, false, "");
                        if (isSaveSuccessful == false)
                        {
                            sbErrors.Append("An error occurred.");
                        }
                    }
                    catch (SPException spex)
                    {
                        sbErrors.Append("An error occurred: " + spex.Message);
                    }
                    catch (Exception ex)
                    {
                        sbErrors.Append("An error occurred: " + ex.Message);
                    }

                    if (SPContext.Current.IsPopUI)
                    {
                        if (sbErrors.Length > 0)
                        {
                            sbErrors.Append("<br/><br/>Please <a href='#' onclick='history.go(-1);return false;'>go back</a> and try again.");
                            longOp.EndScript("document.getElementById('s4-simple-card-content').innerHTML = \"<br/>Errors have occurred during the submission. Details: <br/>" + sbErrors.ToString() + " \";");
                        }
                        else
                        {
                            longOp.EndScript("try { window.frameElement.commitPopup(); } catch (e) {}");
                        }
                    }
                    else
                    {
                        if (sbErrors.Length > 0)
                        {
                            SPUtility.TransferToErrorPage(sbErrors.ToString());
                        }
                        else
                        {
                            longOp.End(SPContext.Current.Web.Url, SPRedirectFlags.DoNotEndResponse | SPRedirectFlags.Trusted, HttpContext.Current, "");
                        }
                    }
                }
                catch (ThreadAbortException) { /* Thrown when redirected */ }
                catch (Exception ex)
                {
                    SPUtility.TransferToErrorPage(ex.ToString());
                }
            }
        }
        protected new void CreateButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation.Begin(delegate(SPLongOperation longOperation)
                {
                    SPWeb web = SPContext.Current.Web;
                    PublishingWeb currentPublishingWeb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPage publishingPage      = null;
                    SPFolder sPFolder = null;
                    if (!string.IsNullOrEmpty(folderUrl))
                    {
                        sPFolder = currentPublishingWeb.Web.GetFolder(folderUrl);
                        if (!sPFolder.Exists)
                        {
                            string url = Helper.ConcatUrls(folderUrl, nameInput.Text);
                            SPUtility.CreateParentFoldersForFile(currentPublishingWeb.PagesList, url, false);
                            sPFolder = currentPublishingWeb.Web.GetFolder(folderUrl);
                        }
                    }
                    PageLayout pageLayout = null;
                    string text           = base.Request.QueryString.Get("PLUrl");
                    if (string.IsNullOrEmpty(text))
                    {
                        pageLayout = currentPublishingWeb.DefaultPageLayout;
                    }
                    else
                    {
                        try
                        {
                            pageLayout = new PageLayout(base.Web.GetListItem(text));
                        }
                        catch (Exception)
                        {
                            Logger.ToLog(new Exception(string.Format("Unable to create PageLayout from listitem of path : {0}", text)));
                            pageLayout = currentPublishingWeb.DefaultPageLayout;
                        }
                    }
                    publishingPage = SPHelper.CreatePublishingPage(currentPublishingWeb, nameInput.Text, pageLayout, sPFolder, false);
                    if (publishingPage != null && originalRequestedName != null)
                    {
                        publishingPage.Title = originalRequestedName;
                        publishingPage.ListItem["NewsType"] = ddlNewsType.SelectedValue;
                        publishingPage.Update();
                    }

                    string text2     = SPHttpUtility.UrlPathEncode(publishingPage.ListItem.File.ServerRelativeUrl, false);
                    string FinishUrl = SPHelper.DesignModeUrl(text2);

                    if (!string.IsNullOrEmpty(base.Request.QueryString.Get("IsDlg")))
                    {
                        if (base.Request.QueryString["shouldRedirectPage"] == "0")
                        {
                            string scriptLiteralToEncode = SPHelper.ConvertToAbsoluteUrl(FinishUrl, currentPublishingWeb.Web.Site, true);
                            longOperation.EndScript("window.frameElement.commitPopup('" + SPHttpUtility.EcmaScriptStringLiteralEncode(scriptLiteralToEncode) + "');");
                        }
                        else
                        {
                            longOperation.EndScript("window.frameElement.navigateParent('" + SPHttpUtility.EcmaScriptStringLiteralEncode(FinishUrl) + "');");
                        }
                    }
                    else
                    {
                        longOperation.End(FinishUrl);
                    }
                });
            }
        }
Beispiel #34
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void OkButton_Click(object sender, EventArgs e)
        {
            this.Validate();

            if (this.IsValid)
            {
                using (SPLongOperation operation = new SPLongOperation(this))
                {
                    operation.Begin();
                    this.ServiceApplication.Name = this.textBoxServiceName.Text.Trim();
                    IisWebServiceApplicationPoolSection iisSection = this.applicationPoolSection as IisWebServiceApplicationPoolSection;
                    this.ServiceApplication.ApplicationPool = iisSection.GetOrCreateApplicationPool();
                    this.ServiceApplication.Update();
                    operation.EndScript("window.frameElement.commitPopup();");
                }
            }
        }
Beispiel #35
0
        protected void createNewButton_OnClick(object sender, EventArgs e)
        {
            Hashtable metadataProblems = checkMetadataState();

            if (metadataProblems.Count > 0)
            {
                RecordsTypeFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__RECORDS_TYPE].WBxToString();

                FunctionalAreaFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__FUNCTIONAL_AREA].WBxToString();

                WorkBoxShortTitleMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__WORK_BOX_SHORT_TITLE].WBxToString();

                ReferenceIDMessage.Text    = metadataProblems[WorkBox.COLUMN_NAME__REFERENCE_ID].WBxToString();;
                ReferenceDateMessage.Text  = metadataProblems[WorkBox.COLUMN_NAME__REFERENCE_DATE].WBxToString();;
                SeriesTagFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__SERIES_TAG].WBxToString();

                OwningTeamFieldMessage.Text    = metadataProblems[WorkBox.COLUMN_NAME__OWNING_TEAM].WBxToString();
                InvolvedTeamsFieldMessage.Text = metadataProblems[WorkBox.COLUMN_NAME__INVOLVED_TEAMS].WBxToString();

                pageRenderingRequired = true;
            }
            else
            {
                pageRenderingRequired = false;
            }

            // The event should only be processed if there is no other need to render the page again
            if (pageRenderingRequired)
            {
                renderPage();
            }
            else
            {
                WBCollection collection = new WBCollection(WorkBoxCollectionUrl.Value);

                collection.Web.AllowUnsafeUpdates = true;

                WBUtils.logMessage("OK so we've set to allow unsafe updates of the WorkBoxCollectionWeb");

                string selectedWorkBoxTemplateValue = WorkBoxTemplateID.Value;
                if (selectedWorkBoxTemplateValue == "")
                {
                    selectedWorkBoxTemplateValue = WorkBoxTemplates.SelectedValue;
                }

                int templateID = Convert.ToInt32(selectedWorkBoxTemplateValue);

                WBTemplate template = collection.GetTypeByID(templateID);


                WBTeam owningTeam = new WBTeam(teams, OwningTeamUIControlValue.Value);
                WBTermCollection <WBTeam> involvedTeams = new WBTermCollection <WBTeam>(teams, InvolvedTeamsField.Text);

                Hashtable extraValues = null;
                extraValues = new Hashtable();

                if (ReferenceID.Text != "")
                {
                    extraValues.Add(WorkBox.COLUMN_NAME__REFERENCE_ID, ReferenceID.Text);
                }

                if (!ReferenceDate.IsDateEmpty)
                {
                    extraValues.Add(WorkBox.COLUMN_NAME__REFERENCE_DATE, ReferenceDate.SelectedDate);
                }

                if (SeriesTagDropDownList.SelectedValue != "")
                {
                    extraValues.Add(WorkBox.COLUMN_NAME__SERIES_TAG, SeriesTagDropDownList.SelectedValue);
                }

                if (functionalAreaFieldIsEditable)
                {
                    extraValues.Add(WorkBox.COLUMN_NAME__FUNCTIONAL_AREA, FunctionalAreaField.Text);
                }
                else
                {
                    extraValues.Add(WorkBox.COLUMN_NAME__FUNCTIONAL_AREA, workBoxRecordsType.DefaultFunctionalArea(functionalAreas).UIControlValue);
                }

                WBLogging.Generic.Unexpected("Owning team has values: " + owningTeam.Name + " " + owningTeam.Id);
                WorkBox newWorkBox = collection.RequestNewWorkBox(WorkBoxShortTitle.Text, "", template, owningTeam, involvedTeams, extraValues);

                if (newWorkBox == null)
                {
                    string pageTitle = Uri.EscapeDataString("Failed to create new work box");
                    string pageText  = Uri.EscapeDataString("Your request to create a new work box was not successful.");

                    string redirectUrl = "WorkBoxFramework/GenericOKPage.aspx";
                    string queryString = "pageTitle=" + pageTitle + "&pageText=" + pageText;

                    SPUtility.Redirect(redirectUrl, SPRedirectFlags.RelativeToLayoutsPage, Context, queryString);
                }


                collection.Web.AllowUnsafeUpdates = false;

                using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                {
                    longOperation.LeadingHTML  = "Creating your new work box.";
                    longOperation.TrailingHTML = "Please wait while the work box is being created.";

                    longOperation.Begin();


                    newWorkBox.Open("Requested via NewWorkBox.aspx.");

                    if (relatedWorkBox != null)
                    {
                        switch (RelationType.Value)
                        {
                        case WorkBox.RELATION_TYPE__DYNAMIC:
                            break;

                        case WorkBox.RELATION_TYPE__MANUAL_LINK:
                        {
                            relatedWorkBox.LinkToWorkBox(newWorkBox, WorkBox.RELATION_TYPE__MANUAL_LINK);
                            break;
                        }

                        case WorkBox.RELATION_TYPE__CHILD:
                        {
                            relatedWorkBox.LinkToWorkBox(newWorkBox, WorkBox.RELATION_TYPE__CHILD);
                            newWorkBox.LinkToWorkBox(relatedWorkBox, WorkBox.RELATION_TYPE__PARENT);
                            break;
                        }

                        default:
                        {
                            WBUtils.shouldThrowError("Did not recognise the relation type: " + RelationType.Value);
                            break;
                        }
                        }

                        relatedWorkBox.Dispose();
                    }
                    collection.Dispose();

                    string html = "<h1>Successfully created</h1><p>Your new work box has been successfully created.</p>";

                    html += String.Format("<p>Go to your new work box: <a href=\"#\" onclick=\"javascript: dialogReturnOKAndRedirect('{0}');\">{1}</a></p>",
                                          newWorkBox.Url,
                                          newWorkBox.Title);


                    string pageTitle = Uri.EscapeDataString("Created new work box");
                    string pageText  = Uri.EscapeDataString(html);

                    string okPageUrl = "WorkBoxFramework/GenericOKPage.aspx";

                    string refreshQueryString = "?recordsTypeGUID=" + newWorkBox.RecordsType.Id.ToString();

                    newWorkBox.Dispose();

                    string queryString = "pageTitle=" + pageTitle + "&pageText=" + pageText + "&refreshQueryString=" + refreshQueryString;

                    longOperation.End(okPageUrl, SPRedirectFlags.RelativeToLayoutsPage, Context, queryString);
                }
            }
        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite osite = ((SPSite)properties.Feature.Parent);

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite elevatedSite = new SPSite(osite.ID))
                    {
                        var web = elevatedSite.RootWeb;
                        RemoveEventReceiverFromList(web);
                        SPList list            = web.GetList(web.ServerRelativeUrl + "/_catalogs/masterpage/");
                        bool oldWebAllowUnsafe = web.AllowUnsafeUpdates;
                        web.AllowUnsafeUpdates = true;

                        foreach (SPListItem item in list.Items)
                        {
                            if (item.File.CheckedOutByUser != null)
                            {
                                Page page = HttpContext.Current.Handler as Page;
                                SPLongOperation operation = new SPLongOperation(page);
                                operation.Begin();
                                try
                                {
                                    operation.End("javascript:if(!alert('Cannot activate the feature of tracking, master page: " + Convert.ToString(item["Name"]) + " is checked out by user: "******" (" + item.File.CheckedOutByUser.LoginName + ").')) document.location = window.location.href.substring(0, window.location.href.indexOf('_layouts')) + '_catalogs/masterpage/Forms/AllItems.aspx';", SPRedirectFlags.Static, HttpContext.Current, null);
                                }
                                catch (ThreadAbortException ex)
                                {
                                    Logger.WriteLog(Logger.Category.Information, "Piwik Master page is checked out: " + Convert.ToString(item["Name"]), ex.Message);
                                }
                                catch (Exception ex) { throw ex; }
                            }
                        }

                        foreach (SPListItem item in list.Items)
                        {
                            if (Convert.ToString(item["Name"]).ToLower().EndsWith(".master"))
                            {
                                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                                EventDisabler eventDisabler   = new EventDisabler();
                                SPFile file            = item.File;
                                byte[] byteArrayOfFile = file.OpenBinary();
                                if (byteArrayOfFile.Length > 0)
                                {
                                    string strFileContentsBefore = enc.GetString(byteArrayOfFile);
                                    //check if javascript exists
                                    PropertyBagOperations pbos = new PropertyBagOperations();
                                    string trackerJSScriptUrl  = pbos.GetPropertyValueFromListByKey("piwik_trackerjsscripturl");
                                    if (!strFileContentsBefore.ToLower().Contains(trackerJSScriptUrl.ToLower()))
                                    {
                                        if (item.File.CheckOutType == SPFile.SPCheckOutType.None)
                                        {
                                            SPFileLevel oldLevel = item.File.Level;
                                            string newStr        = AddJSRefToFile(strFileContentsBefore, trackerJSScriptUrl);
                                            byte[] byteArrayFileContentsAfter = null;
                                            if (!newStr.Equals(""))
                                            {
                                                //after binary to string there are ??? chars at the first line, this is the action to replace it:
                                                if (newStr.Substring(0, 3).Equals("???"))
                                                {
                                                    newStr = newStr.Replace("???", "");
                                                }
                                                byteArrayFileContentsAfter = enc.GetBytes(newStr);
                                                eventDisabler.DisableEvents();
                                            }

                                            if (list.ForceCheckout)
                                            {
                                                item.File.CheckOut();
                                            }

                                            item.File.SaveBinary(byteArrayFileContentsAfter);
                                            item.File.Update();

                                            if (list.ForceCheckout)
                                            {
                                                if (item.File.Level == SPFileLevel.Checkout)
                                                {
                                                    if (oldLevel == SPFileLevel.Published)
                                                    {
                                                        item.File.CheckIn("", SPCheckinType.MajorCheckIn);
                                                    }
                                                    else
                                                    {
                                                        item.File.CheckIn("", SPCheckinType.MinorCheckIn);
                                                    }
                                                }
                                            }

                                            try
                                            {
                                                if (oldLevel == SPFileLevel.Published)
                                                {
                                                    if (item.File.DocumentLibrary.EnableModeration)
                                                    {
                                                        item.File.Approve("");
                                                    }
                                                    else
                                                    {
                                                        item.File.Publish("");
                                                    }
                                                }
                                            }
                                            catch (Exception exp)
                                            {
                                                Logger.WriteLog(Logger.Category.Unexpected, "Piwik FeatureActivating publish or approve master", exp.Message);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        CreateOrUpdateValueInPropertyBag("false", web, web.Properties, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);

                        web.AllowUnsafeUpdates = oldWebAllowUnsafe;
                    }
                    bool ifWasntDeactivatingAndActive = true;
                    PropertyBagOperations pbo         = new PropertyBagOperations();
                    Configuration cfg = new Configuration();

                    using (SPSite elevatedSite = new SPSite(cfg.PiwikAdminSiteUrl))
                    {
                        ClientContext context        = new ClientContext(pbo.GetPropertyValueFromListByKey(ConfigValues.PiwikPro_PropertyBag_AdminSiteUrl));
                        ListProcessor sdlo           = new ListProcessor(context, cfg, new SPLogger());
                        ifWasntDeactivatingAndActive = sdlo.AddOrUpdateElementInList(osite.RootWeb.Title, ConfigValues.PiwikPro_SiteDirectory_Column_Status_New, osite.RootWeb.Url, "", osite.RootWeb.ServerRelativeUrl, "");
                    }
                    if (!ifWasntDeactivatingAndActive)
                    {
                        using (SPSite elevatedSite = new SPSite(osite.ID))
                        {
                            var web = elevatedSite.RootWeb;
                            CreateOrUpdateValueInPropertyBag("true", web, web.Properties, ConfigValues.PiwikPro_PropertyBag_PiwikIsTrackingActive);
                        }
                    }
                }
                catch (Exception exc)
                {
                    Logger.WriteLog(Logger.Category.Unexpected, "Piwik FeatureActivating Full in elevated", exc.Message);
                }
            });
        }
 protected void BtnNext_Click(object sender, EventArgs e) {
     using (SPLongOperation longOperation = new SPLongOperation(this.Page)) {
         longOperation.LeadingHTML = "请稍等,这不会花费很长的时间...";
         longOperation.TrailingHTML = "请稍等,这不会花费很长的时间...";
         longOperation.Begin();
         var redirectURL = string.Concat(SPContext.Current.Web.Url, HttpContext.Current.Request.Url.AbsolutePath);
         longOperation.End(redirectURL);
     }
 }
Beispiel #38
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string     action     = string.Empty;
            string     actionDesc = string.Empty;
            LinkButton button     = sender as LinkButton;

            if (button.ID == "btnCopy")
            {
                action     = "copy";
                actionDesc = "copied";
            }
            else if (button.ID == "btnMove")
            {
                action     = "move";
                actionDesc = "moved";
            }
            var    destination   = FormatFileDestination(txtDestination.Text.Trim());
            SPFile fileProcessed = null;

            SPLongOperation longOp = new SPLongOperation(this.Page);

            longOp.LeadingHTML = "Please wait while your file(s) are being " + actionDesc + "...";
            longOp.Begin();

            var fileList = GetSelectedFiles();

            foreach (SPFile file in fileList)
            {
                try
                {
                    if (!SPFileExtensions.Exists(file, destination))
                    {
                        fileProcessed = action == "copy" ? CopyFile(file, destination) : MoveFile(file, destination);
                        Logger.Instance.Info("Processed file " + action + " for: " + fileProcessed.Name + " from " + file.Url + " to " + fileProcessed.Url);
                    }
                    else
                    {
                        Logger.Instance.Error("Error in Batch File Copy/Move: User attempted to copy " + file.Name + " to a location where the file already exists.", DiagnosticsCategories.eCaseWeb);
                        errorMessages = errorMessages == null ? errorMessages = new StringBuilder("Error(s):<br /> " + file.Name + " already exists. <br />") : errorMessages.Append(file.Name + " already exists. <br />");
                        lblItems.Text = null;
                        continue;
                    }
                }
                catch (System.ArgumentException argEx)
                {
                    Logger.Instance.Error("Error in Batch File Copying: " + file.Name, argEx, DiagnosticsCategories.eCaseWeb);
                    errorMessages = errorMessages == null ? errorMessages = new StringBuilder("Error(s):<br />The file you are trying to copy does not exist. <br />") : errorMessages.Append("The file you are trying to copy does not exist. <br />");
                    lblItems.Text = null;
                    continue;
                }
                catch (System.IO.FileNotFoundException fnfEx)
                {
                    Logger.Instance.Error("Error in Batch File Copying: " + file.Name, fnfEx, DiagnosticsCategories.eCaseWeb);
                    errorMessages = errorMessages == null ? errorMessages = new StringBuilder("Error(s):<br />The file you are trying to copy could not be found. <br />") : errorMessages.Append("The file you are trying to copy could not be found. <br />");
                    lblItems.Text = null;
                    continue;
                }
                catch (Exception ex)
                {
                    Logger.Instance.Error("Error in Batch File Copying: " + file.Name, ex, DiagnosticsCategories.eCaseWeb);
                    errorMessages = errorMessages == null ? errorMessages = new StringBuilder("Error(s):<br />This URL contains invalid characters. <br />") : errorMessages.Append("This URL contains invalid characters. <br />");
                    lblItems.Text = null;
                    continue;
                }
            }
            //show any error messages that we have
            lblErrors.Text = errorMessages == null ? null : errorMessages.ToString();

            if ((errorMessages == null || errorMessages.Length == 0))
            {
                //close the modal
                // Response.Write(string.Format(CultureInfo.InvariantCulture, "<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, '{0}');</script>", treeViewSelectedDocs.Nodes.Count));
                // Response.Flush();
                // Response.End();
                string strScript = "try { alert('File(s) " + actionDesc + " successfully.'); window.frameElement.commitPopup(); } catch (e) {}";
                if (SPContext.Current.IsPopUI)
                {
                    longOp.EndScript(strScript);
                }
            }
            else
            {
                errorMessages.Append("<br/><br/>Please <a href='#' onclick='history.go(-1);return false;'>go back</a> and try again.");
                longOp.EndScript("document.getElementById('s4-simple-card-content').innerHTML = \"<br/><br/><br/><h4>Errors have occurred during the submission.</h4>" + errorMessages.ToString() + " \";");
            }
        }
Beispiel #39
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string localID = Request.QueryString["LocalID"];

            if (localID == null || localID == "")
            {
                localID = Request.QueryString["IASClientID"];
            }


            if (localID == null || localID == "")
            {
                ErrorMessage.Text = "Could not find the LocalID on the request parameters.";
                return;
            }

            bool   justFind       = false;
            string justFindString = Request.QueryString["JustFind"];

            if (justFindString != null && justFindString != "")
            {
                WBUtils.logMessage("Testing JustFind = " + justFindString);

                justFind = true.ToString().ToLower().Equals(justFindString.ToLower());

                WBUtils.logMessage("Testing justFind = " + justFind);
                WBUtils.logMessage("true.ToString() = " + true.ToString());
            }
            else
            {
                WBUtils.logMessage("No JustFind query parameter");
            }

            using (WBCollection collection = new WBCollection(SPContext.Current))
            {
                WorkBox workBox = collection.FindByLocalID(localID);

                if (workBox == null)
                {
                    WBUtils.logMessage(" workBox was NULL");
                }

                if (workBox == null && justFind)
                {
                    string html = "<h3>There is no work box with ID: " + localID + "</h3>\n";

                    html += "<a href=\"routing.aspx?LocalID=" + localID + "&justFind=false\">Click here to create a new work box with this ID</a>\n";

                    DoesNotExistYet.Text = html;
                }
                else
                {
                    using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                    {
                        if (workBox == null)
                        {
                            longOperation.LeadingHTML  = "No documents found: creating new work box.";
                            longOperation.TrailingHTML = "This service user doesn't yet have a work box so it is being created.";
                        }
                        else
                        {
                            longOperation.LeadingHTML  = "Found service user's work box.";
                            longOperation.TrailingHTML = "Please wait while the work box is opened.";
                        }

                        longOperation.Begin();

                        collection.Site.AllowUnsafeUpdates = true;
                        collection.Web.AllowUnsafeUpdates  = true;
                        if (workBox == null)
                        {
                            workBox = collection.RequestNewWorkBox("", localID);
                        }

                        if (workBox.HasBeenCreated)
                        {
                            workBox.Web.AllowUnsafeUpdates = true;
                        }

                        if (!workBox.HasBeenOpened)
                        {
                            workBox.Open();
                        }

                        string workBoxUrl = workBox.Url;

                        workBox.Web.AllowUnsafeUpdates     = false;
                        collection.Web.AllowUnsafeUpdates  = false;
                        collection.Site.AllowUnsafeUpdates = false;

                        workBox.Dispose();

                        longOperation.End(workBoxUrl, SPRedirectFlags.Static, Context, "");
                    }
                }
            }
        }
Beispiel #40
0
        /// <summary>
        /// Click event.
        /// </summary>
        /// <param name="sender">The Sender.</param>
        /// <param name="e">The EventArgs.</param>
        protected void ButtonRemoveService_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = HttpContext.GetGlobalResourceObject("NVRConfigService.ServiceAdminResources", "ManageServiceRemoveOperationLeadingHtml", CultureInfo.CurrentCulture).ToString();
                operation.TrailingHTML = HttpContext.GetGlobalResourceObject("NVRConfigService.ServiceAdminResources", "ManageServiceRemoveOperationTrailingHtml", CultureInfo.CurrentCulture).ToString();
                operation.Begin();

                NVRConfigService.RemoveService();

                operation.End("/_admin/NVRConfigService/ManageService.aspx");
            }
        }
        protected void OnOkButtonClick(object sender, EventArgs e)
        {
            if (Page.IsValid && _applicationPool != null)
            {
                if (ServiceApplicationID == Guid.Empty)
                {
                    ParagoServiceApplication      serviceApplication      = null;
                    ParagoServiceApplicationProxy serviceApplicationProxy = null;

                    using (SPLongOperation operation = new SPLongOperation(this))
                    {
                        operation.Begin();

                        try
                        {
                            string name = ServiceApplicationNameTextBox.Text.Trim();

                            serviceApplication = ParagoServiceApplication.Create(name, ParagoService.Local, _applicationPool);

                            if (serviceApplication == null)
                            {
                                throw new NullReferenceException("ParagoServiceApplication");
                            }

                            serviceApplication.UpdateSettingInternal(ParagoServiceSettings.Code.Key, "PARAGO");

                            serviceApplication.Update(true);
                            serviceApplication.Provision();

                            serviceApplicationProxy = (ParagoServiceApplicationProxy)ParagoService.Local.CreateProxy(name, true, serviceApplication, null);

                            if (serviceApplicationProxy == null)
                            {
                                throw new NullReferenceException("ParagoServiceApplicationProxy");
                            }

                            serviceApplicationProxy.Update(true);
                            serviceApplicationProxy.Provision();

                            ServiceHelper.SetDefaultServiceApplicationProxy(serviceApplicationProxy);

                            serviceApplicationProxy.Update(true);

                            SendResponseForPopUI();
                        }
                        catch (Exception ex)
                        {
                            if (serviceApplicationProxy != null)
                            {
                                serviceApplicationProxy.Unprovision();
                                serviceApplicationProxy.Delete();
                            }

                            if (serviceApplication != null)
                            {
                                serviceApplication.Unprovision();
                                serviceApplication.Delete();
                            }

                            throw new SPException("Failed to create Parago Service Application", ex);
                        }
                    }
                }
                else
                {
                    ParagoServiceApplication serviceApplication = GetServiceApplication();
                    UpdateSettings(serviceApplication);
                    serviceApplication.Update(true);

                    SendResponseForPopUI();
                }
            }
        }
        private void PostFile()
        {
            bool thumbUploaded = false, posterUploaded = false;
            string destFolder = mediaConfig.TempLocationFolder;
            var originFileInfo = new FileInfo(FileToUpload.PostedFile.FileName);
            try
            {

                using (SPLongOperation longOperation = new SPLongOperation(this.Page))
                {
                    SPWeb web = SPContext.Current.Web;
                    MediaAsset asset = MediaAsset.FromFile(originFileInfo, SPContext.Current.Web.Url, mediaConfig);
                    longOperation.Begin();

                    asset.FileSize = FileToUpload.PostedFile.ContentLength;

                    var validator = ValidatorFactory.GetValidator(asset.MediaType, mediaConfig);
                    validator.ValidateFileSize(asset.FileSize);
                    IAssetStorageManager storage = AssetStorageFactory.GetStorageManager("Media", web.Url);
                    string newFileUniqueNameWithoutExtension = Guid.NewGuid().ToString();
                    string newFileUniqueName = String.Concat(newFileUniqueNameWithoutExtension, originFileInfo.Extension);

                    //upload optional images
                    if (ThumbnailInput.PostedFile != null && !String.IsNullOrEmpty(ThumbnailInput.PostedFile.FileName))
                    {
                        string thumbFileName = MediaConfig.GetThumbnailFileName(newFileUniqueNameWithoutExtension, ThumbnailInput.PostedFile.FileName);
                        asset.Thumbnail = storage.Save(thumbFileName, ThumbnailInput.PostedFile.InputStream);
                        thumbUploaded = true;
                    }
                    if (PosterInput.PostedFile != null && !String.IsNullOrEmpty(PosterInput.PostedFile.FileName))
                    {
                        string posterFileName = MediaConfig.GetPosterFileName(newFileUniqueNameWithoutExtension, PosterInput.PostedFile.FileName);
                        asset.Poster = storage.Save(posterFileName, PosterInput.PostedFile.InputStream);
                        posterUploaded = true;
                    }
                    //upload principal file
                    if (asset.MediaType == MediaType.Image)
                    {
                        if (!thumbUploaded)//no thumb image was uploaded
                        {
                            //generate thumb & save
                            ImageProcessor imgProc = new ImageProcessor();
                            using (MemoryStream thumbStream = new MemoryStream())
                            {
                                string thumbFileName = MediaConfig.GetThumbnailFileName(newFileUniqueNameWithoutExtension);
                                imgProc.GenerateThumbnail(FileToUpload.PostedFile.InputStream, thumbStream);
                                thumbStream.Position = 0;
                                asset.Thumbnail = storage.Save(thumbFileName, thumbStream);
                            }
                            FileToUpload.PostedFile.InputStream.Position = 0;
                        }
                        //save to final location
                        asset.Location = storage.Save(newFileUniqueName, FileToUpload.PostedFile.InputStream);
                        asset.Status = ProcessingStatus.Success;
                    }
                    else
                    {
                        var tempFileInfo = new FileInfo(Path.Combine(destFolder, newFileUniqueName));

                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            //save to file system
                            FileToUpload.PostedFile.SaveAs(tempFileInfo.FullName);
                            asset.TempLocation = tempFileInfo.FullName;
                            asset.Duration = MediaLengthCalculator.GetMediaLength(tempFileInfo);
                        });
                        try
                        {
                            validator.ValidateLength(asset.Duration);
                        }
                        catch (MediaTooLargeException)
                        {
                            FileUtils.Delete(tempFileInfo);
                            throw;
                        }
                        if (asset.MediaType == MediaType.Audio)
                        {
                            asset.Location = storage.Save(newFileUniqueName, FileToUpload.PostedFile.InputStream);
                            FileUtils.Delete(tempFileInfo);
                            asset.TempLocation = String.Empty;
                            if (!thumbUploaded)//no thumb image was uploaded, upload default
                            {
                                string thumbnailFileName = MediaConfig.GetThumbnailFileName(newFileUniqueNameWithoutExtension, mediaConfig.DefaultAudioThumbnail);
                                SPFile thumbImg = web.GetFile(mediaConfig.DefaultAudioThumbnail);
                                asset.Thumbnail = storage.Save(thumbnailFileName, thumbImg.OpenBinaryStream());
                            }
                            if (!posterUploaded)//no poster image was uploaded, upload default
                            {
                                string posterFileName = MediaConfig.GetPosterFileName(newFileUniqueNameWithoutExtension, mediaConfig.DefaultAudioPoster);
                                SPFile thumbImg = web.GetFile(web.Url + mediaConfig.DefaultAudioPoster);
                                asset.Poster = storage.Save(posterFileName, thumbImg.OpenBinaryStream());
                            }
                            asset.Status = ProcessingStatus.Success;
                        }
                        else if (asset.MediaType == MediaType.Video && !mediaConfig.EncodeVideoFlag && thumbUploaded && posterUploaded)
                        {
                            //video doesn't need encoding, nor generation of thumb and poster images => upload file and set status as processed.
                            asset.Location = storage.Save(newFileUniqueName, FileToUpload.PostedFile.InputStream);
                            FileUtils.Delete(tempFileInfo);
                            asset.TempLocation = String.Empty;
                            asset.Status = ProcessingStatus.Success;
                        }
                    }
                    var list = web.Lists[mediaConfig.MediaAssetsListName];
                    int id;
                    string contentTypeId;
                    mediaRepository.Insert(list, asset, out id, out contentTypeId);
                    string url = String.Format("{0}?ID={1}&ContentTypeId={2}", list.DefaultEditFormUrl, id, contentTypeId);
                    longOperation.End(url);
                }
            }
            catch (ThreadAbortException) { /* Thrown when redirected */}
            catch (Exception ex)
            {
                logger.LogToOperations(ex, LogCategories.Media, EventSeverity.Error, "Error uploading media '{0}'", FileToUpload.PostedFile.FileName);
                SPUtility.TransferToErrorPage(ex.ToString());
            }
        }
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            try
            {

            SPSecurity.RunWithElevatedPrivileges(() =>
            {

                //operation.EndScript("SP.UI.ModalDialog.commonModalDialogClose(1, 'Submitted');");
                #region Create document
                if (!String.IsNullOrEmpty(Configuration.ServiceURL) && !String.IsNullOrEmpty(Configuration.ProjectUID))
                {
                    if (DataRepository.P14Login(((string)SPContext.Current.Web.Properties[Constants.PROPERTY_NAME_DB_SERVICE_URL])))
                    {
                        Utility.WriteLog("Successful P14 Login to the system for Document creation stage", System.Diagnostics.EventLogEntryType.Information);
                        using (var operation = new SPLongOperation(this))
                        {
                            try
                            {
                                operation.LeadingHTML = "<b>Document creation in Progress...</b>";
                                operation.TrailingHTML = "";
                                operation.Begin();
                                var docName = this.txtDocumentName.Text + ".pptx";
                                var docLib = this.Web.Lists[this.ListId];
                                var templateFile = this.Web.GetFile(Constants.TEMPLATE_FILE_LOCATION);
                                PMMP.PMPDocument document = new PMMP.PMPDocument();
                                var stream = document.CreateDocument("Presentation", templateFile.OpenBinary(), Configuration.ProjectUID);

                                SPListItem item = docLib.RootFolder.Files.Add(docName, stream, true).Item;

                                var pmmContentType = (from SPContentType ct in docLib.ContentTypes
                                                      where ct.Name.ToLower() == Constants.CT_PMM_NAME.ToLower()
                                                      select ct).FirstOrDefault();

                                if (pmmContentType != null)
                                {
                                    item[SPBuiltInFieldId.ContentTypeId] = pmmContentType.Id;
                                    item[Constants.FieldId_Comments] = txtComment.Text;
                                    item.Update();
                                }

                            }
                            catch (Exception ex)
                            {
                                this.ShowErrorMessage(ex);
                                SPUtility.TransferToErrorPage(ex.ToString());
                            }
                            finally
                            {
                                EndOperation(operation);
                            }

                        }
                    }
                    else
                    {
                        Utility.WriteLog("An error has ocurred in trying to P14 Login to the system", System.Diagnostics.EventLogEntryType.Error);
                        this.ShowErrorMessage("An error has ocurred in trying to P14 Login to the system");
                    }
                }
                else
                {
                    this.ShowErrorMessage("An error has ocurred trying to get the configuration parameters");
                    Utility.WriteLog("An error has ocurred trying to get the configuration parameters", System.Diagnostics.EventLogEntryType.Error);
                }
                #endregion

            });
            }
            catch (Exception ex)
            {
                this.ShowErrorMessage(ex);
            }
            this.pnlSubmit.Visible = true;
        }