Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

July 21, 2012

Creation of webpart page and content editor webpart programatically in sharepoint 2010

 DynamicDL
 public static bool insert(PropellerStudioBL propellerStudioBL)
        {

            bool insert = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (MysiteDataContext context = new MysiteDataContext(SiteHelper.SiteUrl))
                {

                    PropellerItem propellerStudioItem = new PropellerItem()

                    {

                     Title  = propellerStudioBL.Propellertitle,
                     

                    };
                    context.Propeller.InsertOnSubmit(propellerStudioItem);
                    context.SubmitChanges();

                    if (propellerStudioItem.Id > 0)
                    {
                        insert = true;
                        if (propellerStudioBL.Title != null && propellerStudioBL.Title != string.Empty)
                        {
                           
                        }
                        else
                        {
                            insert = true;
                        }
                    }
                }
            });
            return insert;
        }
     public static System.Data.DataTable GetPropellerData(PropellerStudioBL propellerStudioBL)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Title");
            dt.Columns.Add("Url");
            DataRow row;
            SPSite spsite;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {


                using (VCSBINTRANETDataContext context = new VCSBINTRANETDataContext(SiteHelper.SiteUrl))
                {

                    var quer = from propellerda in context.PropellerStudio
                               orderby propellerda.Id descending
                               select propellerda;

                    if (quer != null)
                    {
                        foreach (PropellerStudioItem item in quer.Take(3))
                        {
                            row = dt.Rows.Add();
                            row["Title"] = Convert.ToString(item.Title);
                            row["Url"] = Convert.ToString(SPContext.Current.Web.Url + "/pages/" + item.Title + ".aspx");
                        }
                    }
                }
            });
            return dt;
        }

Gridview

           <asp:GridView ID="grdPropeller"  Width="100%" runat="server" BorderStyle="None" 
               AutoGenerateColumns="False" GridLines="None" EmptyDataText="There are no items to show in this view."
               ShowHeader="False">
               <Columns>
           
                   <asp:TemplateField>
                       <ItemStyle Width="350px" />
                       <ItemTemplate>
                           <asp:HyperLink ID="HypTitle" NavigateUrl='<%# Eval("Url") %>' runat="server">
                           <%# Eval("Title")%>                                              
                     
                       <br />
                          </ItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>
      
 
 Function to add A contenteditorwebpart dynamically

protected void createcontenteditorwebpart(string pagename)
        {
            SPSite site = SPContext.Current.Site;
                using (SPWeb web = site.OpenWeb())
                {
                            

                    SPList list = web.Lists["Pages"];
                    string postInformation =

                      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +

                      "<Method>" +

                        "<SetList Scope=\"Request\">" + list.ID + "</SetList>" +

                        "<SetVar Name=\"ID\">New</SetVar>" +

                        "<SetVar Name=\"Cmd\">NewWebPage</SetVar>" +

                        "<SetVar Name=\"Type\">WebPartPage</SetVar>" +

                        "<SetVar Name=\"WebPartPageTemplate\">1</SetVar>" +

                        "<SetVar Name=\"Title\">" + pagename + "</SetVar>" +

                        "<SetVar Name=\"Overwrite\">true</SetVar>" +

                      "</Method>";
                    string processBatch = web.ProcessBatchData(postInformation);
                    web.Update();
           
                }
               
          
        }
Function to creat A webpartPage 
 public void Createwebpartpage(string title)
        {
          
            createcontenteditorwebpart(title);
            SPFile page = SPContext.Current.Web.GetFile("/Pages/" + title + ".aspx");
            using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                XmlElement p = new XmlDocument().CreateElement("p");
                p.InnerText = "Edit this webpart to add content on this Page";
              

                ContentEditorWebPart cewp = new ContentEditorWebPart
                {
                    Content = p
                };
                wpmgr.AddWebPart(cewp, "Header", 0);
            }
            page.Update();
         

        }
Note:
1.Call  Createwebpartpage(txtPropellerTitle.Text);function in submit button.
2.Add Microsoft.sharepoint.publishing dll in reference

