Tuesday, September 13, 2011

Add / Delete content type to list programmatically

Hi Friend,

Here is sample code to add / delete content type in list / library programmatically.Also i will create the site column and add into custom content type.

 public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite spCurrentSite = properties.Feature.Parent as SPSite)//new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb spCurrentweb = spCurrentSite.OpenWeb())
                        {
                            //Delete existing content type
                             spCurrentweb.AllowUnsafeUpdates = true;
                            SPContentType newwvOCSDoc = spCurrentweb.ContentTypes.Cast<SPContentType>().FirstOrDefault(c => c.Name == "wvOCSDoc");

                            if (newwvOCSDoc != null)
                            {
                                newwvOCSDoc.Delete();
                            }

                            //Delete existing site columns

                            SPField CountryCode= spCurrentweb.Fields.Cast<SPField>().FirstOrDefault(f => f.StaticName == "wvCountryCode");
                            if (CountryCode!= null)
                            {
                                CountryCode.Delete();
                            }
                         
                            SPField ProjectID = spCurrentweb.Fields.Cast<SPField>().FirstOrDefault(f => f.StaticName == "wvProjectID");
                            if (ProjectID != null)
                            {
                                ProjectID.Delete();
                            }

                            //Now add new content type in site

                            SPContentType myContentType = new SPContentType(spCurrentweb.ContentTypes["Document"], spCurrentweb.ContentTypes, "wvOCSDoc");

                            myContentType.Group = "Custom Content Types"; //Group name

                            //Create new Site Columns
                            spCurrentweb.Fields.Add("wvCountryCode", SPFieldType.Text, false);
                            spCurrentweb.Fields.Add("wvProjectID", SPFieldType.Text, false);
                          
                            SPFieldLink Author = new SPFieldLink(spCurrentweb.Fields["Author"]);
                            myContentType.FieldLinks.Add(Author);

                            SPFieldLink wvCountryCode = new SPFieldLink(spCurrentweb.Fields["wvCountryCode"]);
                            myContentType.FieldLinks.Add(wvCountryCode);

                            SPFieldLink wvProjectID = new SPFieldLink(spCurrentweb.Fields["wvProjectID"]);
                            myContentType.FieldLinks.Add(wvProjectID);

                            spCurrentweb.ContentTypes.Add(myContentType);
                            myContentType.Update();

                           spCurrentweb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }

            catch (Exception ex)
            { }
        }
Now you can see the "wvOCSDoc" content type in site content type section of your site.

Use of UpdateMappedPage in sharepoint 2010

Hi Friend,

In sharepoint 2007, we were not able to open our custom site page instead of default page. Suppose you have requirement like that you need to open your custom page instead of error.aspx / accessdenied.aspx / login.aspx / signout.aspx etc.
Now we can override these page using UpdateMappedPage method in sharepoint 2010. Here you can see how we can update all the pages.

I am simply create a event receiver to update the error.aspx, Accessdenied.aspx and Signout.aspx pages. First you need to create three .aspx pages respectively and create new folder in layout folder of root directory. Then put all the pages in newly created folder. (In my case that is errorpage.aspx, accessdenied.aspx and logout.aspx)
Now go back to your code and use below code:

  const string CustomErrorPage = "/_layouts/Customerorrpages/errorpage.aspx";
  const string CustomAccessdeniedPage = "/_layouts/Customerorrpages/accessdenied.aspx";
  const string CustomLogoutPage = "/_layouts/Customerorrpages/logout.aspx";

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    SPSite web = properties.Feature.Parent as SPSite;
                    SPWebApplication webApp = web.WebApplication;
                    using (SPSite site = webApp.Sites[0])
                    {
                        using (SPWeb rootWeb = site.RootWeb)
                        {
                            if (webApp != null)
                            {
                               
                                webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Error, CustomErrorPage);
                                webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied, CustomAccessdeniedPage);
                                webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Signout, CustomLogoutPage);
                                webApp.Update(true);
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                }
            });
         }
           
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                   
                    SPSite web = properties.Feature.Parent as SPSite;
                    SPWebApplication webApp = web.WebApplication;
                   
                    using (SPSite site = webApp.Sites[0])
                    {
                        using (SPWeb rootWeb = site.RootWeb)
                        {
                            if (webApp != null)
                            {
                              
                         webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Error, null);
                         webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied, null);
                         webApp.UpdateMappedPage(SPWebApplication.SPCustomPage.Signout, null);
                                webApp.Update(true);
                            }
                        }
                    }
                }
                catch(Exception ex)
                {
                   
                }
            });
       }
Now you can see, if you activate this feature then it will override the pages and once you deactivate this then again value set is null.

Please provide your feedback

Upload document in document library with content type in sharepoint

Hi Friend,
I am going to write simple steps to upload document in document library with content type. I know that most of the people are aware about it but this simple post can help for new friends.

First Thing is, i want to explain about business requirements: Get content type name, multiple document source path, sharepoint library URL and file extensions from the configuration file (web.config).

1. First create two content type in your site.
 Go to your site-->Site Settings-->Click "Site content Types" from galleries section-->Click "Create"-->Put "wvOCSImage" in name textbox--->"select document content type" from "select parent content type from:" dropdown-->Select "document" from parent content type dropdown-->Select "Custom Content Type" as group and click ok.

Do the same for second content type and give name  "wvOCSDoc".

2. Now here is my <appsettings> of application web.config file

Go to C:\inetpub\wwwroot\wss\VirtualDirectories\ and open your application web.config file and copy and paste below settings just before </configuration> tab.

