Tuesday 24 January 2012

Item level security on SharePoint List Programatically


Item level security on SharePoint List Programatically

Properties to set item level security is already in SharePoint object Model. Following is the
SPList have properties to set item level security: SPList.ReadSecurity and SPList.WriteSecurity

E.g.
SPList spList = SPContext.Current.Web.Lists["Vaibhav Blog List"];
spList.ReadSecurity = 2;
spList.WriteSecurity = 4;
spList.Update();

In more, below will help you to understand more:

ReadSecurity
1. SPList.ReadSecurity = 1 stands for Read Access: Specify which items users can read “All items”
2. SPList.ReadSecurity = 2 stands for Read Access: Specify which items users can read “Only their own”
WriteSecurity 
1. SPList.WriteSecurity = 1 stands for Edit access: Specify which items users can edit “All items”
2. SPList.WriteSecurity = 2 stands for Edit access: Specify which items users can edit “Only their own”
3. SPList.WriteSecurity = 4 stands for Edit access: Specify which items users can edit “None”

Sunday 22 January 2012

BBIINNCC reference

Deploying page layouts URL:
 <Module Name="masterpage" Url="_catalogs/masterPage">
<File Path="masterpage\BincArticleLeft.aspx" Url="BincArticleLeft.aspx"  Type="GhostableInLibrary">
     
      <Property Name="Title"
            Value="abc" />
      <Property Name="MasterPageDescription"
                Value="The article page with image on left contains an image field and a rich text field." />
      <Property Name="ContentType"
                Value="$Resources:cmscore,contenttype_pagelayout_name" />
      <Property Name="PublishingPreviewImage" Value="/_catalogs/masterpage/en-US/Preview Images/ArticleLeft.png"/>
      <Property Name="PublishingAssociatedContentType"
      Value=";#ArticleBInc;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF39002b979b5c686349eb92d939ff73924bec009f244e5227374f12aee85340cb147169;#"/>
    </File>
</Module>

Deploying page Pages:
<Module Name="Pages" Path="Pages" Url="$Resources:cmscore,List_Pages_UrlName;">

<File Name="Accueil.aspx" Url="Home.aspx"  Path="\Home.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE">
      <Property Name="Title" Value="Accueil"/>
      <Property Name="PublishingPageLayout" Value="~SiteCollection/_catalogs/masterpage/ArticleLinks.aspx, Title"/>
      <Property Name="ContentType" Value="Page Article Binc" />
      <Property Name="ContentTypeId"
                Value="0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF39002b979b5c686349eb92d939ff73924bec009f244e5227374f12aee85340cb147169" />
      <Property Name="PublishingPageContent"
        Value="page content comes here" />
    </File>
</Module>

List Instance:
 <List FeatureId="4bcccd62-dcaf-46dc-a7d4-e38277ef33f4" Type="851"
                    Title="Images et Photos" Url="$Resources:core,lists_Folder;/ImagesPhotos"
                      Description="Liste des images et photos publique du département" QuickLaunchUrl="$Resources:core,lists_Folder;/ImagesPhotos" />
 <List FeatureId="00BFEA71-EC85-4903-972D-EBE475780106" Title="Événements"
              Type="106"  Description="Liste des événements publiques du département"
              Url="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder;"
              QuickLaunchUrl="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder;/Calendar.aspx" />
 <List Title="Annonces Privées" VersioningEnabled="True" EnableMinorVersions="True"
         FeatureId="00bfea71-d1ce-42de-9c63-a44004ce0104"
         Url="AnnoncesPrivees"
         Description="Liste des annonces du département" Type="104">
        </List>

  <List Title="Tâches" VersioningEnabled="True" EnableMinorVersions="True"
       FeatureId="00bfea71-a83e-497e-9ba0-7a5c597d0107"
       Url="Taches"
       Description="Liste des tâches du département" Type="107">
        </List>


Creating Views in onet.xml:
 <Module Name="DefaultBlank" Url="" Path="">
      <File Url="default.aspx">
 <View  BaseViewID="0" List="AnnoncesPrivees" WebPartZoneID="webpartzone1"  DisplayName="Annonce du département" RowLimit="1"  >
          <![CDATA[
              <webParts>
                  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
                      <metaData>
                          <type name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" />
                          <importErrorMessage>Cannot import this Web Part</importErrorMessage>
                      </metaData>
                      <data>
                          <properties>
                              <property name="Title">Annonce du département</property>
                              <property name="AllowConnect" type="bool">True</property>
                              <property name="AllowClose" type="bool">False</property>
                          </properties>
                      </data>
                  </webPart>
              </webParts>
          ]]>
        </View>
