public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager)
        {
            SPQuery qry = new SPQuery();

               qry.Query = String.Format(CultureInfo.CurrentCulture,
               "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
               webPartName);

               SPList webPartGallery = null;

               if (null == web.ParentWeb)
               {
               webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
               }

               else
               {
               webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
               }

               SPListItemCollection webParts = webPartGallery.GetItems(qry);

               XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());

               string errorMsg;

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

               return webPart;
        }
Exemple #2
0
        public static WebPart CreateWebPart(this SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, out string errorMsg)
        {
            var query = new SPQuery
            {
                Query = String.Format(CultureInfo.CurrentCulture,
                                      "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                                      webPartName),
                RowLimit = 1
            };

            SPList webPartGallery = web.IsRootWeb
                                        ? web.GetCatalog(SPListTemplateType.WebPartCatalog)
                                        : web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);

            SPListItemCollection webParts = webPartGallery.GetItems(query);

            if (webParts.Count == 0)
            {
                throw new SPException(string.Format("Web Part \"{0}\" not found in the gallery.", webPartName));
            }

            using (Stream stream = webParts[0].File.OpenBinaryStream())
            {
                XmlReader xmlReader = new XmlTextReader(stream);
                WebPart   webPart   = webPartManager.ImportWebPart(xmlReader, out errorMsg);
                xmlReader.Close();
                return(webPart);
            }
        }
