Ads

Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Tuesday, 14 March 2017

C# code to create page layout in SharePoint 2010 using visual studio 2010

We normally use SharePoint Designer to create page layout. We can also do this by using visual studio.

Here we are article page as parent page. So need to activate two features
       a) SharePoint Server Publishing Infrastructure. [Site Collection Feature]
       b) SharePoint Server Publishing. [Manage Site Features]

If these two features are not activated then we wont see article page content type in Content Types. see the image.
activate these two features
1) Open visual studio --> File--> New --> Project --> Select SP 2010 --> Select Content Type  template --> project name.
3) Specify URL location for debugging and deploying this solution as sandbox solution for testing purpose only.
4) Choose Content Type from the drop down here am selecting 'Article Page' and Click on Next.
5) Now it will automatically open Elements.xml file of ContentType1. Now modifying Name of the Content Type and save the file.
6) Now Add Module for actual pagelayout name it as PageLayoutModule
By default module has two files one is Elements.xml and sample.txt
7) Now delete sample.txt file from PageLayoutModule
8) Now adding pagelayout page i.e UdayPageLayout.aspx to PageLayoutModule.
9) Design pagelayout. Here am adding one table in that am adding three webpart zones.
These webpart zones are used to place webpart.
here the code which i was used.

 <%@ Page Language="C#" Inherits="Microsoft.SharePoint.Publishing.PublishingLayoutPage,Microsoft.SharePoint.Publishing,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePointWebControls" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="PublishingWebControls" Namespace="Microsoft.SharePoint.Publishing.WebControls"
    Assembly="Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="PublishingNavigation" Namespace="Microsoft.SharePoint.Publishing.Navigation"
    Assembly="Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:content contentplaceholderid="PlaceHolderPageTitle" runat="server">
<SharePointWebControls:FieldValue id="PageTitle" FieldName="Title" runat="server" />
</asp:content>
<asp:content contentplaceholderid="PlaceHolderMain" runat="server">
<table cellspacing="0" border="0" width="100%" cellpadding="0>
  <tr>
       <td width="100%">
       <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Top" Title="loc:Top" />
       </td>
       </tr>
       <tr>
       <td>
       <table width="100%">
       <tr>
       <td width="50%">
       <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Left" Title="loc:left" />
       </td>
       <td width="50%">
       <WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="Right" Title="loc:right" />
       </td>
       </tr>
       </table>
       </td>
       </tr>
       </table>
</asp:content>

10) Now open Elements.xml which is under PageLayoutModule and it looks like this.
11) Now change File tag's URL attribute because inorder to display your custom pagelayout in pagelayouts(which is in ribbon while the page in edit mode).
12) Now am adding properties to page layout. in this we specify Title of the page layout and ContentType i.e pagelayout content type and PublishingAssociatedContentType i.e name of the parent content type and Content Type ID of the Elements.xml which is under ContentType1.
And also Add URL attribute in Module tag.
13) Now open Features-->Feature1, ContentType1 and PageLayoutModule are in Items in the Solution.
Move these two items to Items in the Feature.
15) Now deployee the solution.
After successfully solution deploye. The page layout is available at http://<<server>>:<<port>>/_Catalogs/masterpage (_Catalogs/masterpage) is specified in pagelayoutmodule.
To go that page follow these steps
16) Now open your site --> site actions -->site settings, Click on Master pages and layouts which is uder Galleries.
17) Now you can find newly deployed pagelayout file in the list of files and its status as "Draft".
18) Now checkin the newly added pagelayout file. we can do it in two ways. one is through ribbon and through item menu.
19) While checkin select major version and add your comments and click on "OK".
20) Now the pagelayout status changes to pending it means we need to approve it.
Select the pagelayout and click on "Approve/Reject" from ribbon.
21) Then select "Approved" radio button in Approval Status. Click on "OK".
22) Now the pagelayout file status is approved, so that pagelayout is available.
23) Now Go to Site Actions --> More Options.
24) Select Page in left panel and click on Publishing page.Now click on Create.
25) Now you can see newly added pagelayout as (Name of the content type which is in Elements.xml file under layout1) Title value in Elements.xml which is under PageLayoutModule.i.e (CustomePagelayoutSample) Custome Page Layout.
now click on Create.
26) Now you can aslo see the newly added content page layout in page layouts(which is in ribbon).
Now you can add your webparts in webpart zones. And CheckIn Then Publish the page.
Refer: c-sharpcorner