</File>
</Module>

Image webpart:
<AllUsersWebPart WebPartZoneID="webpartzone10" WebPartOrder="4">
          <![CDATA[
      <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">
        <Title>Image Web Part</Title>
        <FrameType>None</FrameType>
        <Description>Use to display pictures and photos.</Description>
        <PartImageSmall />
        <PartImageLarge>/_layouts/images/msimagel.gif</PartImageLarge>
        <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
        <TypeName>Microsoft.SharePoint.WebPartPages.ImageWebPart</TypeName>
        <ImageLink xmlns="http://schemas.microsoft.com/WebPart/v2/Image%22%3E/_layouts/images/homepageSamplePhoto.jpg%3C/ImageLink>
        <AlternativeText xmlns="http://schemas.microsoft.com/WebPart/v2/Image" />
        <VerticalAlignment xmlns="http://schemas.microsoft.com/WebPart/v2/Image%22%3EMiddle%3C/VerticalAlignment>
        <HorizontalAlignment xmlns="http://schemas.microsoft.com/WebPart/v2/Image%22%3ECenter%3C/HorizontalAlignment>
        <BackgroundColor xmlns="http://schemas.microsoft.com/WebPart/v2/Image%22%3Etransparent%3C/BackgroundColor>
      </WebPart>
   ]]>
        </AllUsersWebPart>

Adding Content types to list and setting default content type:
using System.Collections.Generic;

 SPContentType contype = web.ContentTypes["Page Article Binc"];
// to get the content type from root site
//SPContentType contype1 = SPContext.Current.Site.RootWeb.ContentTypes["Page Article Binc"];
 SPList listpages12 = web.Lists["Pages"];
                    listpages12.ContentTypes.Add(contype);
                    listpages12.Update();
                    SPContentTypeCollection currentOrder = listpages12.ContentTypes;
                    List<SPContentType> result = new List<SPContentType>();
                    foreach (SPContentType ct in currentOrder)
                    {
                        if (ct.Name.Contains("Page Article Binc"))
                        {
                            result.Add(ct);
                        }
                    }
                    listpages12.RootFolder.UniqueContentTypeOrder = result;
                    listpages12.RootFolder.Update();
                    listpages12.Update();


Setting default page:
  PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                PublishingPageCollection webpages = publishingWeb.GetPublishingPages();
                                web.AllowUnsafeUpdates = true;

                SPFile welcomeFile = web.GetFile(web.ServerRelativeUrl + "pages/home.aspx");
             
                publishingWeb.DefaultPage = welcomeFile;
                publishingWeb.Update();
   web.AllowUnsafeUpdates = true;

Hiding Page Layouts:
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
 PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts();
 foreach (PageLayout layout in layouts)
                {                  
                   
                    if (layout.Name.Equals("ArticleLeft.aspx"))
                    {
                        SPListItem item1 = layout.ListItem;
                        item1.File.CheckOut();
                        item1["PublishingHidden"] = true;
                        item1.Update();
                        item1.File.CheckIn("CheckIn");
                        item1.File.Approve("s");

                    }
}