Sample for creating a a Article page programatically
 public void createuserwiki(string title)
        {
            SPWeb spweb = SPContext.Current.Web;

            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(spweb);
            string pageName = title + ".aspx";

            PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();
            PageLayout currPageLayout = pageLayouts[9];
            PublishingPageCollection pages = publishingWeb.GetPublishingPages();
          
           PublishingPage newPage = pages.Add(pageName, currPageLayout);

            newPage.ListItem[FieldId.PublishingPageContent] = "";
            newPage.ListItem[FieldId.RollupImage] = "";
            newPage.ListItem[FieldId.Title] = "";

            newPage.ListItem.Update();
            newPage.Update();
            newPage.CheckIn("This is just a comment");
            SPFile page = SPContext.Current.Web.GetFile("/Pages/" + title + ".aspx");
            using (SPLimitedWebPartManager wpmgr = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                XmlElement p = new XmlDocument().CreateElement("p");
                p.InnerText = "Edit this webpart to add content on this Page";
                // page.DeleteProperty(pageLayouts[0]);

                ContentEditorWebPart cewp = new ContentEditorWebPart
                {
                    Content = p
                };
                wpmgr.AddWebPart(cewp, "Header", 0);





            }

May 09, 2012

Create Team Site under Publishing Site in SharePoint 2010


You’ve created a new site collection in SharePoint 2010 and chose the Publishing Site template. When you go to Site Actions -> New Site you only see ‘Publishing Site with Workflow’ and ‘Enterprise Wiki’ as available options. What if you want to create a team site as a subsite?
· Go to Site Actions -> Site Settings
· Select ‘Page layouts and site templates’ under Look and Feel
· Decide whether to make all site templates available (‘Subsites can use any site template’) or choose templates from the ‘Subsites can only use the following site templates’ list
· Click OK
Now when you try to create a new subsite you have access to the site templates you need

Steps to move Pages and Webpart to a Production server using coding


STEP 1:

Steps to Create a Sharepoint Project

File ->New ->Project->EmptySharepointProject
STEP 2:
Deploy the site has Farm solution

STEP 3:
Right click the project àAdd->New Item ->Sharepoint 2010 ->Module
STEP 4:
Rename sample.txt to Samplepage.aspx .Copy and paste the below code without any changes in samplepage.aspx.if u want to change you can rename the webpartzoneid and u can add multiple zones.
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="PublishingNavigation" Namespace="Microsoft.SharePoint.Publishing.Navigation" Assembly="Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page language="C#" Inherits="Microsoft.SharePoint.Publishing.PublishingLayoutPage,Microsoft.SharePoint.Publishing,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
 
    <SharePoint:ScriptLink name="<% $SPUrl:~SiteCollection/_layouts/jQuery/js/jquery-1.6.2.min.js%>" runat="server"/>
    <SharePoint:ScriptLink name="<% $SPUrl:~SiteCollection/_layouts/jQuery/js/jquery-ui-1.8.16.custom.min.js%>" runat="server"/>
    <SharePoint:CssRegistration name="<% $SPUrl:~SiteCollection/_layouts/SUPortal/Layout.css%>" runat="server"/>
    <SharePoint:CssRegistration name="<% $SPUrl:~SiteCollection/_layouts/SUPortal/Theme.css%>" runat="server"/>
    <SharePoint:CssRegistration name="<% $SPUrl:~SiteCollection/_layouts/jQuery/css/Aristo/jquery-ui-1.8.7.custom.css%>" runat="server"/>
</asp:Content>
 <asp:Content ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    <SharePoint:FieldValue ID="PageTitle" FieldName="Title" runat="server" />
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftActions" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageDescription" runat="server">
    <SharePoint:ProjectProperty Property="Description" runat="server"/>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderBodyRightMargin" runat="server">
    <div height="100%" class="ms-pagemargin"><img src="/_layouts/images/blank.gif" width="10" height="1" alt="" /></div>
</asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderPageImage" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderNavSpacer" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderId="PlaceHolderLeftNavBar" runat="server"></asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div id="main">
    <div id="colLeft">
        <div id="zone1" class="topRow">
            <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Zone1" Title="Zone 1">
                <ZoneTemplate>
          
                </ZoneTemplate>
            </WebPartPages:WebPartZone>
        </div>
        <div id="zone4">
            <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Zone4" Title="Zone 4">
                <ZoneTemplate></ZoneTemplate>
            </WebPartPages:WebPartZone>
        </div>
    </div>
    <div id="colRight">
        <div id="zone3" class="topRow">
            <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Zone3" Title="Zone 3">
                <ZoneTemplate></ZoneTemplate>
            </WebPartPages:WebPartZone>
        </div>
        <div id="zone6">
            <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Zone6" Title="Zone 6">
                <ZoneTemplate></ZoneTemplate>
            </WebPartPages:WebPartZone>
        </div>
    </div>
    <div id="colMiddle">
        <div id="colMiddleContainer">
            <div id="zone2" class="topRow">
                <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Zone2" Title="Zone 2">
                    <ZoneTemplate></ZoneTemplate>
                </WebPartPages:WebPartZone>
            </div>
            <div id="zone5">
                <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Zone5" Title="Zone 5">
                    <ZoneTemplate></ZoneTemplate>
                </WebPartPages:WebPartZone>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" language="javascript">if(typeof(MSOLayout_MakeInvisibleIfEmpty) == "function") {MSOLayout_MakeInvisibleIfEmpty();}</script>
</asp:Content>
STEP 5:
Copy and paste the below code in elements.xml.
<?xml version="1.0"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Url="$Resources:cmscore,List_Pages_UrlName;" List="101" Name="PageModule">
  <File Url="SamplePage.aspx" Type="GhostableInLibrary" Path="PageModule\SamplePage.aspx">
      <Property Name="Title" Value="My Custom Page"/> <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;"/>
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png"/>
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#"/>
      <AllUsersWebPart WebPartOrder="1" WebPartZoneID="Zone1">
        <![CDATA[
  // Put the exported webpart coding which is shown in Step 10
        ]]
      </AllUsersWebPart>
    </File>
  </Module>
</Elements>
 
STEP 6:
Open the page in site you needed to take back up of the webpart
STEP 7:
Choose Edit webpart







STEP 8:

Choose Export all data in Export Mode in Advanced category
  STEP 9:
When Export is choosen the file will be saved has Wepartname.webpart.Open the file in notepad copy the webpart code and paste in elements .xml .Check Zone 1 id and webpartzoneid in samplepage.aspx  is same.

 STEP 10:
  Open the Elements.xml and paste the below coding
 <AllUsersWebPart WebPartOrder="1" WebPartZoneID="Zone1">

        <![CDATA[

        <webParts>

  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">

    <metaData>

      <type name="VCSB.INTRANET.NewsInnerWebpart.NewsInnerWebpart,



VCSB.INTRANET, Version=1.0.0.0, Culture=neutral,



PublicKeyToken=5c6b1aa174bc8565" />

      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>

    </metaData>

    <data>

      <properties>

        <property name="AllowZoneChange" type="bool">True</property>

        <property name="ExportMode" type="exportmode">All</property>

        <property name="HelpUrl" type="string" />

        <property name="Hidden" type="bool">False</property>

        <property name="TitleUrl" type="string" />

        <property name="Description" type="string">My Visual WebPart</property>

        <property name="AllowHide" type="bool">True</property>

        <property name="AllowMinimize" type="bool">True</property>

        <property name="Title" type="string">NewsInnerWebpart</property>

        <property name="ChromeType" type="chrometype">None</property>

        <property name="AllowConnect" type="bool">True</property>

        <property name="Width" type="unit" />

        <property name="Height" type="unit" />

        <property name="HelpMode" type="helpmode">Navigate</property>

        <property name="CatalogIconImageUrl" type="string" />

        <property name="AllowEdit" type="bool">True</property>

        <property name="TitleIconImageUrl" type="string" />

        <property name="Direction" type="direction">NotSet</property>

        <property name="AllowClose" type="bool">True</property>

        <property name="ChromeState" type="chromestate">Normal</property>

      </properties>

    </data>

  </webPart>

</webParts>

       

        ]]>

      </AllUsersWebPart>


STEP 11:

Repeat the process for multiple webparts and paste the below coding in Elements.xml inside <File> tag, if  multiple webparts exist in same page ,rename zone1 to zone2.
<AllUsersWebPart WebPartOrder="1" WebPartZoneID="Zone2">
        <![CDATA[
       <webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="VCSB.INTRANET.NewsInnerWebpart.NewsInnerWebpart,
VCSB.INTRANET, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=5c6b1aa174bc8565" />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="AllowZoneChange" type="bool">True</property>
        <property name="ExportMode" type="exportmode">All</property>
        <property name="HelpUrl" type="string" />
        <property name="Hidden" type="bool">False</property>
        <property name="TitleUrl" type="string" />
        <property name="Description" type="string">My Visual WebPart</property>
        <property name="AllowHide" type="bool">True</property>
        <property name="AllowMinimize" type="bool">True</property>
        <property name="Title" type="string">NewsInnerWebpart</property>
        <property name="ChromeType" type="chrometype">None</property>
        <property name="AllowConnect" type="bool">True</property>
        <property name="Width" type="unit" />
        <property name="Height" type="unit" />
        <property name="HelpMode" type="helpmode">Navigate</property>
        <property name="CatalogIconImageUrl" type="string" />
        <property name="AllowEdit" type="bool">True</property>
        <property name="TitleIconImageUrl" type="string" />
        <property name="Direction" type="direction">NotSet</property>
        <property name="AllowClose" type="bool">True</property>
        <property name="ChromeState" type="chromestate">Normal</property>
      </properties>
    </data>
  </webPart>
</webParts>
      
        ]]>
      </AllUsersWebPart>
STEP 12:
If single webpart exist in a page means copy and paste the below code in Elements.xml  and rename the url,path etc.

<File Url="SamplePage.aspx" Type="GhostableInLibrary" Path="PageModule\SamplePage.aspx">
      <Property Name="Title" Value="My Custom Page"/> <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;"/>
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png"/>
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#"/>
      <AllUsersWebPart WebPartOrder="1" WebPartZoneID="Zone1">
        <![CDATA[
        <webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="VCSB.INTRANET.NewsInnerWebpart.NewsInnerWebpart,
VCSB.INTRANET, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=5c6b1aa174bc8565" />
      <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="AllowZoneChange" type="bool">True</property>
        <property name="ExportMode" type="exportmode">All</property>
        <property name="HelpUrl" type="string" />
        <property name="Hidden" type="bool">False</property>
        <property name="TitleUrl" type="string" />
        <property name="Description" type="string">My Visual WebPart</property>
        <property name="AllowHide" type="bool">True</property>
        <property name="AllowMinimize" type="bool">True</property>
        <property name="Title" type="string">NewsInnerWebpart</property>
        <property name="ChromeType" type="chrometype">None</property>
        <property name="AllowConnect" type="bool">True</property>
        <property name="Width" type="unit" />
        <property name="Height" type="unit" />
        <property name="HelpMode" type="helpmode">Navigate</property>
        <property name="CatalogIconImageUrl" type="string" />
        <property name="AllowEdit" type="bool">True</property>
        <property name="TitleIconImageUrl" type="string" />
        <property name="Direction" type="direction">NotSet</property>
        <property name="AllowClose" type="bool">True</property>
        <property name="ChromeState" type="chromestate">Normal</property>
      </properties>
    </data>
  </webPart>
</webParts>
   
        ]]>
      </AllUsersWebPart>
    </File>

STEP 13:
If you want to create page alone copy and paste the below code in Elements.xml 
<?xml version="1.0"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Url="$Resources:cmscore,List_Pages_UrlName;" List="101" Name="PageModule">
<File Url="SamplePage.aspx" Type="GhostableInLibrary" Path="PageModule\SamplePage.aspx">
      <Property Name="Title" Value="My Custom Page"/> <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;"/>
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png"/>
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#"/>
     
   </File>
   
<File Url="SamplePage.aspx" Type="GhostableInLibrary" Path="PageModule\Test.aspx">
      <Property Name="Title" Value="My Custom Page"/> <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;"/>
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png"/>
      <Property Name="PublishingAssociatedContentType" Value=";#$Resources:cmscore,contenttype_articlepage_name;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#"/>
     
   </File>
</Module> 
</Elements>

 STEP 14:
Deploy the project to the particular site.Now the page and webpart will be created automatically in the  site.Go to Siteactions->View all site content->Pages .Check the page and webpart exists in the site.