How to programmatically add webpart to publishing page

How to add visual webpart in publishing page please let me know.
Thanks in advance

public void AddTaskListsWebPart()
            SPLimitedWebPartManager manager = null;
            SPFile file = null;
            try
                SPSecurity.RunWithElevatedPrivileges(delegate()
                    using (SPSite spSite = new SPSite(site id))
                        using (SPWeb spWeb = spSite.OpenWeb())
                            spWeb.AllowUnsafeUpdates = true;
                            file = spWeb.GetFile(pageurl);
                            if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                                file.CheckOut();
                                manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                                if (manager.WebParts.Count <= 0)
                                    TaskLists objTaskLists = new TaskLists(); //Replace
TaskLists with your webpart name
                                    manager.AddWebPart(objTaskLists, "zone1",
0); //replace zoneid and index with yours one.
                                    manager.SaveChanges(objTaskLists);
                                    //pnlTaskLists.Controls.Add(objTaskLists);
                                    file.Update();
                                    file.CheckIn(string.Empty);
                                    file.Publish(string.Empty);
                                    spWeb.Update();
                            spWeb.AllowUnsafeUpdates = false;
            catch (Exception ex)
                Utility.SPTraceLogError(ex); //Handle your error as per your logic
            finally
                if (manager != null)
                    manager.Dispose();

Similar Messages

  • How to place a WebPart in Publishing Page Content

    Hi,
    when you use a publishing page you are able through the ribbon to add existing webparts into the content of the publishing page.
    I would like to add programmatically a webpart into the content of the publishing page. I couldnt find anyting to that question on the web.
    Can someone help?
    regards
    yavuz
    Regards
    Yavuz
    www.ybog.net | Field notes on software development and technology

    Try below:
    http://sharepoint2010mind.blogspot.in/2012/06/add-webpart-programmatically-publishing.html
    http://sharepoint.stackexchange.com/questions/86026/add-programmatically-custom-web-part-to-page-without-web-part-zone
    PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
    string pageName = "NewPage.aspx";
    PageLayout[] pageLayouts = pWeb.GetAvailablePageLayouts();
    PageLayout newPage = pageLayouts[0]; //Body only type of page layout
    PublishingPageCollection pages = pWeb.GetPublishingPages();
    PublishingPage nPage = pages.Add(pageName, newPage);
    nPage.Update();using (SPSite site = new SPSite("http://win2008/sites/publishing"))
    SPWeb web = site.RootWeb;
    SPFile page = web.GetFile("Pages/Lipsum.aspx");
    page.CheckOut();
    using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
    Guid storageKey = Guid.NewGuid();
    string wpId = String.Format("g_{0}", storageKey.ToString().Replace('-', '_'));
    XmlElement p = new XmlDocument().CreateElement("p");
    p.InnerText = "Hello World";
    ContentEditorWebPart cewp = new ContentEditorWebPart
    Content = p,
    ID = wpId
    wpmgr.AddWebPart(cewp, "wpz", 0);
    string marker = String.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"></div></div>", new object[] { storageKey.ToString("D") });
    SPListItem item = page.Item;
    string content = item["PublishingPageContent"] as string;
    item["PublishingPageContent"] = content.Replace("|", marker);
    item.Update();
    page.CheckIn(String.Empty);
    http://sharepoint.stackexchange.com/questions/86026/add-programmatically-custom-web-part-to-page-without-web-part-zone
    http://www.zeemanj.net/?p=291

  • How to programmatically add rectangle to a pdf file ?

    How to programmatically add rectangle to a pdf file ?
    There is several page pdfs, non-vector, black and white.
    Users are color blind and have disabilities.
    To train them, one adds a rectangle at a certain lower-left point and width,height specified for a page.
    The idea is to give the script the page and coordinates and size of rectangle to be added programmatically. Green rectangles are acceptable as the cones are most sensitive there.
    Also, additional feature to add bookmarks on the left in the order these rectangle data is provided to the script.
    The script could be "hard-wired" by a list of the rectangle coodinates, and page number, pasted inside acrobat and run or entered into acrobat in some way.
    Your script would help many disabled people who are distributed through out the world.
    Feel free to contact me by email if you wish.
    Dying Vets

    P.S.
    This rectangle does not have to be a full annotation rectangle which needs user,date and a lot of info.
    Something minimal like this would suffice
    1 0 0 RG % red for stroke color
    200 300 50 75 re
    As you can see that the native unit of the pdf file is the "point" having 72 in an inch.
    The file dpi would be given. However, one could assume that pixel for the rectangle lower-left and width/height are given.
    From the pixels and dpi, the points could be calculated if desired.

  • How do you add a "top of page" button to an iWeb page?

    How do you add a "top of page" button to an iWeb page?

    Two solutions:
    The Easy One:
    Create a Form (which will be the button) and add text to it or choose a picture from iphoto. Now give the form/picture a hyperlink to the same site. So now if you press the button, the site will refresh and start at the beginning/top
    The advanced way:
    1. Publish your site on the web (not just local). Copy the URL
    2. Now create a Button like displained in the solution above. As Hyperlink you'll now have to set external site and paste the before copied link AND add the following at the end of the url:      #widget0
    3. Add a html widget to the top of the site.
    4. The widget's content should be   <a name="anchor"></a>
    5. Publish your site again on the web and look wether it works.
    This way won't work, if the created site is linked as an iframe.

  • How can I add an existing cfm page to a project?

    CFB3 Question: How can I add an existing cfm page to a project? I created a project and copied a file into the project folder but I can't seem to find a way to add the cfm file into the project.

    @Carl - Well heck, yes I did... But after reading your response I went back and tried right-clicking on and refreshing different things and what worked was right-clicking on the project name in the Navigator window and then clicking on refresh in that context menu.
    Thank you Carl!

  • How can I add a language on pages (Greek) to check the spelling when that language is not on the list?

    how can I add a language on pages (Greek) to check the spelling when that language is not on the list?
    I can see other languages available for spelling check, but not Greek and I dont see how to add it.
    I have added the Greek keyboard on the Mac, so I can write in Greek , but I dont know how to check the spelling in Greek on pages

    You can try to add a 3rd party spellchecker
    http://milaraki.com/blog/2010/11/greek-spelling-at-pages-how-to/

  • How to programmatically add af:setPropertyListener to CommandImageLink

    Hi All,
    My Requirement: programmatically add af:setPropertyListener to CommandButton
    I referred this post how to programmatically add af:setPropertyListener to CommandButton and followed the following code.
    Code:
    // create a value expression
    ValueExpression vx =
    elFactory.createValueExpression(elContext, "#{pageFlowScope.clockNo}",
    String.class);
    // set a default value if desired
    vx.setValue(elContext, clockNo);
    SetPropertyListener spl =
    new SetPropertyListener(ActionEvent.class.getName());
    spl.setFrom(clockNo);
    spl.setValueExpression("to", vx);
    // add the listener to the button
    newOpButton.addActionListener(spl);
    My Code:
    <af:commandImageLink id="editInsuraceDetLink"
    icon="/resources/images/Edit.jpg"
    iconPosition="trailing"
    rendered="#{not row.deleted}"
    action="addEndorsement"
    useWindow="true"
    inlineStyle="vertical-align:bottom;"
    partialSubmit="true"
    shortDesc="Edit"
    *actionListener="#{pageFlowScope.GetEndorsementTypeListener.execute}"*
    returnListener="#{GetEndorsementDetailsListener.execute}"
    windowEmbedStyle="window"
    windowModalityType="applicationModal"
    windowHeight="650" windowWidth="740">
    </af:commandImageLink>
    Action Listener - .GetEndorsementTypeListener.execute code:
    RichCommandImageLink a_button = (RichCommandImageLink) a_component.findComponent("editInsuraceDetLink");
    FacesContext fctx = FacesContext.getCurrentInstance();
    Application application = fctx.getApplication();
    ELContext elContext = fctx.getELContext();
    ExpressionFactory elFactory = application.getExpressionFactory();
    ValueExpression vx = elFactory.createValueExpression(elContext, "#{pageFlowScope.controlFlowName}", String.class);
    // set a default value if desired
    //vx.setValue(elContext, clockNo);
    SetPropertyListener spl = new SetPropertyListener(ActionEvent.class.getName());
    spl.setFrom(a_target.getEndorsementFor().toString());
    spl.setValueExpression("to", vx);
    System.out.println("From= "+spl.getFrom());
    System.out.println("To= "+spl.getValueExpression("to"));
    // add the listener to the button
    a_button.addActionListener(spl);
    I got the following output.
    From= Nominee / Appointee
    To= ValueExpression[#{pageFlowScope.controlFlowName}]
    Now my Problem is: the pageFlowScope variable ControlFlowName is not set.
    And also I got a *link*: https://blogs.oracle.com/vijaymohan/entry/usage_of_setpropertylistener_and_setactionlistener
    Whats wrong with my code. Is my problem related with above *link*.
    Please suggest me how to add SetPropertyListener programmatically.
    -Thanks
    Mohanraj

    Frank,
    This works:
            // create a value expression
            ValueExpression vx =
                elFactory.createValueExpression(elContext, "#{pageFlowScope.clockNo}",
                                                String.class);
            // set a default value if desired
            vx.setValue(elContext, clockNo);
            SetPropertyListener spl =
                new SetPropertyListener(ActionEvent.class.getName());
            spl.setFrom(clockNo);
            spl.setValueExpression("to", vx);
            // add the listener to the button
            newOpButton.addActionListener(spl);But, I am thinking you would have known about it before I posted it. I don't really know how it works, but it does.
    Can you help me reconcile between this, and what you said. Because what you said makes sense too.

  • How to programmatically add timeline webpart to publishing page

    Can we add timeline webpart programmatically?
    If yes then please let me know how we can add it?

    Hi Jason,
    Thanks for your reply. It helped me lot but i want to add something to your code.
    1) Added web.AllowUnsafeUpdates to resolve error of disallow to update.
    2) Added TimelineType  and SourceSelection  properties else it shows add setup properties of webpart
    3) manager.WebParts.Count >= 0 Added condition else on every request it adds control.
    Also i want to know few line of code from your answer:
    1) What is the purpose of using storagekey? Why it is needed?
    2) Why you update page items?
    try
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                        using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                            web.AllowUnsafeUpdates = true;
                            SPFile page = web.GetFile("/Pages/Home.aspx");
                            page.CheckOut();
                            using (SPLimitedWebPartManager manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
                                if (manager.WebParts.Count <= 0)
                                    SPTimelineWebPart timelineWebPart = new SPTimelineWebPart();
                                    timelineWebPart.TimelineType = SPTimelineWebPart.TimelineTypeTaskList;
    //Task type list
                                    timelineWebPart.SourceSelection = "Tasks"; //list name
                                    manager.AddWebPart(timelineWebPart, "timelineZone", 0);
                            page.CheckIn(string.Empty);
                            page.Publish(string.Empty);
                            web.AllowUnsafeUpdates = false;
                catch (Exception ex)
                    lblError.Visible = true;
                    lblError.Text = ex.Message.ToString();
    Once again thanks for your reply. Please if you can resolve my queries then please reply it.

  • How can I add metadata to iWeb pages hosted on .mac?

    How can I add title/description/keyword metadata to my website?
    Is there an easy solution?
    I publish my site to my .mac account.
    Any direction would be appreciated. I work in the web marketing industry, so it bugs me not being able to add metadata to my site.
    Thanks!
    Macbook   Mac OS X (10.4.7)  

    So I find the folder: Welcome_files for example
    Then do I open up the Welcome.js file using text
    editor?
    When I add the metadata, then do I Save As and put
    the file back into the Welcome_files folder?
    Actually every page like Welcome has a Welcome.html file and then a folder "Welcome_files". The file you want to edit is the Welcome.html file. Not anything in the folder.
    Do I need to Publish again, or is that process
    automatic since the site is pulling from down from my
    iDisk?
    Nope don't publish again. That would just overwrite you changes again. Just save the file in the same place and you're done.
    Will I have to re-enter metadata every time that the
    page changes, or every time the site changes?
    Anytime iWeb thinks the page needs to be republished, your edited file will be overwritten.

  • How to programmatically add UDVs to project?

    Hi all,
    I have successfully used something like this to programatically add shared variables to an LVLIB (the code assumes that the library associated with the Container Reference contains at least one variable):
    An example output would be:
    Container Name: "MyLibrary.lvlib"
    Variable Name: "Variable1"
    Variable Path: <blank>
    Variable Type String: "Variable"
    (I notice that there is no way to specify the data type of the variable, and LabVIEW creates a DBL variable in the LVLIB by default.)
    However, if Container Reference is associated with a "User-Defined Variables" container, then I get Error 1 at the Invoke Node ("LabVIEW: An input parameter is invalid"). A example output is:
    Container Name: "User-Defined Variables"
    Variable Name: "Variable1"
    Variable Path: <blank>
    Variable Type String: "Variable"
    Questions:
    Does the error occur because LabVIEW is trying to create a DBL variable (which is not allowed with UDVs)?
    How can I programmatically add UDVs to my project?
    Thanks in advance!

    What is the scope of your project? How will you be using these UDV's?
    Mark P.
    Applications Engineer
    National Instruments
    www.ni.com/support

  • Site Template and webparts in Publishing Pages

    Hi
    I've created a couple of webparts in SPD and added these to the pages in the Pages Library (Publish). I then export the site as a template (switching publish off first) and create a new sites from the template. Unfortunately the weparts are missing from
    the publish pages but are available in the new site Webparts Gallery. The Site Pages have the Webparts available but the Publishing pages dont. When I exported the SC root web I switched off publishing for the site.
    Why aren’t the weparts appearing on the page created in Pages Library. Ive switched on publishing now in the new site but its made no difference. ?
    I found this blog but it doesnt appear to provide a solution :http://blogs.technet.com/b/stefan_gossner/archive/2007/09/19/save-site-as-template-option-and-the-publishing-feature.aspx
    Thanks

    As I said, templates are not supported when you turn on publishing.  That's why there is no "save site as template" link after you turn on Publishing in a Site Collection.  I assume you are using one of the hacks to navigate directly
    to the page that lets you save the site as a template, since the link isn't there.  That will work for some sites, but clearly won't for yours.  There is no workaround.  Site Templates aren't supported in Publishing environments because they
    aren't reliable.  If you want Page layouts then you need publishing.  If you use publishing then you can't use site templates.
    Paul Stork SharePoint Server MVP
    Principal Architect: Blue Chip Consulting Group
    Blog: http://dontpapanic.com/blog
    Twitter: Follow @pstork
    Please remember to mark your question as "answered" if this solves your problem.

  • How to programmatically add af:setPropertyListener to CommandButton

    I just read:
    https://blogs.oracle.com/jdevotnharvest/entry/creating_adf_faces_comamnd_button
    from Frank Nimphius.
    How do I programmatically add an af:setPropertyListener to the programmatically created command button?
    I just cannot seem to figure it out.
    Thanks.
    Edited by: Arie Morgenstern on Feb 8, 2013 9:59 PM

    Frank,
    This works:
            // create a value expression
            ValueExpression vx =
                elFactory.createValueExpression(elContext, "#{pageFlowScope.clockNo}",
                                                String.class);
            // set a default value if desired
            vx.setValue(elContext, clockNo);
            SetPropertyListener spl =
                new SetPropertyListener(ActionEvent.class.getName());
            spl.setFrom(clockNo);
            spl.setValueExpression("to", vx);
            // add the listener to the button
            newOpButton.addActionListener(spl);But, I am thinking you would have known about it before I posted it. I don't really know how it works, but it does.
    Can you help me reconcile between this, and what you said. Because what you said makes sense too.

  • How to programmatically add Allergens & Sensitivities

    We want to ensure that the Allergens (Known to Contain and Does not contain) and Sensitivities (Known to Contain and Does not contain) on the Trade spec match the allergens and sensitivities from the formulation output. How do I programmatically add Allergens (Known to Contain and Does not contain) and Sensitivities (Known to Contain and Does not contain) to their appropriate collection in code?

    Here's my code:
    My code:
    var transContext = AppPlatformHelper.ApplicationManager.TransactionManager.GetSharedContext();
    transContext.Begin();
    try
    // Get allergens from Associated Specs that are Primary associations and not in Version History status
    var allergensContained = tradeSpec.LinkedAssociations.Values.Cast<IAssociatedSpec>()
                                      .Where(linkedSpec => linkedSpec.AssociationType.AssociationTypeML.Targetname == "Primary")
                                      .Where(linkedSpec => !linkedSpec.AssociationHost.IsVersionHistoryStatus())
                                      .SelectMany(linkedSpec => linkedSpec.AssociationHost.As<IGSMTradeSpecDO>()
                                                                  .AllergensContained.Values.Cast<IAllergenContainedDO>()
                                                                  .Select(x => new { Allergen = x.ComplianceItem.Name, Pkid =x.Allergen.PKID })
                                                                  .ToArray())
    // Get allergens not in the Trade Spec
    var allergensToAdd = allergensContained.GroupBy(x => x.Allergen)
                          .Where(x => tradeSpec.AllergensContained.Values.Cast<IAllergenContainedDO>().All(y => y.ComplianceItem.Name != x.Key))
                                          .Select(x => new { Allergen = x.Key, PKIDs = x })
                                          .ToArray();
    // Add allergens to the Trade Spec
    allergensToAdd.Each(x =>
       // Add allergen (known to contain)
       var allergenContainedDo = (IAllergenContainedDO)ServiceBase.DataManager.newObject(EnumUniversalDataObjectType.AllergenContainedDO);
       allergenContainedDo.Allergen = (IAllergen)ServiceBase.DataManager.objectFromID(x.PKIDs.First().Pkid); // pkid of allergen(2002)
       allergenContainedDo.MaxPer100g = 1.0;
       allergenContainedDo.MaxPer100gUOM = (IUOM)ServiceBase.DataManager.objectFromID(ServiceBase.UnitOfMeasureService.GetUOMByISOCode("GR").PKID);
       tradeSpec.AllergensContained.Add(allergenContainedDo);
       allergenContainedDo.Save(transContext.Connection);
    catch (Exception ex)
        transContext.SetAbort();
    finally
        transContext.Commit();

  • How do you add a user defined page size for a "standard" user

    I have been trying to add a User Defined Page size in the Adobe PDF Properties with a "Standard" AD account.  When I click add/modify, no error shows up on the screen but the page size does not show up in the drop down menu.  The only accounts that can add page sizes are "Admin" accounts, as far as I know.  Does anyone know a workaround?  PLEASE HELP!!!

    Firefox unable to store your password without username.
    *https://support.mozilla.org/en-US/kb/password-manager-remember-delete-change-passwords

  • How do I add a "Print this page" button (not just a "Print" button) to a PDF?

    I am creating a multipage PDF in Acrobat Pro 8 for a client and it includes a linked table of contents with several sections and also several forms sprinkled throughout. I need to be able to add buttons that allow the user to print specific page numbers. Is it possible to add a "print this page" button to a page ... or even a "print this form" in case the form within the larger document is multiple pages? I would appreciate any help, thanks!

    I was just coming back to here to say I've figured it out and am using an invisible button (over text that was created to look like a link) on each page... tested and working (when combined with the code). Thank you for your replies!

Maybe you are looking for