Custom Left Navigation:
 private void displayleftnav(SPSite site, string url)
        {
            using (SPSite siteCollection = new SPSite(site.Url))
            {
               
                using (SPWeb web1 = siteCollection.OpenWeb(url))
                {
                    PublishingWeb publishingWebs = PublishingWeb.GetPublishingWeb(web1);
                                     
                    publishingWebs.Navigation.InheritGlobal = true;
                    publishingWebs.Navigation.GlobalIncludePages = false;
                    publishingWebs.Navigation.GlobalIncludeSubSites = false;
                    publishingWebs.Navigation.ShowSiblings = false;
                   // publishingWebs.Navigation.CurrentIncludeSubSites = true;
                   // publishingWebs.Navigation.CurrentIncludePages = false;
                    if (web1.Url.Contains("Prive"))
                    {
                        publishingWebs.Navigation.InheritGlobal = true;
                        publishingWebs.Navigation.GlobalIncludePages = false;
                        publishingWebs.Navigation.GlobalIncludeSubSites = false;
                        publishingWebs.Navigation.ShowSiblings = false;
                        publishingWebs.Navigation.CurrentIncludeSubSites = false;
                        publishingWebs.Navigation.CurrentIncludePages = false;
                        publishingWebs.Update();
                         SPNavigationNodeCollection CurrentNavigationNodes = web1.Navigation.QuickLaunch;
                        SPNavigationNode bib = new SPNavigationNode("documents","#",true);
                          SPNavigationNode FirstFolder1 = CurrentNavigationNodes.AddAsFirst(bib);
                          SPNavigationNode childNav1 = new SPNavigationNode("Documents1", web1.ServerRelativeUrl.ToString() + "/Documents1", true);
                          FirstFolder1.Children.AddAsFirst(childNav1);
                          childNav1 = new SPNavigationNode("Documents2", web1.ServerRelativeUrl.ToString() + "/Documents2", true);
                          FirstFolder1.Children.AddAsLast(childNav1);
                          childNav1 = new SPNavigationNode("Documents3", web1.ServerRelativeUrl.ToString() + "/Documents3", true);
                          FirstFolder1.Children.AddAsLast(childNav1);
                          childNav1 = new SPNavigationNode("Vidéos", web1.ServerRelativeUrl.ToString() + "/Lists/Videos", true);
                          FirstFolder1.Children.AddAsLast(childNav1);
                          //Then second folder
                          SPNavigationNode SecondFolder1 = CurrentNavigationNodes.AddAsLast(new SPNavigationNode("Outils", "#", true));
                          SPNavigationNode childNavSecond1 = new SPNavigationNode("Liens utiles", web1.ServerRelativeUrl.ToString() + "/LiensUtiles", true);
                          SecondFolder1.Children.AddAsFirst(childNavSecond1);
                          childNavSecond1 = new SPNavigationNode("Mes liens", web1.ServerRelativeUrl.ToString() + "/MesLiens", true);
                          SecondFolder1.Children.AddAsLast(childNavSecond1);
                          //Third Folder
                          SPNavigationNode ThirdFolder1 = CurrentNavigationNodes.AddAsLast(new SPNavigationNode("Autres", "#", true));
                          //add children
                          SPNavigationNode childNavThird1 = new SPNavigationNode("Annonces", web1.ServerRelativeUrl.ToString() + "/AnnoncesPrivees", true);
                          ThirdFolder1.Children.AddAsFirst(childNavThird1);
                          childNavThird1 = new SPNavigationNode("Articles", web1.ServerRelativeUrl.ToString() + "/Pages", true);
                          ThirdFolder1.Children.AddAsLast(childNavThird1);
                    }
                    // Maximum number of dynamic items to show within this level of navigation:
                    //publishingWeb.Navigation.GlobalDynamicChildLimit = 60;
                    //Update the changes
                    publishingWebs.Update();
                }
            }

        }


Adding Custom Top Navigation
 private void AddGlobalNavigation(SPSite site)
        {
           
            SPWeb web = site.OpenWeb();
            SPNavigationNodeCollection topNavigationNodes = web.Navigation.TopNavigationBar;
            SPNavigationNode objItem = new SPNavigationNode("Siège Social", "/Pages/Fr/SiegeSocial.aspx", true);
            //This should be for first folder
            SPNavigationNode FirstFolder = topNavigationNodes.AddAsFirst(objItem);
            //Then add its children
            SPNavigationNode childNav = new SPNavigationNode("Notre équipe", "/Pages/Fr/NotreEquipe.aspx", true);
            FirstFolder.Children.AddAsFirst(childNav);
            childNav = new SPNavigationNode("Organigrammes", "/Pages/Fr/Organigramme.aspx", true);
            FirstFolder.Children.AddAsLast(childNav);
            childNav = new SPNavigationNode("Plan de continuité des affaires", "/Fin/Pages/Fr/PlanContinuiteAffaires.aspx", true);
            FirstFolder.Children.AddAsLast(childNav);
            childNav = new SPNavigationNode("Mesures d'urgence", "/Fin/Pages/Fr/MesuresUrgence.aspx", true);
            FirstFolder.Children.AddAsLast(childNav);
            childNav = new SPNavigationNode("Plan des étages", "/Fin/Pages/Fr/PlanEtages.aspx", true);
            FirstFolder.Children.AddAsLast(childNav);


            //Then second folder
            SPNavigationNode SecondFolder = topNavigationNodes.AddAsLast(new SPNavigationNode("Actualité", "#", true));
            //add children
            SPNavigationNode childNavSecond = new SPNavigationNode("Revues de presse", "/Pages/Fr/RevueDePresse.aspx", true);
            SecondFolder.Children.AddAsFirst(childNavSecond);
            childNavSecond = new SPNavigationNode("Notes internes", "/Pages/Fr/NotesInternes.aspx", true);
            SecondFolder.Children.AddAsLast(childNavSecond);
            childNavSecond = new SPNavigationNode("Activités et événements", "/Pages/Fr/ActivitesEtEvenements.aspx", true);
            SecondFolder.Children.AddAsLast(childNavSecond);
            childNavSecond = new SPNavigationNode("Avis de nomination", "/Pages/Fr/AvisNomination.aspx", true);
            SecondFolder.Children.AddAsLast(childNavSecond);
            childNavSecond = new SPNavigationNode("Autres nouvelles", "/Pages/Fr/AutresNouvelles.aspx", true);
            SecondFolder.Children.AddAsLast(childNavSecond);
            childNavSecond = new SPNavigationNode("Résultats trimestriels", "/AP/RI/Pages/Fr/ResultatsTrimestriels.aspx", true);
            SecondFolder.Children.AddAsLast(childNavSecond);
            childNavSecond = new SPNavigationNode("Actualité par fonction", "/Pages/Fr/ActualiteFonction.aspx", true);
            SecondFolder.Children.AddAsLast(childNavSecond);
}
}
}