Exemple #3
0
    /// <summary> 
    /// Adds the web part to the page from a definition. 
    /// </summary> 
    /// <param name="manager">The web part manager.</param> 
    /// <param name="definition">The web part definition.</param> 
    /// <param name="zone">The web part zone.</param> 
    /// <param name="index">The zone index.</param> 
    protected void AddWebPart(SPLimitedWebPartManager manager, string definition, string zone, int index)
    {
      // Guard 
      if (manager == null)
      {
        throw new ArgumentNullException("manager");
      }

            if (Web == null)
      {
        throw new InvalidOperationException("You must call EnsureContext method before calling this method.");
      }

            string data = Web.GetFileAsString(definition);
      if (data != null)
      {
        WebPart webPart;
                using (var reader = new StringReader(data))
        {
          string errorMessage;
                    var xmlTextReader = new XmlTextReader(reader);
          webPart = manager.ImportWebPart(xmlTextReader, out errorMessage);
          if (webPart == null)
          {
            throw new WebPartPageUserException(errorMessage);
          }
        }

        manager.AddWebPart(webPart, zone, index);
      }
    }
        internal static WebPart AddWebPart(SPLimitedWebPartManager manager, SPFile file, string webPartXml, Hashtable customReplaceText)
        {
            WebPart       wp;
            XmlTextReader reader = null;

            try
            {
                webPartXml = webPartXml.Replace("${siteCollection}", file.Item.ParentList.ParentWeb.Site.Url);
                webPartXml = webPartXml.Replace("${site}", file.Item.ParentList.ParentWeb.Url);
                webPartXml = webPartXml.Replace("${webTitle}", HttpUtility.HtmlEncode(file.Item.ParentList.ParentWeb.Title));
                if (customReplaceText != null)
                {
                    foreach (string key in customReplaceText.Keys)
                    {
                        webPartXml = webPartXml.Replace(key, HttpUtility.HtmlEncode(customReplaceText[key].ToString()));
                    }
                }
                reader = new XmlTextReader(new StringReader(webPartXml));

                string err;
                wp = manager.ImportWebPart(reader, out err);
                if (!string.IsNullOrEmpty(err))
                {
                    throw new Exception(err);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return(wp);
        }
Exemple #5
0
        /// <summary>
        /// Creates the web part.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param nme="webPartName">Name of the web part.</param>
        /// <param name="webPartManager">The web part manager.</param>
        /// <returns></returns>
        public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, bool isHidden)
        {
            SPQuery qry = new SPQuery();

            qry.Query = String.Format(CultureInfo.CurrentCulture,
                                      "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                                      webPartName);
            SPList webPartGallery = null;

            if (web.ParentWeb == null)
            {
                webPartGallery = web.GetCatalog(
                    SPListTemplateType.WebPartCatalog);
            }
            else
            {
                webPartGallery = web.Site.RootWeb.GetCatalog(
                    SPListTemplateType.WebPartCatalog);
            }

            SPListItemCollection webParts = webPartGallery.GetItems(qry);

            XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
            string    errorMsg;

            System.Web.UI.WebControls.WebParts.WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);
            webPart.Hidden = isHidden;

            return(webPart);
        }
        public static void DeleteAllThenAddWebPartToPage(SPFile page, string wpXml, string wpZone)
        {
            using (SPLimitedWebPartManager wpMgr = page.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
            {
                // Delete all web parts
                // Play the shell game because you can't delete from a collection in an enumerator
                List <WebPart> wpList = new List <WebPart>();
                foreach (WebPart wp in wpMgr.WebParts)
                {
                    wpList.Add(wp);
                }
                foreach (WebPart wp in wpList)
                {
                    wpMgr.DeleteWebPart(wp);
                }

                // Add our new web part
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(wpXml);
                using (XmlNodeReader reader = new XmlNodeReader(doc))
                {
                    string errorMessage = null;
                    System.Web.UI.WebControls.WebParts.WebPart wp = wpMgr.ImportWebPart(reader, out errorMessage);
                    wpMgr.AddWebPart(wp, wpZone, wp.ZoneIndex);
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="wpmngr"></param>
        /// <param name="webpartName"></param>
        /// <returns></returns>
        private System.Web.UI.WebControls.WebParts.WebPart GetWebPartToAdd(SPLimitedWebPartManager wpmngr, string webpartName)
        {
            // string sLayoutshive = SPUtility.GetGenericSetupPath("TEMPLATE\\LAYOUTS\\RSG.INSIDE.KMTTEMPLATEWEBPARTS\\WEBPARTS\\");
            string     sLayoutshive    = "C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\15\\TEMPLATE\\LAYOUTS\\RSG.INSIDE.KMTTEMPLATEWEBPARTS\\WEBPARTS\\";
            string     webpartFilePath = sLayoutshive + webpartName;
            FileStream file            = File.OpenRead(webpartFilePath);

            string error = string.Empty;

            System.Web.UI.WebControls.WebParts.WebPart webpart = wpmngr.ImportWebPart(XmlReader.Create(file), out error);

            return(webpart);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="wpmngr"></param>
        /// <param name="webpartName"></param>
        /// <returns></returns>
        private System.Web.UI.WebControls.WebParts.WebPart GetWebPartToAdd(SPLimitedWebPartManager wpmngr, string webpartName, string cityName, string lobValue)
        {
            //string sLayoutshive = SPUtility.GetGenericSetupPath("15\\TEMPLATE\\LAYOUTS\\RSG.INSIDE.KMTTEMPLATEWEBPARTS\\WEBPARTS\\");
            string     sLayoutshive    = "C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\15\\TEMPLATE\\LAYOUTS\\RSG.INSIDE.KMTTEMPLATEWEBPARTS\\WEBPARTS\\";
            string     webpartFilePath = sLayoutshive + webpartName;
            FileStream file            = File.OpenRead(webpartFilePath);

            string error = string.Empty;

            System.Web.UI.WebControls.WebParts.WebPart webpart = wpmngr.ImportWebPart(XmlReader.Create(file), out error);
            if (lobValue != string.Empty)
            {
                ((RSG.Inside.KMTTemplateWebParts.TopDocumentsFromDocumentLibrary.TopDocumentsFromDocumentLibrary)(webpart)).LOBColumnValue          = lobValue;
                ((RSG.Inside.KMTTemplateWebParts.TopDocumentsFromDocumentLibrary.TopDocumentsFromDocumentLibrary)(webpart)).CityorEntityColumnValue = cityName;
            }

            return(webpart);
        }
Exemple #9
0
        private System.Web.UI.WebControls.WebParts.WebPart CreateWebPartByFileName(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
        {
            SPQuery query = new SPQuery();

            query.Query = string.Format(CultureInfo.InvariantCulture, "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>", webPartName);

            SPList webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);

            SPListItemCollection webParts = webPartGallery.GetItems(query);

            System.Web.UI.WebControls.WebParts.WebPart webPart = null;
            if (webParts.Count > 0)
            {
                XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                string    errorMessage;
                webPart = manager.ImportWebPart(xmlReader, out errorMessage);
            }

            return(webPart);
        }
Exemple #10
0
 private void btn_Import_Click(object sender, EventArgs e)
 {
     using (SPSite site = new SPSite(siteUrl))
     {
         using (SPWeb web = site.OpenWeb(webUrl))
         {
             SPFile thePage = web.GetFile(pageUrl);
             SPLimitedWebPartManager theWebPartManager = thePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
             string[]  webParts = Directory.GetFiles(tb_ImportPath.Text);
             XmlReader xReader  = null;
             System.Web.UI.WebControls.WebParts.WebPart wp = null;
             for (int i = 0; i < webParts.Length; i++)
             {
                 string customError = string.Empty;
                 xReader = new XmlTextReader(webParts[i]);
                 wp      = theWebPartManager.ImportWebPart(xReader, out customError);
                 theWebPartManager.AddWebPart(wp, "Rich Content", 1);
                 tb_Message.Text += wp.Title + "Import Success...";
             }
         }
     }
 }
        public SPWebPartInstance ImportWebPart(Base64EncodedByteArrayInstance webPart)
        {
            if (webPart == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A byte array must be supplied as the first argument.");
            }


            using (var ms = new MemoryStream(webPart.Data))
            {
                var    reader = XmlReader.Create(ms);
                string errorMessage;
                var    result = m_limitedWebPartManager.ImportWebPart(reader, out errorMessage) as WebPart;

                if (errorMessage.IsNullOrWhiteSpace() == false)
                {
                    throw new JavaScriptException(this.Engine, "Error", errorMessage);
                }

                return(result == null
                    ? null
                    : new SPWebPartInstance(this.Engine.Object.InstancePrototype, result));
            }
        }
Exemple #12
0
 private void btn_AddToPage_Click(object sender, EventArgs e)
 {
     using (SPSite site = new SPSite(siteUrl))
     {
         using (SPWeb web = site.OpenWeb(webUrl))
         {
             SPFile thePage = web.GetFile(pageUrl);
             SPLimitedWebPartManager theWebPartManager = thePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
             string  webPartName = cBox_WebPart.SelectedItem.ToString();
             SPQuery qry         = new SPQuery();
             qry.Query = String.Format(CultureInfo.CurrentCulture, "<Where><Eq><FieldRef Name=\"FileLeafRef\" /><Value Type=\"Text\">{0}</Value></Eq></Where>", webPartName);
             SPList webPartGallery = null;
             if (null == web.ParentWeb)
             {
                 webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
             }
             else
             {
                 webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
             }
             SPListItemCollection webParts = webPartGallery.GetItems(qry);
             if (webParts.Count == 0)
             {
                 tb_Message.Text += "Can't find " + webPartName + "...";
             }
             else
             {
                 XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                 string    errorMsg;
                 System.Web.UI.WebControls.WebParts.WebPart webPart = theWebPartManager.ImportWebPart(xmlReader, out errorMsg);
                 theWebPartManager.AddWebPart(webPart, "Rich Content", 1);
                 tb_Message.Text += "Add " + webPartName + " Success...";
             }
         }
     }
 }
        /// <summary>
        /// Adds the web part to the page from a definition.
        /// </summary>
        /// <param name="manager">The web part manager.</param>
        /// <param name="definition">The web part definition.</param>
        /// <param name="zone">The web part zone.</param>
        /// <param name="index">The zone index.</param>
        protected void AddWebPart(SPLimitedWebPartManager manager, string definition, string zone, int index)
        {
            // Guard
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            if (this.Web == null)
            {
                throw new InvalidOperationException("You must call EnsureContext method before calling this method.");
            }

            string data = this.Web.GetFileAsString(definition);
            if (data != null)
            {
                WebPart webPart;
                using (StringReader reader = new StringReader(data))
                {
                    string errorMessage;
                    XmlTextReader xmlTextReader = new XmlTextReader(reader);
                    webPart = manager.ImportWebPart(xmlTextReader, out errorMessage);
                    if (webPart == null)
                    {
                        throw new WebPartPageUserException(errorMessage);
                    }
                }

                manager.AddWebPart(webPart, zone, index);
            }
        }
        protected void TabContainerRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            // Panel is the place holder to show web parts in a tab.
            Panel panel = (Panel)e.Item.FindControl("TabContainer");

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (panel != null)
                {
                    using (SPLimitedWebPartManager wpManager = SPContext.Current.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
                    {
                        try
                        {
                            // Elevated previleges required for EXPORT and IMPORT. Else Users with normal read access will get errors.
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                // Retrieve the web part titles in the ConfigureTabs XML string for this tab.
                                var webPartTitles = from t in xDocument.Descendants("webPart")
                                                    where (string)t.Parent.Attribute("name") == (string)e.Item.DataItem
                                                    select(string) t.Attribute("title");

                                foreach (string wpTitle in webPartTitles)
                                {
                                    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wpManager.WebParts)
                                    {
                                        // Find the matched closed web part in WebParts collection
                                        if (webPart.Title == wpTitle && webPart.IsClosed == true)
                                        {
                                            string errorMessage;
                                            MemoryStream stream  = new MemoryStream();
                                            XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);

                                            // Export the closed webpart to a memory stream.
                                            wpManager.ExportWebPart(webPart, writer);

                                            writer.Flush();
                                            stream.Position = 0;

                                            XmlTextReader reader = new XmlTextReader(stream);

                                            // Import the exported webpart.
                                            System.Web.UI.WebControls.WebParts.WebPart newWebPart = wpManager.ImportWebPart(reader, out errorMessage);

                                            reader.Close();
                                            writer.Close();

                                            // Show the imported webpart.
                                            panel.Controls.Add(newWebPart);
                                            break;
                                        }
                                    }
                                }
                            });
                        }
                        catch (Exception ex)
                        {
                            // For debugging use only.
                            Label label = new Label();
                            label.Text = "Please check your XML configuration for error. " + Environment.NewLine + ex.Message;
                            panel.Controls.Add(label);
                        }
                    }
                }
            }
        }
Exemple #15
0
        private System.Web.UI.WebControls.WebParts.WebPart CreateWebPartByFileName(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
        {
            SPQuery query = new SPQuery();
            query.Query = string.Format(CultureInfo.InvariantCulture, "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>", webPartName);

            SPList webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);

            SPListItemCollection webParts = webPartGallery.GetItems(query);

            System.Web.UI.WebControls.WebParts.WebPart webPart = null;
            if (webParts.Count > 0)
            {
                XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                string errorMessage;
                webPart = manager.ImportWebPart(xmlReader, out errorMessage);
            }

            return webPart;
        }
Exemple #16
0
 private void AddGroupUsers(string pageUrl, string zoneId, string Title, string Description)
 {
     try
     {
         SPSecurity.RunWithElevatedPrivileges(delegate()
         {
             using (SPSite sharepointSite = new SPSite(pageUrl))
             {
                 using (SPWeb sharepointWeb = sharepointSite.OpenWeb())
                 {
                     sharepointWeb.AllowUnsafeUpdates = true;
                     SPFile file = sharepointWeb.GetFile(pageUrl);
                     if (null != file)
                     {
                         using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                         {
                             if (null != mgr)
                             {
                                 SPQuery query         = new SPQuery();
                                 query.Query           = String.Format(CultureInfo.CurrentCulture, "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>wp_AddGroupUsers</Value></Eq></Where>");
                                 SPList webPartGallery = sharepointWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                                 SPListItemCollection webPartGalCol = webPartGallery.GetItems(query);
                                 XmlReader xmlReader = new XmlTextReader(webPartGalCol[0].File.OpenBinaryStream());
                                 string errorMessage;
                                 System.Web.UI.WebControls.WebParts.WebPart SiteProcertForm = mgr.ImportWebPart(xmlReader, out errorMessage);
                                 SiteProcertForm.Title       = Title;
                                 SiteProcertForm.Description = Description;
                                 SiteProcertForm.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                                 SiteProcertForm.ChromeType  = System.Web.UI.WebControls.WebParts.PartChromeType.None;
                                 mgr.AddWebPart(SiteProcertForm, "", SiteProcertForm.ZoneIndex);
                                 sharepointWeb.Update();
                             }
                         }
                     }
                 }
             }
         });
     }
     catch (Exception ex)
     {
         ex.ToString();
     }
 }
Exemple #17
0
        public static WebPart FindWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager, string webPartListName)
        {
            try
            {
                SPSite spSite = new SPSite(web.Url);
                SPWeb spWeb = spSite.RootWeb;

                SPQuery query = new SPQuery();
                query.Query = String.Format(CultureInfo.CurrentCulture,
                    "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
                    webPartName);

                SPList webPartGallery = spWeb.Lists[webPartListName];
                if (null == spWeb.ParentWeb)
                {
                    webPartGallery = spWeb.GetCatalog(
                       SPListTemplateType.WebPartCatalog);
                }
                else
                {
                    webPartGallery = spWeb.Site.RootWeb.GetCatalog(
                       SPListTemplateType.WebPartCatalog);
                }
                SPListItemCollection webParts = webPartGallery.GetItems(query);

                if (webParts.Count == 0)
                {
                    EssnLog.logInfo(String.Format("Web part with name {0} is not exist on SpWeb {1}", webPartName, spWeb.Url));
                    return null; //check if webpart exist
                }

                XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
                string errorMessage;
                WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
                webPart.ChromeType = PartChromeType.BorderOnly;
                return webPart;
            }
            catch (Exception ee)
            {
                EssnLog.logInfo("Error on FindWebPart in FeatureActivated.");
                EssnLog.logExc(ee);
                return null;
            }
        }
