Friday, March 8, 2013

Hide approve state column from all lists

[Code]

private void hideApproveStateColumn(SPWeb oWeb)
        {            oWeb.AllowUnsafeUpdates = true;
            SPListCollectionAdapter listAdapter = new SPListCollectionAdapter(oWeb.Lists);
            var result = from list in listAdapter                         select list;
            foreach (SPList list in result)            {                if (list.EnableModeration == true)                {                    string ApprovalStatusColumnName = "_ModerationStatus";                    SPView defaultView = list.DefaultView;                    if (defaultView.ViewFields.SchemaXml.Contains(ApprovalStatusColumnName))                    {                        defaultView.ViewFields.Delete(ApprovalStatusColumnName);                        defaultView.Update();                    }                }            }            oWeb.AllowUnsafeUpdates = false;        }

create view to List programaticallly

[Code]

private void CreateView(SPWeb oWeb)
        {          
            SPSecurity.RunWithElevatedPrivileges(delegate()            {                string strViewName = "myView";                bool bAlreadyExists;              
                SPList oList = oWeb.Lists["Pages"];                SPViewCollection oViewCollection = oList.Views;
                var newWeb = GetRootWeb(oWeb);
               addContentTypeToList(oList);
                StringCollection viewFields = AddFieldsToView();
                bAlreadyExists = CheckViewExist(oViewCollection);
                if (bAlreadyExists) return;                                   oViewCollection.Add(strViewName, viewFields, Query, 10, true, false);                oWeb.Update();            });        }
        private string Query        {            get            {                string query;                query = string.Format(@" <Where>                                        <Eq>                                            <FieldRef Name='ContentType' />                                            <Value Type='Computed'>{0}</Value>                                        </Eq>                                    </Where>                               <OrderBy>                                 <FieldRef Name='Created' Ascending='FALSE' />                       </OrderBy>", mycontentType);
                return query;            }        }
        private static StringCollection AddFieldsToView()        {            StringCollection viewFields= new System.Collections.Specialized.StringCollection();
            try            {                viewFields.Add("field1");                viewFields.Add("field2");                viewFields.Add("field3");                viewFields.Add("field4");            }            catch (Exception e)            {                //write code when exception happen            }            return viewFields;        }

   private static SPWeb GetRootWeb(SPWeb oWeb)        {            SPWeb newWeb = oWeb;            while (!newWeb.IsRootWeb)            {                newWeb = newWeb.ParentWeb;            }            return newWeb;        }

  private void addContentTypeToList(SPList oList)        {            if (oList.ContentTypes[myCTName] == null)            {                oList.ContentTypes.Add(myCT);                oList.Update();            }        }
        private static bool CheckViewExist(SPViewCollection oViewCollection)        {            bool bAlreadyExists=false;
            foreach (SPView vItem in oViewCollection)            {                if (vItem.Title == "myView")                {                    bAlreadyExists = true;                    break;                }
            }            return bAlreadyExists;        }

Create DiscussionBoard Programatically

[Code]

   private void CreateDiscussionBoardListToSite(SPWeb oWeb,string listNameEn,string listDescEn,string listNameAr,string listDescAr)        {            SPList list = oWeb.Lists.TryGetList(listNameEn);            if (list!=null) return;
            oWeb.AllowUnsafeUpdates = true;            Guid listId = oWeb.Lists.Add(listNameEn, listDescEn, SPListTemplateType.DiscussionBoard);            SPList createdList = oWeb.Lists[listId];            createdList.OnQuickLaunch = true;
            createdList.TitleResource.SetValueForUICulture(new CultureInfo(1033), listNameEn);            createdList.TitleResource.SetValueForUICulture(new CultureInfo(1025), listNameAr);            createdList.TitleResource.Update();
            createdList.DescriptionResource.SetValueForUICulture(new CultureInfo(1033), listDescEn);            createdList.DescriptionResource.SetValueForUICulture(new CultureInfo(1025), listDescAr);            createdList.DescriptionResource.Update();
         
            createdList.Update();        }

create default home page and add webparts on sitedefinition


11-      Create home.aspx page bye adding textfile and change extension .aspx
22-      Open home.aspx and write magic code :

 <%@ Page Inherits="Microsoft.SharePoint.Publishing.TemplateRedirectionPage,Microsoft.SharePoint.Publishing,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %> <%@ Reference VirtualPath="~TemplatePageUrl" %> <%@ Reference VirtualPath="~masterurl/default.master" %>

33-  Open onet.xml and add these lines
 <Modules>    <Module Name="DefaultBlank" Url="Pages" Path="">
      <File Url="Home.aspx"  Path="Home.aspx" Type="GhostableInLibrary">
        <Property Name="Title" Value="Home" />
        <Property Name="PublishingPageLayout" Value="~SiteCollection/_catalogs/masterpage/HomeLayout.aspx, Home Default Layout" />
        <Property Name="ContentType" Value="myPagesCT" />
        <AllUsersWebPart WebPartZoneID="myWebpart" WebPartOrder="1">
          <![CDATA[

<!—your webpart code à]]>        </AllUsersWebPart>
</File></Module></Modules>

Apply page layout to publishing pages


1-      Update content types to publishing pages
======================================

  private void UpdatePublishingPageContentTypes(SPWeb Web)        {            Web.AllowUnsafeUpdates = true;            // Get a content type.            SPContentTypeCollection contentTypeColl = Web.AvailableContentTypes;            string pageContentTypeName = "Page";            SPContentType pageContentType = Web.ContentTypes[pageContentTypeName];          
            foreach (SPContentType contentType in contentTypeColl)            {                if (contentType.Id.ToString().ToLower().Contains(pageContentType.Id.ToString().ToLower()))                {                    try                    {                        SPList list = Web.Lists["Pages"]; // Throws exception if does not exist.
                        // Make sure the list accepts content types.                        list.ContentTypesEnabled = true;
                        if (list.ContentTypes[contentType.Name] == null)                        {                            list.ContentTypes.Add(contentType);                        }                    }                    catch (ArgumentException ex)                    {                        // No list is found.                    }                }            }            Web.AllowUnsafeUpdates = false;        }


2-      Add content type attribute to elements .xml under file line declaration :
<File Url="Home.aspx"  Path="Home.aspx" Type="GhostableInLibrary">
        <Property Name="Title" Value="Home" />
        <Property Name="PublishingPageLayout" Value="~SiteCollection/_catalogs/masterpage/HomeLayout.aspx, Home Default Layout" />
        <Property Name="ContentType" Value="myPagesCT" />
</File>

Add EventReceiver To All Lists Programatically


This code to add (itemAdding , itemUpdating , itemDeleting ) event receiver fire in all lists

private void AddEventReceiver(SPWeb myweb)
        {          
         
           SPWeb siteCollection = myweb.Site.RootWeb;            SPContentTypeCollection contentTypeCollection = siteCollection.ContentTypes;
            try            {                string contentTypeName ="myContentType"              
                string contentTypeID = GetContentTypeId(siteCollection, contentTypeName);
                AddReceiverToDiffrentLists(myweb, contentTypeCollection, contentTypeID);                           }            catch            {                //write your code on exception happened            }
            finally            {                siteCollection.Dispose();                myweb.Dispose();            }
        }
        private static string GetContentTypeId(SPWeb myweb, string contentTypeName)        {            return myweb.ContentTypes[contentTypeName].Id.ToString();        }



        private void AddReceiverToDiffrentLists(SPWeb myweb, SPContentTypeCollection contentTypeCollection, string ContentTypeID)        {            SPContentType publPageContentType = fetchContentType(contentTypeCollection, ContentTypeID);            AttachEventReceiverToCT(myweb, publPageContentType);        }
    
  private static void AttachEventReceiverToCT(SPWeb myweb, SPContentType publPageContentType)        {          
            try            {                ArrayList eventTypeArraylist = new ArrayList();
                eventTypeArraylist.Add(SPEventReceiverType.ItemAdding);                eventTypeArraylist.Add(SPEventReceiverType.ItemDeleting);                eventTypeArraylist.Add(SPEventReceiverType.ItemUpdating);
                foreach (var item in eventTypeArraylist)                {                    publPageContentType.EventReceivers.Add((SPEventReceiverType)item, Assembly.GetExecutingAssembly().FullName, "myTestProject.ListDefinitions.ItemReceiver.ItemReceiver");                }
                publPageContentType.Update(true, false);                myweb.Update();            }            catch            {                //write your exception code            }            finally            {                //write your code            }        }
     private SPContentType fetchContentType(SPContentTypeCollection contentTypeCollection, string ID)        {            SPContentType publContentType = null;            foreach (SPContentType contentType in contentTypeCollection)            {
                if (string.Equals(contentType.Id.ToString(), ID, StringComparison.InvariantCultureIgnoreCase))                {                    publContentType = contentType;                    break;                }            }            return publContentType;        }

Add rating Field To Discussion board


This Code To Add Rating Field To Discussion Board List
=================================


private void  DiscussionBoardListsOperation(SPWeb oSite)
        {          
            SPSecurity.RunWithElevatedPrivileges(delegate                {                    oSite.AllowUnsafeUpdates = true;                    SPListCollectionAdapter listAdapter = new SPListCollectionAdapter(oSite.Lists);                    var result = from list in listAdapter                                 where list.BaseTemplate.Equals(SPListTemplateType.DiscussionBoard)                                 select list;
                    foreach (var disclist in result)                    {                        ActivateRatingForList(disclist);                    }                    oSite.AllowUnsafeUpdates = false;                });        }     
        public void ActivateRatingForList(SPList list)        {            SPView DiscSubView = list.Views["Subject"];            SPView DiscFlatView = list.Views["Flat"];            SPView DiscThreadViews = list.Views["Threaded"];            Guid averageRatingId = new Guid("5a14d1ab-1513-48c7-97b3-657a5ba6c742");            Guid ratingCountId = new Guid("b1996002-9167-45e5-a4df-b2c41c6723c7");
            SPField averageRating = list.ParentWeb.AvailableFields[averageRatingId];            if (averageRating != null && !list.Fields.Contains(averageRating.Id))            {                list.Fields.Add(averageRating);            }            SPField ratingCount = list.ParentWeb.AvailableFields[ratingCountId];            if (ratingCount != null && !list.Fields.Contains(ratingCount.Id))            {                list.Fields.Add(ratingCount);            }            if (averageRating != null && !DiscSubView.ViewFields.Exists(averageRating.InternalName))            DiscSubView.ViewFields.Add(averageRating);          
            if (averageRating != null && !DiscFlatView.ViewFields.Exists(averageRating.InternalName))            DiscFlatView.ViewFields.Add(averageRating);
            string query = @"<OrderBy>                                    <FieldRef Name='Created' Ascending='FALSE' />                                    <FieldRef Name='ItemChildCount' Ascending='FALSE' />                                </OrderBy>";
            DiscSubView.Paged = true;            DiscSubView.RowLimit = 10;
            DiscFlatView.Paged = true;            DiscFlatView.RowLimit = 10;
            DiscThreadViews.Paged = true;            DiscThreadViews.RowLimit = 10;
            DiscFlatView.Query = query;            DiscSubView.Query = query;            DiscThreadViews.Query = query;          
            DiscFlatView.Update();            DiscSubView.Update();            DiscThreadViews.Update();          
            list.Update();        }

Add folders to list


This code to add folder to Pages list

    private void CreateFolderToPagesList(SPWeb oWeb)
        {            oWeb.AllowUnsafeUpdates = true;            string myFolderName = "myFolderName";
            SPList pageList = oWeb.Lists["Pages"];            foreach (SPListItem folder in pageList.Folders)            {                if(folder.Name.Equals(newsFolderName))                return;            }            SPListItem item = pageList.Items.Add("", SPFileSystemObjectType.Folder,myFolderName);            item.Update();            oWeb.AllowUnsafeUpdates = false;
        }

Add contentEditor Web part to specific view


 private void AddContentEditorWebPartToAllNewsView(SPWeb oSite)        {            string webURL = oSite.Url;            string viewUrl = webURL + "/Pages/Forms/myView.aspx";            SPLimitedWebPartManager wpMgr = oSite.GetLimitedWebPartManager(viewUrl,                 PersonalizationScope.Shared);          
            bool wpExist = IsContentEditorWebPartExist(wpMgr);
            string error="Error on Import Content Editor Web Part";
            if (!wpExist)            {                string exportedWebPartXml = GetContentEditorHtmlSources();                XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(exportedWebPartXml));
                System.Web.UI.WebControls.WebParts.WebPart importedWp = wpMgr.ImportWebPart(reader, out error);                wpMgr.AddWebPart(importedWp, "Main", 2);                wpMgr.SaveChanges(importedWp);            }        }
        private static bool IsContentEditorWebPartExist(SPLimitedWebPartManager wpMgr)        {            SPLimitedWebPartCollection wpColl = wpMgr.WebParts;            bool wpExist = false;
            for (int i = 0; i < wpColl.Count; i++)            {                if (wpMgr.WebParts[i].Title.ToLower().Equals("Content Editor".ToLower()))                {                    wpExist = true;                    break;                }            }            return wpExist;        }
   private string GetContentEditorHtmlSources()        {            StringBuilder builder = new StringBuilder();
            builder.Append("<WebPart xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns='http://schemas.microsoft.com/WebPart/v2'>");            builder.Append(" <Title>Content Editor</Title>");            builder.Append("<FrameType>Default</FrameType>");            builder.Append("<IsIncluded>true</IsIncluded>");            builder.Append("<ZoneID>Main</ZoneID>");            builder.Append("<PartOrder>2</PartOrder>");            builder.Append("<FrameState>Normal</FrameState>");            builder.Append(" <AllowRemove>true</AllowRemove>");            builder.Append("<AllowZoneChange>true</AllowZoneChange>");            builder.Append(" <AllowMinimize>true</AllowMinimize>");            builder.Append("<AllowConnect>true</AllowConnect>");            builder.Append("<AllowEdit>true</AllowEdit>");            builder.Append(" <AllowHide>true</AllowHide>");            builder.Append(" <IsVisible>true</IsVisible>");            builder.Append(" <HelpMode>Modeless</HelpMode>");            builder.Append(" <Dir>Default</Dir>");            builder.Append(" <MissingAssembly>Cannot import this Web Part.</MissingAssembly>");            builder.Append(" <PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge>");            builder.Append(" <Assembly>Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>");            builder.Append(" <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>");            builder.Append(" <ContentLink xmlns='http://schemas.microsoft.com/WebPart/v2/ContentEditor' />");            builder.Append(@" <Content xmlns='http://schemas.microsoft.com/WebPart/v2/ContentEditor'>    <![CDATA[<script type='text/javascript'>var theTDs = document.getElementsByTagName('td');var i=0;var TDContent = '';while (i < theTDs.length) {try {TDContent = theTDs[i].innerText || theTDs[i].textContent;if ((TDContent.indexOf('<DIV') == 0) && (TDContent.indexOf('</DIV>') >= 0)) {theTDs[i].innerHTML = TDContent;}}catch(err){}i=i+1;}</script>]]>  </Content>");
            builder.Append("<PartStorage xmlns='http://schemas.microsoft.com/WebPart/v2/ContentEditor' />");            builder.Append("</WebPart>");
            return builder.ToString();
        }

Add approve workflow to document library


     1-   Go to schema.xml in document library
2- Add  ModeratedList="TRUE"  in line of list

Ex:
<List xmlns:ows="Microsoft SharePoint" EnableContentTypes="TRUE" Title="Articles" Direction="$Resources:Direction;" Url=Lists/Articles" BaseType="1" xmlns="http://schemas.microsoft.com/sharepoint/" ModeratedList="TRUE" DraftVersionVisibility="2">