Retrieving data from a SharePoint list
There can be different scenarios in InfoPath where programming can be needed. Professional applications cannot be complete without some sort of programming effort. InfoPath is designed in a way that makes creating forms very easy for the users. You can create complicated forms without coding anything but large organizations try to leverage full benefits of InfoPath and full benefits can only be had by adding value to the forms by using complex programming techniques. In this article, we are going to use a simple programming technique that will show you how to populate a drop down box in InfoPath form programmatically with data from a SharePoint list. Of course, there is a way to do it without programming, for example, you can use a data connection to populate the drop down but suppose you want to populate the drop down in a particular scenario or in other words, we can say that you want to populate it dynamically depending on business logic in the form. There can be literally hundreds of scenarios. The biggest advantage of using programming to achieve this goal is you don't have to worry that your data connection will break after deploying to the form to some other server which is a very common problem.

1. Open "user registration" form in InfoPath editor.

2. Add a new data source. Right-click "myFields" in data sources and click "Add".




3. Add "Countries" as a name. From "Type", select "Group" and check "Repeating" checkbox at the bottom and click OK. This will add a repeating group in the data sources.




4. Right-click the newly added group "Countries" and select "Add".

5. We will add two fields (elements). Add "Displayname" in the "Name" box. Leave all other options as they are.



6. Repeat steps 4 and 5 to add another field and name it "Value".

7. Right-click the "Country" drop down in the form and select "Drop-Down List Box Properties".

8. Select "Look up values in the form's data source" option in the "List box entries".



9. Click "Select XPath" button.



10. Select "Countries" (repeating group) and click OK.

11. "Value" and "Display name" will automatically be populated. Change the value in "Value" box by clicking the "Select XPath" button and selecting "Value". Click OK to close the properties.



12. Open VSTA by selecting Tools > Programming > Microsoft Visual Studio Tools For Applications.

13. Add a reference to "Microsoft.SharePoint.DLL".



The DLL is located in the following folder:

System Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

14. Add a reference in code.

using Microsoft.SharePoint;

15. In the FormEvents_Loading(),. add following function:

//Populate country drop downAddCountries();


16. The code for AddCountries() is as following:


{
public void AddCountries()try{






{

newNode = nav.Clone();
newNode.SelectSingleNode(
newNode.SelectSingleNode(
nav.InsertAfter(newNode);
newNode =
}
nav.DeleteSelf();

nav =
}
SPSite site = SPContext.Current.Site;SPWeb web = site.OpenWeb();SPList list = web.Lists["Countries"];SPListItemCollection listitems = list.Items;XPathNavigator nav = this.CreateNavigator().SelectSingleNode("/my:myFields/my:Countries", this.NamespaceManager);foreach (SPListItem li in listitems)XPathNavigator newNode = null;"/my:myFields/my:Countries/my:Displayname", this.NamespaceManager).SetValue(li["Title"].ToString());"/my:myFields/my:Countries /my:Value", this.NamespaceManager).SetValue(li["Title"].ToString());null;null;catch{

}
}