Tuesday, 7 March 2017

C# code to get Last Modified Date of a SharePoint Site/web Programmatically

using (SPSite siteCollection = new SPSite("siteurl"))
{
  SPWebCollection sites = siteCollection.AllWebs;

  foreach (SPWeb site in sites)
  {
    DateTime dt = site.RegionalSettings.TimeZone.UTCToLocalTime(site.LastItemModifiedDate);
    Console.WriteLine("site::::{0} Modified time::::{1}", site.Title, dt.ToString());

  }
}




Use C# code to create new Web Application in Sharepoint 2010 Enabling FBA


SPWebApplicationBuilder webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
webAppBuilder.Port = portNo;webAppBuilder.ApplicationPoolId = "IIS application ID";
webAppBuilder.IdentityType = IdentityType.SpecificUser;
webAppBuilder.ManagedAccount = mngAcc;
webAppBuilder.RootDirectory = new DirectoryInfo("physical path of web application"));
webAppBuilder.ServerComment = "Server comment";
webAppBuilder.UseNTLMExclusively = true;
webAppBuilder.AllowAnonymousAccess = false;
webAppBuilder.CreateNewDatabase = true;
webAppBuilder.DatabaseServer = "SQL Server name";
webAppBuilder.DatabaseName = "Database name";
if ("SQL Authentication is selected")
{
   webAppBuilder.DatabaseUsername = "username";
   webAppBuilder.DatabasePassword = "password";
}
newApplication = webAppBuilder.Create();
SPFormsAuthenticationProvider fbaAuthProvider = new SPFormsAuthenticationProvider(membershipProvider, roleManager);

newApplication.UseClaimsAuthentication = true;
newApplication.IisSettings[SPUrlZone.Default].AddClaimsAuthenticationProvider(fbaAuthProvider);
newApplication.Update();
newApplication.Provision();

C# code to check user permission in SharePoint list

The following sample shows how to check adding list item permissions for the current user.
using (SPSite spSite = new SPSite("http://MySiteUrl"))
{
  using (SPWeb spWeb = spSite.OpenWeb())
  {
    // Get the current user.
    SPUser currentUser = spWeb .SiteUsers[HttpContext.Current.User.Identity.Name.ToString()];
    // Get the list.
    SPList spList = spWeb.Lists["MyList"];
    // Variable to determine permission.
    bool userPermission = spList.DoesUserHavePermissions(currentUser, SPBasePermissions.AddListItems);
    if ( userPermission )
    {
      // Perform operation here.
    }
  }
}

The local variable "userPermission" will set to True if the user can add items in list otherwise it will set to false.
Similarly,
For viewing list item
   bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.ViewListItems);
For editing list item
   bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.EditListItems);
For deleting list item
   bool userPermission = spList.DoesUserHavePermissions(loginUser, SPBasePermissions.DeleteListItems);

Friday, 17 February 2017

News Tickers in SharePoint 2013 using JQuery

Lets create a custom list called "News"
We will get news text from title of this list and display in SharePoint page page

VS --> New Project --> SP 2013 empty project --> Deploy as a farm solution
Add new item --> Visual web part
Add jQuery reference to layout folder & add its reference in ascx page of web part

Add script in same page:
< script > $(document).ready(function() {
    $('#NewsTicker').vTicker({
        speed: 500,
        pause: 3000,
        showItems: 1,
        animation: 'fade',
        mousePause: true,
        direction: 'up' /*Text direction*/
    });
}); < /script>

