Search code examples
asp.netimportwebformsdevexpressweb-parts

Importing a asp.net webPart in WebForm website from .Webpart file programmatically (Not a sharePoint Project)


We have created several user Controls (Ascx) that we render to a webpart zone. Similarly, we have a control containing WebPartManager which is implemented in all the .aspx pages.

I am working on a feature where it is required to Import generated .webpart file on any page using a file upload control. I am Using devExpress fileUpload control and upon FileUploadComplete Event executing the below-mentioned code. The code Runs without any error but also doesn't display any web-part in the specified zone. Which is the problem.

 protected void WebPartUploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            string ErrorMessge = string.Empty;
            if (e.UploadedFile.IsValid)
            {
                var xmlReader = XmlReader.Create(e.UploadedFile.FileContent);
                xmlReader.Read();

                System.Web.UI.WebControls.WebParts.WebPart webPart = wpManager.ImportWebPart(xmlReader, out ErrorMessge);

                       wpManager.AddWebPart(webPart, wpManager.Zones["Zone5"], 1);
            }


        }

I might be missing some fundamental code. If anybody knows the answer kindly help. Thanks .


Solution

  • I finally figured out the issue. Just in case if someone in future come across a similar problem, this will help.

    So, The problem here is the Devexpress File-Upload control is an ajax control, making partial postback thus not updating the CatalogZone of the page which is out of its scope.

    The way to deal with it is :

    1. Create a new .WebPart file and clone the content of the uploaded file.
    2. Re-direct to the same page which fires Page_Load event
    3. Execute the above code in the page_Load Event in order to import.

    Below is the code to explain just that :

    WebPartUploadControl_FileUploadComplete

            protected void WebPartUploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
            {
    
    String WebPartFilePath = Server.MapPath("DirectoryWhereYouWantTosaveCloneFile");
                String WebPartFileName = "NameOfYourCloneFile.WebPart";
                
                string FileContent = string.Empty;
    
                Creating Directory to store data of uploaded file(.webPart).
    
                Session["ImportWebPartFilePath"] = $"{WebPartFilePath}/{WebPartFileName}";
                if (!Directory.Exists(WebPartFilePath))
                {
                    Directory.CreateDirectory(WebPartFilePath);
                }
    
                Reading Uploaded file Data
    
                using (StreamReader sr = new StreamReader(e.UploadedFile.FileContent))
                {
                    FileContent = sr.ReadToEnd();
                }
    
                //Copying File Data to the newly Created file 
    
                if (!File.Exists(Session["ImportWebPartFilePath"].ToString()))
                {
                    File.AppendAllText(WebPartFilePath + "/" + WebPartFileName, FileContent);
                }
    
                e.CallbackData = "Page Settings Imported Successfully.";
    
                // Response.Redirect(Request.RawUrl) does not work in while ajax callback in 
                   devexpress
                // Creating a callback to current page to trigger Page_Load event.
    
                DevExpress.Web.ASPxWebControl.RedirectOnCallback(this.Request.Path);
    }
    

    Page_Load

    if (Session["ImportWebPartFilePath"] != null)
                {
                    //Import Webpart Settings
                    ImportWebPartsToCurrentPage(Session["ImportWebPartFilePath"].ToString());
                    File.Delete(Session["ImportWebPartFilePath"].ToString());
                    Session["ImportWebPartFilePath"] = null;
    
                }
    

    ImportWebPartsToCurrentPage

     private void ImportWebPartsToCurrentPage(String FilePath)
            {
                string ErrorMessge = string.Empty;
                //Extracting All WebParts in the file
                XDocument WebPartXml = XDocument.Load(FilePath);
    
                //Spliting the each webpart.
                var WebPartDescriptions = WebPartXml.Root.Elements();
                try
                {
                    foreach (var WebPartDescription in WebPartDescriptions)
                    {
                        var xmlReader = XmlReader.Create(new StringReader(WebPartDescription.ToString()));
                        xmlReader.Read();
                        // Adding Webpart to page Catalog.
                        System.Web.UI.WebControls.WebParts.WebPart webPart = wpManager.ImportWebPart(xmlReader, out ErrorMessge);
                        //Adding webpart to the page.
                        if (!wpManager.WebParts.Contains(webPart))
                        {
                            wpManager.AddWebPart(webPart, wpManager.Zones["ZoneName"], 0);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex);
    
                }
            }