Exemple #18
0
        private static System.Web.UI.WebControls.WebParts.WebPart ResolveWebPartInstance(SPSite site,
                                                                                         SPLimitedWebPartManager webPartManager,
                                                                                         WebPartDefinition webpartModel)
        {
            System.Web.UI.WebControls.WebParts.WebPart webpartInstance = null;

            if (!string.IsNullOrEmpty(webpartModel.WebpartType))
            {
                var webPartType = Type.GetType(webpartModel.WebpartType);
                webpartInstance = Activator.CreateInstance(webPartType) as System.Web.UI.WebControls.WebParts.WebPart;
            }
            else if (!string.IsNullOrEmpty(webpartModel.WebpartFileName))
            {
                var webpartFileName = webpartModel.WebpartFileName;
                var rootWeb         = site.RootWeb;

                // load definition from WP catalog
                var webpartCatalog = rootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                var webpartItem    = webpartCatalog.Items.OfType <SPListItem>().FirstOrDefault(
                    i => string.Compare(i.Name, webpartFileName, true) == 0);

                if (webpartItem == null)
                {
                    throw new ArgumentException(string.Format("webpartItem. Can't find web part file with name: {0}", webpartFileName));
                }

                using (var streamReader = new MemoryStream(webpartItem.File.OpenBinary()))
                {
                    using (var xmlReader = XmlReader.Create(streamReader))
                    {
                        var errMessage = string.Empty;
                        webpartInstance = webPartManager.ImportWebPart(xmlReader, out errMessage);

                        if (!string.IsNullOrEmpty(errMessage))
                        {
                            throw new ArgumentException(
                                      string.Format("Can't import web part foe with name: {0}. Error: {1}", webpartFileName, errMessage));
                        }
                    }
                }
            }
            else if (!string.IsNullOrEmpty(webpartModel.WebpartXmlTemplate))
            {
                var stringBytes = Encoding.UTF8.GetBytes(webpartModel.WebpartXmlTemplate);

                using (var streamReader = new MemoryStream(stringBytes))
                {
                    using (var xmlReader = XmlReader.Create(streamReader))
                    {
                        var errMessage = string.Empty;
                        webpartInstance = webPartManager.ImportWebPart(xmlReader, out errMessage);

                        if (!string.IsNullOrEmpty(errMessage))
                        {
                            throw new ArgumentException(
                                      string.Format("Can't import web part for XML template: {0}. Error: {1}",
                                                    webpartModel.WebpartXmlTemplate, errMessage));
                        }
                    }
                }
            }
            else
            {
                throw new Exception("Either WebpartType or WebpartFileName or WebpartXmlTemplate needs to be defined.");
            }

            return(webpartInstance);
        }