Add style CSS in same page:
<style type="text/css" media="all">
    #NewsTicker
    {
        width: 844px;
        margin: auto;
    }

    #NewsTicker ul li div
    {
        height:30px;
        background: Yellow;
    }

    <div style="width:1310px; height:30px; border-style:solid; border-width:2px; border-color:#FFCB05">
        <div style="float:left;background-color:White; height: 27px; width: 118px;">
            <h2 style="font-family:Arial; font-size:22px; background-color:#FFCB05; color:Black;">News</h2>
        </div>
        <div id="NewsTicker" style="float:left; padding-left:15px; font-size:24px; font-family:Arial; height: 29px;">
            <ul style="width: 920px">
                <asp:Literal ID="ltNews" runat="server" Text=""></asp:Literal>
            </ul>
        </div>
    </div>
</style>

Now write C# code in page load to bind data:
private void BindData()
{
    Guid siteId = SPContext.Current.Site.ID;
    Guid webId = SPContext.Current.Web.ID;
    StringBuilder sb = new StringBuilder();
    SPSecurity.RunWithElevatedPrivileges(delegate
    {
        using(SPSite site = new SPSite(siteId))
        {
            using(SPWeb web = site.OpenWeb(webId))
            {
                SPList list = web.Lists.TryGetList("News"); /*Create the list*/
                if (list != null)
                {
                    foreach(SPListItem item in list.Items)
                    {
                        sb.AppendLine("<li>");
                        sb.AppendLine("<div>");
                        sb.AppendLine(item.Title); /*Get the title column*/
                        sb.AppendLine("</div>");
                        sb.AppendLine("</li>");
                    }
                }

            }
        }
    });
    ltNews.Text = sb.ToString();
}

Finally deploy and add this webpart in page to see the result

Tuesday, 14 February 2017

Connect SharePoint online using CSOM from console application


Create new console application project in VS 2013
R-click on References in the Solution Explorer --> click on Manage NuGet Packages.
Search for Microsoft.SharePointOnline.CSOM and then click on Install

Code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Security;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.SharePoint.Client;
    namespace CSOMOffice365  
    {
        class Program  
        {
            static void Main(string[] args)  
          {
                string userName = "BlaBla.onmicrosoft.com";
                Console.WriteLine("Enter password.");
                SecureString password = GetPassword();  
                using(var clientContext = new ClientContext("SharePoint site URL"))  
                {
                    // SharePoint Online Credentials
                    clientContext.Credentials = new SharePointOnlineCredentials(userName, password);  
                    Web web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    Console.WriteLine("Title: " + web.Title + "; URL: " + web.Url);
                    Console.ReadLine();
                }
            }
            private static SecureString GetPassword()
          {
                ConsoleKeyInfo info;
                SecureString securePassword = new SecureString();
                do  
                {
                    info = Console.ReadKey(true);
                    if (info.Key != ConsoleKey.Enter)  
                    {
                        securePassword.AppendChar(info.KeyChar);
                    }
                }
                while (info.Key != ConsoleKey.Enter);
                return securePassword;
            }
        }
    }


Wednesday, 3 August 2016

difference between Feature.xml, Manifest.xml, Elements.xml & Onet.xml in SharePoint

  • Feature.xml
    • Defines a Feature 
    • Specifies the location of assemblies, files, dependencies, or properties that support the Feature.
  • Manifest.xml -
    • Used during the deployment of a .wsp solution package.  
    • It tells SharePoint what files to copy, what features to install, where to put your binaries, adds SafeControl entries, as well as set code access security.
  • Elements.xml -
    • This is a definition file for the module. 
    • Contains the actual feature element like list instance,  field, Content type, list template, workflow..etc
    •  
  •  Onet.xml
    •  Depending on where an Onet.xml file is located and whether it is part of a site definition or a web template, the markup in the file does some or all of the following:
      • Specifies the web-scoped and site collection-scoped Features that are built-in to websites that are created from the site definition or web template.
      • Specifies the list types, pages, files, and Web Parts that are built-in to websites that are created from the site definition or web template.
      • Defines the top and side navigation areas that appear on the home page and in list views for a site definition.
      • Specifies the list definitions that are used in each site definition and whether they are available for creating lists in the user interface (UI).
      • Specifies document templates that are available in the site definition for creating document library lists in the UI, and specifies the files that are used in the document templates.
      • Defines the base list types from which default SharePoint Foundation lists are derived. (Only the global Onet.xml file serves this function. You cannot define new base list types.)
      • Specifies SharePoint Foundation components.
      • Defines the footer section used in server email.
      •  