17. Compile the project, publish the form and open it in SharePoint, here is what you should see:



18. This is the programmatic solution. You don't have to worry that your data connection will break on another server. Let's discuss the code briefly. This is not an efficient method of populating the drop down. We should have used SPQuery() object to get data from the list. SPQuery is fast and efficient and works very well with large lists but here our objective was not to achieve efficiency but to show how to fetch data programmatically. We get site context using the "SPContext". You can also hard code the site URL but that's not a good idea. We cannot hard code paths in professional applications. After creating the listitem collection, we read each list item from the collection in a loop. Before getting into the loop, we create a main node that points to the "Countries" repeating group. In the for loop, we create a clone of this node and add values to the "Value" and "Displayname" elements. "Value" and "Displayname" fields get their values from the list item.

newNode.SelectSingleNode(
newNode.SelectSingleNode(
"/my:myFields/my:Countries/my:Displayname", this.NamespaceManager).SetValue(li["Title"].ToString());"/my:myFields/my:Countries /my:Value", this.NamespaceManager).SetValue(li["Title"].ToString());

After you set the values, you have to insert this cloned node in the nodes hierarchy. You do this using the "InsertAfter() method:

nav.InsertAfter(newNode);


"newNode" is passed as a parameter to the "InsertAfter()" method.

After you leave the for loop, you must destroy the parent node that was used to create cloned nodes. This is important to avoid duplicate entry of the parent node otherwise you will see first entry as duplicates.

nav.DeleteSelf();

You can download the form and complete application code for reference.

Happy programming!

Download completed InfoPath form and application code (ZIP format)
Retrieving data from a SharePoint list
There can be different scenarios in InfoPath where programming can be needed. Professional applications cannot be complete without some sort of programming effort. InfoPath is designed in a way that makes creating forms very easy for the users. You can create complicated forms without coding anything but large organizations try to leverage full benefits of InfoPath and full benefits can only be had by adding value to the forms by using complex programming techniques. In this article, we are going to use a simple programming technique that will show you how to populate a drop down box in InfoPath form programmatically with data from a SharePoint list. Of course, there is a way to do it without programming, for example, you can use a data connection to populate the drop down but suppose you want to populate the drop down in a particular scenario or in other words, we can say that you want to populate it dynamically depending on business logic in the form. There can be literally hundreds of scenarios. The biggest advantage of using programming to achieve this goal is you don't have to worry that your data connection will break after deploying to the form to some other server which is a very common problem.

1. Open "user registration" form in InfoPath editor.

2. Add a new data source. Right-click "myFields" in data sources and click "Add".




3. Add "Countries" as a name. From "Type", select "Group" and check "Repeating" checkbox at the bottom and click OK. This will add a repeating group in the data sources.




4. Right-click the newly added group "Countries" and select "Add".

5. We will add two fields (elements). Add "Displayname" in the "Name" box. Leave all other options as they are.



6. Repeat steps 4 and 5 to add another field and name it "Value".

7. Right-click the "Country" drop down in the form and select "Drop-Down List Box Properties".

8. Select "Look up values in the form's data source" option in the "List box entries".



9. Click "Select XPath" button.



10. Select "Countries" (repeating group) and click OK.

11. "Value" and "Display name" will automatically be populated. Change the value in "Value" box by clicking the "Select XPath" button and selecting "Value". Click OK to close the properties.



12. Open VSTA by selecting Tools > Programming > Microsoft Visual Studio Tools For Applications.

13. Add a reference to "Microsoft.SharePoint.DLL".



The DLL is located in the following folder:

System Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

14. Add a reference in code.

using Microsoft.SharePoint;

15. In the FormEvents_Loading(),. add following function:

//Populate country drop downAddCountries();


16. The code for AddCountries() is as following:


{
public void AddCountries()try{






{

newNode = nav.Clone();
newNode.SelectSingleNode(
newNode.SelectSingleNode(
nav.InsertAfter(newNode);
newNode =
}
nav.DeleteSelf();

nav =
}
SPSite site = SPContext.Current.Site;SPWeb web = site.OpenWeb();SPList list = web.Lists["Countries"];SPListItemCollection listitems = list.Items;XPathNavigator nav = this.CreateNavigator().SelectSingleNode("/my:myFields/my:Countries", this.NamespaceManager);foreach (SPListItem li in listitems)XPathNavigator newNode = null;"/my:myFields/my:Countries/my:Displayname", this.NamespaceManager).SetValue(li["Title"].ToString());"/my:myFields/my:Countries /my:Value", this.NamespaceManager).SetValue(li["Title"].ToString());null;null;catch{

}
}