Exemple #19
0
        public static System.Web.UI.WebControls.WebParts.WebPart ResolveWebPartInstance(SPSite site,
           SPLimitedWebPartManager webPartManager,
           WebPartDefinition webpartModel)
        {
            System.Web.UI.WebControls.WebParts.WebPart webpartInstance = null;

            if (!string.IsNullOrEmpty(webpartModel.WebpartType))
            {
                var webPartType = Type.GetType(webpartModel.WebpartType);
                webpartInstance = Activator.CreateInstance(webPartType) as System.Web.UI.WebControls.WebParts.WebPart;
            }
            else if (!string.IsNullOrEmpty(webpartModel.WebpartFileName))
            {
                var webpartFileName = webpartModel.WebpartFileName;
                var rootWeb = site.RootWeb;

                // load definition from WP catalog
                var webpartCatalog = rootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
                var webpartItem = webpartCatalog.Items.OfType<SPListItem>().FirstOrDefault(
                        i => string.Compare(i.Name, webpartFileName, true) == 0);

                if (webpartItem == null)
                    throw new ArgumentException(string.Format("webpartItem. Can't find web part file with name: {0}", webpartFileName));

                using (var streamReader = new MemoryStream(webpartItem.File.OpenBinary()))
                {
                    using (var xmlReader = XmlReader.Create(streamReader))
                    {
                        var errMessage = string.Empty;
                        webpartInstance = webPartManager.ImportWebPart(xmlReader, out errMessage);

                        if (!string.IsNullOrEmpty(errMessage))
                            throw new ArgumentException(
                                string.Format("Can't import web part foe with name: {0}. Error: {1}", webpartFileName, errMessage));
                    }
                }
            }
            else if (!string.IsNullOrEmpty(webpartModel.WebpartXmlTemplate))
            {
                var stringBytes = Encoding.UTF8.GetBytes(webpartModel.WebpartXmlTemplate);

                using (var streamReader = new MemoryStream(stringBytes))
                {
                    using (var xmlReader = XmlReader.Create(streamReader))
                    {
                        var errMessage = string.Empty;
                        webpartInstance = webPartManager.ImportWebPart(xmlReader, out errMessage);

                        if (!string.IsNullOrEmpty(errMessage))
                            throw new ArgumentException(
                                string.Format("Can't import web part for XML template: {0}. Error: {1}",
                                webpartModel.WebpartXmlTemplate, errMessage));
                    }
                }
            }
            else
            {
                throw new Exception("Either WebpartType or WebpartFileName or WebpartXmlTemplate needs to be defined.");
            }

            return webpartInstance;
        }