Tuesday, 10 March 2015

Sharepoint 2010 Code Samples from Microsoft


SharePoint 2010: Developing Styled Master Pages
SharePoint 2010: Developing Delegate Controls
SharePoint 2010: Performing Cross-List Queries
SharePoint 2010: Using JavaScript to Edit and Save Values in Items
 
SharePoint 2010: Using JavaScript to Get Details About Site Collections
SharePoint 2010: Using JavaScript to Show Dialog Boxes
SharePoint 2010: Developing Connected Web Parts
SharePoint 2010: Developing Connected Silverlight Web Parts

SharePoint 2010: Developing Application Pages
SharePoint 2010: Programmatically Reading User Profile Properties
SharePoint 2010: Displaying User Profile Pictures Programmatically
SharePoint 2010: Developing Event Receivers
 
SharePoint 2010: Using REST to Obtain Excel Charts
SharePoint 2010: Creating Custom Timer Jobs
SharePoint 2010: Creating List Items from Silverlight
SharePoint 2010: Retrieving Single List Items in REST Requests
 
SharePoint 2010: Developing Starter Master Pages
SharePoint 2010: Working with Disposable Objects
SharePoint 2010: Displaying Video Files Stored in Azure
SharePoint 2010: Logging Site Events Programmatically
 
 
SharePoint 2010: Using JavaScript to Retrieve and Interrogate Items in Lists
SharePoint 2010: Querying SQL Azure Data from Web Parts
SharePoint 2010: Developing Feature Receivers
SharePoint 2010: Developing Custom Navigation Providers
 
SharePoint 2010: Developing Workflow Activities
SharePoint 2010: Calling Azure Services from Custom Workflow Activities
SharePoint 2010: Using REST to Discover the Contents of Excel Worksheets
SharePoint Online: Authenticating Using the Client-Side Object Model
 
SharePoint 2010: Creating Custom Field Types
SharePoint 2010: Calling Azure Services from Web Parts
SharePoint 2010: Developing State Machine Workflows
SharePoint 2010: Canceling Synchronous Events
 
SharePoint 2010: Using JavaScript to Update Site Properties
SharePoint 2010: Developing Sequential Workflows
SharePoint 2010: Calling Azure Services from Timer Jobs
SharePoint 2010: Using REST to Query Data Ranges in Excel Worksheets
 
SharePoint 2010: Retrieving List Contents and Parsing Atom Responses
SharePoint 2010: Developing Web Templates
SharePoint 2010: Declaring Records Programmatically
SharePoint 2010: Performing Cached Cross-Site Queries
 
SharePoint 2010: Creating Content Organizer Rules Programmatically
SharePoint 2010: Developing Custom Expiration Actions
SharePoint 2010: Developing Custom Expiration Formulae
SharePoint Online: Creating Excel Worksheets by Using Excel Web App
 
SharePoint 2010: Using JQuery to Retrieve List Contents in JSON
SharePoint 2010: Logging Data to the Developer Dashboard
SharePoint 2010: Creating SQL Azure Records from Web Parts
SharePoint 2010: Developing Page Layouts

SharePoint 2010: Developing Ribbon Actions
SharePoint Online: Creating and Deploying Sandboxed Workflow Activities
SharePoint 2010: Calling WCF Services from Custom Workflow Activities
SharePoint Online: Creating Documents Using Word, PowerPoint, or OneNote Web App

Wednesday, 23 April 2014

IF statements for calculated columns in SharePoint 2010 Lists