17. Compile the project, publish the form and open it in SharePoint, here is what you should see:



18. This is the programmatic solution. You don't have to worry that your data connection will break on another server. Let's discuss the code briefly. This is not an efficient method of populating the drop down. We should have used SPQuery() object to get data from the list. SPQuery is fast and efficient and works very well with large lists but here our objective was not to achieve efficiency but to show how to fetch data programmatically. We get site context using the "SPContext". You can also hard code the site URL but that's not a good idea. We cannot hard code paths in professional applications. After creating the listitem collection, we read each list item from the collection in a loop. Before getting into the loop, we create a main node that points to the "Countries" repeating group. In the for loop, we create a clone of this node and add values to the "Value" and "Displayname" elements. "Value" and "Displayname" fields get their values from the list item.

newNode.SelectSingleNode(
newNode.SelectSingleNode(
"/my:myFields/my:Countries/my:Displayname", this.NamespaceManager).SetValue(li["Title"].ToString());"/my:myFields/my:Countries /my:Value", this.NamespaceManager).SetValue(li["Title"].ToString());

After you set the values, you have to insert this cloned node in the nodes hierarchy. You do this using the "InsertAfter() method:

nav.InsertAfter(newNode);


"newNode" is passed as a parameter to the "InsertAfter()" method.

After you leave the for loop, you must destroy the parent node that was used to create cloned nodes. This is important to avoid duplicate entry of the parent node otherwise you will see first entry as duplicates.

nav.DeleteSelf();

You can download the form and complete application code for reference.

Happy programming!

Download completed InfoPath form and application code (ZIP format)
Retrieving data from a SharePoint list
There can be different scenarios in InfoPath where programming can be needed. Professional applications cannot be complete without some sort of programming effort. InfoPath is designed in a way that makes creating forms very easy for the users. You can create complicated forms without coding anything but large organizations try to leverage full benefits of InfoPath and full benefits can only be had by adding value to the forms by using complex programming techniques. In this article, we are going to use a simple programming technique that will show you how to populate a drop down box in InfoPath form programmatically with data from a SharePoint list. Of course, there is a way to do it without programming, for example, you can use a data connection to populate the drop down but suppose you want to populate the drop down in a particular scenario or in other words, we can say that you want to populate it dynamically depending on business logic in the form. There can be literally hundreds of scenarios. The biggest advantage of using programming to achieve this goal is you don't have to worry that your data connection will break after deploying to the form to some other server which is a very common problem.

1. Open "user registration" form in InfoPath editor.

2. Add a new data source. Right-click "myFields" in data sources and click "Add".




3. Add "Countries" as a name. From "Type", select "Group" and check "Repeating" checkbox at the bottom and click OK. This will add a repeating group in the data sources.




4. Right-click the newly added group "Countries" and select "Add".

5. We will add two fields (elements). Add "Displayname" in the "Name" box. Leave all other options as they are.



6. Repeat steps 4 and 5 to add another field and name it "Value".

7. Right-click the "Country" drop down in the form and select "Drop-Down List Box Properties".

8. Select "Look up values in the form's data source" option in the "List box entries".



9. Click "Select XPath" button.



10. Select "Countries" (repeating group) and click OK.

11. "Value" and "Display name" will automatically be populated. Change the value in "Value" box by clicking the "Select XPath" button and selecting "Value". Click OK to close the properties.



12. Open VSTA by selecting Tools > Programming > Microsoft Visual Studio Tools For Applications.

13. Add a reference to "Microsoft.SharePoint.DLL".



The DLL is located in the following folder:

System Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI

14. Add a reference in code.

using Microsoft.SharePoint;

15. In the FormEvents_Loading(),. add following function:

//Populate country drop downAddCountries();


16. The code for AddCountries() is as following:


{
public void AddCountries()try{






{

newNode = nav.Clone();
newNode.SelectSingleNode(
newNode.SelectSingleNode(
nav.InsertAfter(newNode);
newNode =
}
nav.DeleteSelf();

nav =
}
SPSite site = SPContext.Current.Site;SPWeb web = site.OpenWeb();SPList list = web.Lists["Countries"];SPListItemCollection listitems = list.Items;XPathNavigator nav = this.CreateNavigator().SelectSingleNode("/my:myFields/my:Countries", this.NamespaceManager);foreach (SPListItem li in listitems)XPathNavigator newNode = null;"/my:myFields/my:Countries/my:Displayname", this.NamespaceManager).SetValue(li["Title"].ToString());"/my:myFields/my:Countries /my:Value", this.NamespaceManager).SetValue(li["Title"].ToString());null;null;catch{

}
}