<appSettings>
    <add key="IMGcType" value="wvOCSImage" />
    <add key="DoccType" value="wvOCSDoc" />
    <add key="sourcePath" value="C:\Document File Path\Image,C:\Document File Path\Video,D:\Document\Audio,C:\BusinessDoc" />
    <add key="SPLibraryURL" value="http://servername:portno./Content%20Library/Forms/AllItems.aspx" />
    <add key="defaultImage" value="JPG,BMP,jpeg" />
     <add key="defaultDoc" value="DOC,docx" />
  </appSettings>

3. Open visual studio and create custom webpart. and copy and paste below code in pageload event. (You may use same code at any other event as per your requirement)

        String ImgContentType = default(String);
        String DocumentContentType = default(String);
        String sourcepath = default(String);
        String SPLibrarypath = default(String);
        String DefaultImage = default(String);
        String DefaultDoc = default(String);
       
        string[] IndividualSource = new string[];
        string[] IndividualImage;
        string[] IndividualDoc;

            if (ConfigurationManager.AppSettings["IMGcType"] != null)
            {
                ImgContentType = ConfigurationManager.AppSettings["IMGcType"].ToString().Trim();
            }

            if (ConfigurationManager.AppSettings["DoccType"] != null)
            {
                DocumentContentType = ConfigurationManager.AppSettings["DoccType"].ToString().Trim();
            }
            if (ConfigurationManager.AppSettings["sourcePath"] != null)
            {
                sourcepath = ConfigurationManager.AppSettings["sourcePath"].ToString().Trim();
                // separate individual items by commas
                IndividualSource = sourcepath.Split(new char[] { ',' });
            }
            if (ConfigurationManager.AppSettings["SharepointargetPath"] != null)
            {
                SPLibrarypath = ConfigurationManager.AppSettings["SPLibraryURL"].ToString().Trim();
            }

            if (ConfigurationManager.AppSettings["defaultImage"] != null)
            {
                DefaultImage = ConfigurationManager.AppSettings["defaultImage"].ToString().Trim();
                // separate individual items between commas
                IndividualImage = DefaultImage.Split(new char[] { ',' });
            }

            if (ConfigurationManager.AppSettings["defaultDoc"] != null)
            {
                DefaultDoc = ConfigurationManager.AppSettings["defaultDoc"].ToString().Trim();
                // separate individual items between commas
                IndividualDoc = DefaultDoc.Split(new char[] { ',' });

            }

            //get single image file, check extension and upload into document library

            string[][] AllExtensions = new string[][] { IndividualImage, IndividualDoc };
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spCurrentSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb spCurrentweb = spCurrentSite.OpenWeb(SPContext.Current.Web.ID))
                    {
                        spCurrentweb.AllowUnsafeUpdates = true;
                        SPList _Listname = spCurrentweb.GetList(SPLibrarypath);

                        SPContentType WebImageContentType = null;
                        SPContentType WebDocContentType = null;

                        if (_Listname != null)
                        {
                            SPContentType ImageCT = _Listname.ContentTypes[ImgContentType];
                            SPContentType DocumentCT = _Listname.ContentTypes[DocumentContentType];

                            // Enable Content Types on list
                            _Listname.ContentTypesEnabled = true;

                            if (ImageCT == null)
                            {
                                WebImageContentType = spCurrentweb.AvailableContentTypes[ImgContentType];
                                _Listname.ContentTypes.Add(WebImageContentType);
                            }

                            if (DocumentCT == null)
                            {
                                WebDocContentType = spCurrentweb.AvailableContentTypes[DocumentContentType];
                                _Listname.ContentTypes.Add(WebDocContentType);

                            }

                            // Update List Configuration
                            _Listname.Update();

                            foreach (string dirpath in IndividualSource)
                            {
                                string[] Source = Directory.GetFiles(dirpath);

                                foreach (string imagefile in Source)
                                {
                                    for (int row = 0; row < AllExtensions.Length; row++)
                                    {
                                        foreach (string element in AllExtensions[row])
                                        {
                                            if (imagefile.ToLower().EndsWith(element.ToString()) || imagefile.ToUpper().EndsWith(element.ToString()))
                                            {
                                                //Add document to library
                                                StreamReader sr = new StreamReader(imagefile);
                                                Stream fStream = sr.BaseStream;
                                                byte[] contents = new byte[fStream.Length];
                                                fStream.Read(contents, 0, (int)fStream.Length);
                                                fStream.Close();
                                                fStream.Dispose();

                                                string fileName = Path.GetFileName(imagefile);
                                                string destUrl = _Listname.RootFolder.ServerRelativeUrl + "/" + fileName;

                                                foreach (string extension in IndividualImage)
                                                {
                                                    if (extension.Equals(element))
                                                    {
                                                        SPFile addedFile = _Listname.RootFolder.Files.Add(destUrl, contents, true);
                                                        SPItem newItem = addedFile.Item;
                                                        newItem["ContentType"] = WebImageContentType.Name;
                                                        newItem.Update();
                                                        addedFile.Update();
                                                        break;
                                                    }
                                                }

                                                foreach (string extension in IndividualDoc)
                                                {
                                                    if (extension.Equals(element))
                                                    {
                                                        SPFile addedFile = _Listname.RootFolder.Files.Add(destUrl, contents, true);
                                                        SPItem newItem = addedFile.Item;
                                                        newItem["ContentType"] = WebDocContentType.Name;
                                                        newItem.Update();
                                                        addedFile.Update();
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        else
                        {
                            //List name is not found error
                        }
                        spCurrentweb.AllowUnsafeUpdates = false;
                    }
                }
            });
 Now you can go to your library and can see both the content types have been added and all the files from your physical source have been uploaded in document library with content type name. This is just the sample code you can change based on your requirement.\
Please provide your feedback