Here are some examples of IF statements that can be used in calculated columns.
The IF statement is simply:
IF(condition, ifTrue, ifFalse)
Compare text value:
Scenario: If field1 equals Yes we want to display Approved otherwise display Rejected.
Formula:
=IF([field1]="Yes","Approved","Rejected")
2 conditions must be true using AND:
Scenario: If field1 and field2 both equal Yes then display Approved otherwise display Rejected.
Formula:
=IF(AND([field1]="Yes",[field2]="Yes"),"Approved","Rejected")
Either condition can be true:
Scenario: If field1 OR field2 equal Yes then display Approved otherwise display Rejected.
Formula:
=IF(OR([field1]="Yes",[field2]="Yes"),"Approved","Rejected")
Check if field is blank:
Scenario: If field1 is blank display Approved otherwise display Rejected.
Formula:
=IF(ISBLANK([field1]),"Approved","Rejected")
Compare number column values:
Scenario: If field1 is less than 1 Approved otherwise display Rejected.
Formula:

=IF([field1]<1,"Approved","Rejected")

Export sharepoint user profile properties to excel using C#

This is a short guide on how to export the properties from a Sharepoint 2010 user profile database into a spreadsheet using a simple C# script.

Our end result is to get this export into a format something like:


  1. Open Visual Studio
  2. Create new project - Visual C# > Consolse Application

  1. Name it UserProfileDataExtract
  2. Add the missing references below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
namespace UserProfileDataExtract
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Accessing mysite.......");
 
            //This is the mysite location
            SPSite site = new SPSite("http://mysite/people");

            Console.WriteLine("Site Accessed.......");

            StringBuilder sb = new StringBuilder(); 
 
            //Creating headers in the first row
  sb.Append("Username,"); sb.Append("Firstname,"); sb.Append("Lastname,"); sb.Append("Phone,"); sb.Append("Mobile,");
            sb.Append("Email,");
            sb.Append("Manager,");
            sb.Append("JobTitle,");
            sb.Append("\r\n");
  
            Console.WriteLine("Using Site.......");
            using (site)
            {
                Console.WriteLine("Get Context and profile manager.......");
                SPServiceContext context = SPServiceContext.GetContext(site);
                UserProfileManager profileManager = new UserProfileManager(context);

                //Loop through all the user profiles in the sharepoint database
                Console.WriteLine("Starting Loop.......");
                foreach (UserProfile profile in profileManager)
                {
                   //Retrieve the profileimage values for current user
                    string strName = Convert.ToString(profile[PropertyConstants.UserName].Value);
                    string FName = Convert.ToString(profile[PropertyConstants.FirstName].Value);
                    string LName = Convert.ToString(profile[PropertyConstants.LastName].Value);
                    string Phone = Convert.ToString(profile[PropertyConstants.WorkPhone].Value);
                    string Mobile = Convert.ToString(profile[PropertyConstants.CellPhone].Value);
                    string Email = Convert.ToString(profile[PropertyConstants.WorkEmail].Value);
                    string Manager = Convert.ToString(profile[PropertyConstants.Manager].Value);
                    string JobTitle = Convert.ToString(profile[PropertyConstants.JobTitle].Value);
                    Console.WriteLine("Processing: " + strName);
sb.Append(strName + ","); sb.Append(FName + ","); sb.Append(LName + ","); sb.Append(Phone + ","); sb.Append(Mobile + ","); sb.Append(Email + ","); sb.Append(Manager + ","); sb.Append(JobTitle.Replace(",", "-") + ",");
                    sb.Append("\r\n");
               }
          Console.WriteLine("Finished profile retrieval");
          Console.WriteLine("Writing to csv file");
          //Write the long string to a csv file and save it to the desktop
          TextWriter tw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + "SharePointUserData.csv");
          tw.WriteLine(sb.ToString());
          tw.Close(); 
          } 
      }//End Main
    }//End class
 }

Thursday, 26 December 2013

Create an Event Receiver to start Nintex Workflow