17. Compile the project, publish the form and open it in SharePoint, here is what you should see:



18. This is the programmatic solution. You don't have to worry that your data connection will break on another server. Let's discuss the code briefly. This is not an efficient method of populating the drop down. We should have used SPQuery() object to get data from the list. SPQuery is fast and efficient and works very well with large lists but here our objective was not to achieve efficiency but to show how to fetch data programmatically. We get site context using the "SPContext". You can also hard code the site URL but that's not a good idea. We cannot hard code paths in professional applications. After creating the listitem collection, we read each list item from the collection in a loop. Before getting into the loop, we create a main node that points to the "Countries" repeating group. In the for loop, we create a clone of this node and add values to the "Value" and "Displayname" elements. "Value" and "Displayname" fields get their values from the list item.

newNode.SelectSingleNode(
newNode.SelectSingleNode(
"/my:myFields/my:Countries/my:Displayname", this.NamespaceManager).SetValue(li["Title"].ToString());"/my:myFields/my:Countries /my:Value", this.NamespaceManager).SetValue(li["Title"].ToString());

After you set the values, you have to insert this cloned node in the nodes hierarchy. You do this using the "InsertAfter() method:

nav.InsertAfter(newNode);


"newNode" is passed as a parameter to the "InsertAfter()" method.

After you leave the for loop, you must destroy the parent node that was used to create cloned nodes. This is important to avoid duplicate entry of the parent node otherwise you will see first entry as duplicates.

nav.DeleteSelf();

You can download the form and complete application code for reference.

Happy programming!

Download completed InfoPath form and application code (ZIP format)

Hide Left Navigation menu in sharepoint

<style type="text/css">
     #s4-leftpanel{
 display:none !important;
}
.s4-ca{
 margin-left:0px !important;
}</style>

Removing the default site name from top menu

By Default we will have the navigation code as below :

<asp:ContentPlaceHolder id="PlaceHolderTopNavBar" runat="server">
        <asp:ContentPlaceHolder id="PlaceHolderHorizontalNav" runat="server">
            <SharePoint:AspMenu
   ID="TopNavigationMenuV4"
   Runat="server"
   EnableViewState="false"
   DataSourceID="topSiteMap"
   AccessKey="<%$Resources:wss,navigation_accesskey%>"
   UseSimpleRendering="true"
   UseSeparateCss="false"
   Orientation="Horizontal"
   StaticDisplayLevels="2"
   MaximumDynamicDisplayLevels="1"
   SkipLinkText=""
   CssClass="s4-tn"/>

<SharePoint:DelegateControl runat="server" ControlId="TopNavigationDataSource" Id="topNavigationDelegate">
  <Template_Controls>
   <asp:SiteMapDataSource
     ShowStartingNode="False"
     SiteMapProvider="SPNavigationProvider"
     id="topSiteMap"
     runat="server"
     StartingNodeUrl="sid:1002"/>
  </Template_Controls>
 </SharePoint:DelegateControl>
  </asp:ContentPlaceHolder>
      </asp:ContentPlaceHolder>


To Remove the default site name Delete the <SharePoint:DelegateControl runat="server" ontrolId="TopNavigationDataSource" Id="topNavigationDelegate">
  <Template_Controls> and StartingNodeUrl="sid:1002"/>
so the code looks like this,

   <asp:SiteMapDataSource
     ShowStartingNode="False"
     SiteMapProvider="GlobalNavSiteMapProvider"
     id="topSiteMap"
     runat="server"
      StartFromCurrentNode="true" StartingNodeOffset="0"/>

           
    
      

Different styles logos from particular site

By using <% $SPUrl:~site/SitePages/home.aspx %>, you can able to select the particular files from the current site. But this will be applicable only for the master page.

 Eg:
<div id="logo"><a  runat="server" href="<% $SPUrl:~site/SitePages/home.aspx %> ">

<img src="<% $SPUrl:~site/Templatecontent/Images/logo.gif%>"  runat="server" width="105" height="56"  alt="images"/> </a></div>