public override void ItemUpdating(SPItemEventProperties properties)
 {
SPWorkflowManager WfManager = properties.ListItem.ParentList.ParentWeb.Site.WorkflowManager;
SPWorkflowAssociationCollection wfAssociationCollection = properties.ListItem.ParentList.WorkflowAssociations;
SPWorkflowAssociation wfAssociation = wfAssociationCollection.GetAssociationByName("HistoricalDataAudit", System.Threading.Thread.CurrentThread.CurrentCulture);
 

foreach (SPWorkflowAssociation wfAssociationCollectionItem in wfAssociationCollection)
{
  WfManager.StartWorkflow(properties.ListItem, wfAssociationCollectionItem,"");

}

Sunday, 14 July 2013

Change master page as per logged in user group

we will discuss how you can change the master page for your site according to some logic like you can change the master page for a logged in user or simply can switch the application.master page to your custom master page for all applictaion pages.
I achive written a Step-by-step sample code to switch mater page according to logged in user's group.

The Steps to Create a Custom httpModule for Changing master page for a logged in user are :
1. Create a new Class Library project in Visual Studio name it as CustomhttpModule
2. Add the below code in your class file.
using System;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
namespace SwitchMasterPage{
public class CustomHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
// register handler for PreInit event
page.PreInit += new EventHandler(page_PreInit);
}
}
void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null)
{
SPSite site = SPContext.Current.Site;
using (SPWeb web = site.OpenWeb())
{
if (web.CurrentUser != null)
{
SPGroupCollection userGroups = web.CurrentUser.Groups; // Check all the groups user belong to
foreach (SPGroup group in userGroups)
{
if (group.Name.Contains(“OurCustomgroupName”)
// Switch the master page.
page.MasterPageFile = “/_catalogs/masterpage/MyCustom.master”;
}}}
}}
public void Dispose() { /* empty implementation */ }
}
}
it’s important to remember that an HttpModule cannot be deployed in a WSS farm for an individual site collection. Instead, an HttpModule must be configured as an all-or-nothing proposition at the Web application level.
3. Now, sign the project and build it.
4. Drag and Drop the signed assembly in GAC.
5. Next, we need to register this CustomhttpModule in our SharePoint webconfig. To do this add the below under <httpModules> tag in your web app’s web.config fie.
<add name=”CustomHttpModule” type=”SwitchMasterPage.CustomHttpModule,  SwitchMasterPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7ebdb1031dfc1e406?/>
And you are Done!

Monday, 8 July 2013

C# code to create Terms and Term Set programmatically (using code)?

Add reference of "Microsoft.SharePoint.Taxonomy" assembly to your project. Include namespace "Microsoft.SharePoint.Taxonomy". And use the code as listed below.


 using (SPSite site = new SPSite("Site URL"))
            {
                TaxonomySession _TaxonomySession = new TaxonomySession(site);

                //Get instance of the Term Store 
                TermStore _TermStore = _TaxonomySession.TermStores["My Term Store"];

                //Now create a new Term Group
                Group _Group = _TermStore.CreateGroup("My New Group");

                //Create a new Term Set in the new Group
                TermSet _TermSet = _Group.CreateTermSet("My New Termset");

                //Add terms to the term set
                Term _term1 = _TermSet.CreateTerm("First Term", 1033);
                Term _term2 = _TermSet.CreateTerm("Second Term", 1033);
                Term _term3 = _TermSet.CreateTerm("Third Term", 1033);
                Term _term4 = _TermSet.CreateTerm("Last Term", 1033);

                //commit changes
                _TermStore.CommitAll();

            }

C# code to create SharePoint Views (SPView) Programmatically

SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["My List"];

SPViewCollection allListViews = list.Views;
string viewName = "My New View";

StringCollection newviewFields = new StringCollection();
viewAllContactFields.Add("Edit");
viewAllContactFields.Add("LinkTitleNoMenu");
viewAllContactFields.Add("Field1");
viewAllContactFields.Add("Field2");
viewAllContactFields.Add("Field3");


string myquery = "<OrderBy><FieldRef Name='LinkTitle' Ascending='TRUE' /><FieldRef Name='EffectiveDate' Ascending='TRUE' /></OrderBy>";

allListViews.Add(viewName, newviewFields, myquery, 30, true, false);

Ads