Friday, November 6, 2009

Windows Sharepoint - Codes -> Pointing to Share the Knowledge

Hi Friends,
I have learned a some of sharepoint services programming techniques and i've written a combination of vb.net and c#.net both languages are similar to work. just c# have additional concept to learn than VB. So just work around and play around. I think it might be useful for u People. :-) If any Queries Mail me. i'll help u. :-)
Note :
For Beginers to run a console application in the context of Microsoft Windows SharePoint Services 2.0, they must be administrators on the computer where the script is executed. Make sure to add reference which wil be available once if u install sharepoint in your server, so u can insert in application.
How to do that ?

In Solution Explorer, right-click the References node, and then click Add Reference on the shortcut menu. On the .NET tab of the Add Reference dialog box, select Windows SharePoint Services in the list of components, click Select, and then click OK.
On the Visual Studio .NET, File Menu -> New ->Project.
In the New Project dialog box, select Visual Basic Projects or Visual C# Projects in the Project Types box, depending on which language you prefer. In the Templates box, select Console Application. In the Location box, type the path to where to create the application, and then click OK.
And add namespaces in your application when ever you create a new console or asp.net application for sharepoint

Name Spaces Required

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

Ok Let us start :-)

---------------------------------------------------------------------

How do I Lists the Contents of Share point Site ?

[Visual Basic .NET]

Overloads Sub Main(args() As String)
Dim siteCollection As New SPSite("http://phoenix")
Dim sites As SPWebCollection = siteCollection.AllWebs
Dim site As SPWeb
For Each site In sites
Dim lists As SPListCollection = site.Lists
Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString())
Next site
Console.WriteLine("Press ENTER to continue")
Console.ReadLine()
End Sub 'Main
[C#]
static void Main(string[] args)
{
SPSite siteCollection = new SPSite("http://Server_Name");
SPWebCollection sites = siteCollection.AllWebs;
foreach (SPWeb site in sites)
{
SPListCollection lists = site.Lists;
Console.WriteLine("Site: " + site.Name + " Lists: " + lists.Count.ToString());
}
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
Click Start on the Debug menu or press F5 to run the code.
-------------------------------------------------------------------------------------

How to add users to Windows Share point Site Programmatically?

[C#]
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
SPSite oSite = new SPSite("http://phoenix");
SPWeb oWeb = oSite.OpenWeb("/");
oWeb.AllowUnsafeUpdates = true;
string LoginName ="Jayavel";
string Email ="jayavelcs@gmail.com";
string Name ="Jayavel Chakravarthy Srinivasan";
string Notes =" ";
SPRole role = oWeb.Roles["Reader"];
role.AddUser(LoginName, Email, Name, Notes);
role.Update();
}
}
}
---------------------------------------------------------------------------------
How do i Programmatically create a Site ?
C#

//Get reference to the portal
SPSite myPortal = new SPSite("http://localhost);
SPWeb myWeb=portal_site.AllWebs["SiteDirectory"];
SPListCollection myWeblists=myWeb.Lists;
//Get reference to the site directory
SPList siteDir= myWeblists["Sites"];
//Add an new entry
SPListItemCollection listItems = siteDir.Items;
SPListItem item = listItems.Add();
//Assign values to the list columns
item["Title"] = objCommunity.Name;
item["Description"] = objCommunity.Purpose;
//update the new list item
item.Update();
-------------------------------------------------------------------------------------
How do I Create Site ?.

SPWeb web = SPControl.GetContextWeb(Context);
SPSite site = SPControl.GetContextSite(Context);
string url = site.Url + "/sites/" + "site1";
string title = "Site Title";
string description = "Site Description";
string siteTemplate= "STS";
string owner1UserName = web.CurrentUser.LoginName;
string owner1DisplayName = web.CurrentUser.Name;
string owner1Email = web.CurrentUser.Email;
string owner2UserName = "";
string owner2DisplayName = "";
string owner2Email = "";
newSite = site.SelfServiceCreateSite(url, title, description, 1033, siteTemplate, owner1UserName,
owner1DisplayName, owner1Email, owner2UserName, owner2DisplayName, owner2Email);
-------------------------------------------------------------------------------------
How do I Add site to sites list in wss?

SPList list = site.AllWebs["SiteDirectory"].Lists["Sites"];
SPListItem item = list.Items.Add();
item["ows_SiteTitle"] = title;
item["ows_SiteURL"] = url;
item["ows_Description"] = description;
item["ows_Owner"] = owner1DisplayName;
item.Update();
-------------------------------------------------------------------------------------

SharePoint : User Management - WSS

Method 1:

Add user to the site groups

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPRole reader = mySite.Roles["Reader"];
//reader.AddUser(userName,email,displayName,notes);
reader.AddUser("fareast\\jayavel", "jayavelcs@gmail.com", "Jayavel", "Reader");
MessageBox.Show("User addedd");
Method 2:
How do I add role in wss ?

SPWeb newweb = newSite.RootWeb;
newweb.AllowUnsafeUpdates = true;
newweb.Roles.Add("RoleName","Role Description",
newweb.Roles["Administrator"].PermissionMask);
* custom rights example
* newweb.Roles.Add("RoleName","Role Description",
* SPRights.ViewListItems SPRights.ViewPages SPRights.OpenWeb SPRights.BrowseUserInfo);
Method 3:
How do I Add user to role in wss ?

string LoginName ="Login";
string Email ="Email";
string Name ="Name";
string Notes ="Description";
SPRole role = newweb.Roles["Administrator"];
role.AddUser(LoginName, Email, Name, Notes);
role.Update();
-------------------------------------------------------------------------------------
How do I Remove user from the site groups ?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPUser user = mySite.AllUsers["fareast\\pavank"];
SPRole reader = mySite.Roles["Reader"];
reader.RemoveUser(user);
MessageBox.Show("User removed");
-------------------------------------------------------------------------------------
SharePoint : User Management - Sharepoint Portal Server

How do I Add user to the cross - site groups?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPGroup group = mySite.SiteGroups["MyGroup"];
//AddUser(userName,email,displayName,notes);
group.AddUser("fareast\\sumitba", "sumitba@microsoft.com", "sumitba", "Reader");
MessageBox.Show("User addedd");
-------------------------------------------------------------------------------------
How do I Remove user from the cross - site groups ?
SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPGroup group = mySite.SiteGroups["MyGroup"];
SPUser user = mySite.SiteUsers["fareast\\sumitba"];
group.RemoveUser(user);
MessageBox.Show("User Removed");
-------------------------------------------------------------------------------------
How do I Add cross site group ?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPGroupCollection groups = mySite.SiteGroups;
SPUser user = mySite.Users["fareast\\karthisu"];
SPMember member = mySite.Users["fareast\\karthisu"];
groups.Add("NewGroup", member, user, "Test");
MessageBox.Show("Group Added");
-------------------------------------------------------------------------------------
How do I Remove cross site group ?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPGroupCollection groups = mySite.SiteGroups;
groups.Remove("NewGroup");
MessageBox.Show("Group Removed");
-------------------------------------------------------------------------------------
How do I Add site group ?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPRoleCollection siteGroups = mySite.Roles;
siteGroups.Add("MyGroup", "Description", SPRights.ManageWeb SPRights.ManageSubwebs);
MessageBox.Show("Role Added");
-------------------------------------------------------------------------------------
How do I Remove site group ?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPRoleCollection siteGroups = mySite.Roles;
siteGroups.Remove("MyGroup");
MessageBox.Show("Role Removed");
-------------------------------------------------------------------------------------
How do I Set permission to the site group ?

SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPRole reader = mySite.Roles["Reader"];
reader.PermissionMask = SPRights.ManageLists SPRights.ManageListPermissions;
reader.Update();
MessageBox.Show("Permissions updated");
-------------------------------------------------------------------------------------
How do I Add group of users ?
SPWeb mySite = new SPSite("http://phoenix/default.aspx").OpenWeb();
SPUserInfo[] userInfo = new SPUserInfo[2];
userInfo[0].Email = "pavank@microsoft.com";
userInfo[0].LoginName = @"fareast\pavank";
userInfo[0].Name = "Pavank";
userInfo[0].Notes = "Test";
userInfo[1].Email = "sumitbak@microsoft.com";
userInfo[1].LoginName = @"fareast\Sumitba";
userInfo[1].Name = "Sumitba";
userInfo[1].Notes = "Test";
mySite.Roles["Reader"].Users.AddCollection(userInfo);
MessageBox.Show("Users Added");
-------------------------------------------------------------------------------------
How do I Add users to the portal area or portal site level ?

TopologyManager tm = new TopologyManager();
PortalSite ps = tm.PortalSites[ new Uri("http://phoenix") ];
Microsoft.SharePoint.Portal.PortalContext ctx = Microsoft.SharePoint.Portal.PortalApplication.GetContext(ps);
Guid NewsGuid = AreaManager.GetSystemAreaGuid(ctx,SystemArea.News);
PermissionCollection pc = SecurityManager.ManageAreaSecurity(ctx,NewsGuid);
pc.AddUser("fareast\\ramkathi","ramkarthi@microsoft.com","Ram","",PortalRight.AddListItems);
MessageBox.Show("User Added");
-------------------------------------------------------------------------------------
How do I Remove user from portal Area ?

TopologyManager tm = new TopologyManager();
PortalSite ps = tm.PortalSites[ new Uri("http://phoenix") ];
Microsoft.SharePoint.Portal.PortalContext ctx = Microsoft.SharePoint.Portal.PortalApplication.GetContext(ps);
Guid NewsGuid = AreaManager.GetSystemAreaGuid(ctx,SystemArea.News);
PermissionCollection pc = SecurityManager.ManageAreaSecurity(ctx,NewsGuid);
Area news = AreaManager.GetArea(ctx, AreaManager.GetSystemAreaGuid(ctx, SystemArea.News));
SPUser user = news.Web.SiteUsers["fareast\\ramkathi"];
pc.Remove(user);
MessageBox.Show("User Removed");
-------------------------------------------------------------------------------------
How do I Add a user to the portal area level at site group ?

TopologyManager tm = new TopologyManager();
PortalSite ps = tm.PortalSites[ new Uri("http://phoenix") ];
Microsoft.SharePoint.Portal.PortalContext ctx = Microsoft.SharePoint.Portal.PortalApplication.GetContext(ps);
Guid homeGuid = AreaManager.GetSystemAreaGuid(ctx,SystemArea.Home);
Area home = AreaManager.GetArea(ctx, homeGuid);
PermissionCollection spc = SecurityManager.ManageSiteSecurity(ctx);
SPRole reader = home.Web.Roles["Reader"];
//reader.AddUser("domain_name\\alias","email_address","user_name","display_name");
reader.AddUser("fareast\\pavank", "pavank@microsoft.com", "Pavan", "Reader");
MessageBox.Show("User Added");
-------------------------------------------------------------------------------------
How do I Remove a user from the portal area level at site group ?

TopologyManager tm = new TopologyManager();
PortalSite ps = tm.PortalSites[ new Uri("http://phoenix") ];
Microsoft.SharePoint.Portal.PortalContext ctx = Microsoft.SharePoint.Portal.PortalApplication.GetContext(ps);
Guid homeGuid = AreaManager.GetSystemAreaGuid(ctx,SystemArea.Home);
Area home = AreaManager.GetArea(ctx, homeGuid);
PermissionCollection spc = SecurityManager.ManageSiteSecurity(ctx);
SPRole reader = home.Web.Roles["Reader"];
//reader.AddUser("domain_name\\alias","email_address","user_name","display_name");
reader.RemoveUser(home.Web.Users["fareast\\pavank"]);
MessageBox.Show("User removed");
-------------------------------------------------------------------------------------
How do I Add role to the portal area ?

TopologyManager tm = new TopologyManager();
PortalSite ps = tm.PortalSites[ new Uri("http://phoenix") ];
Microsoft.SharePoint.Portal.PortalContext ctx = Microsoft.SharePoint.Portal.PortalApplication.GetContext(ps);
SecurityManager.AddRole(ctx,"Writer","",PortalRight.AddListItems);
MessageBox.Show("Role Added");
-------------------------------------------------------------------------------------
How do I Remove role from the portal area?

TopologyManager tm = new TopologyManager();
PortalSite ps = tm.PortalSites[ new Uri("http://phoenix") ];
Microsoft.SharePoint.Portal.PortalContext ctx = Microsoft.SharePoint.Portal.PortalApplication.GetContext(ps);
Guid homeGuid = AreaManager.GetSystemAreaGuid(ctx,SystemArea.Home);
Area home = AreaManager.GetArea(ctx, homeGuid);
home.Web.Roles.Remove("Writer");
MessageBox.Show("Role removed");
-------------------------------------------------------------------------------------
How do i Create Document Library programmatically?
C#


Code under Main

SPSite oSite = new SPSite("http://phoenix");
SPWeb oWeb = oSite.OpenWeb("/");
oWeb.AllowUnsafeUpdates = true;
SPListTemplate template = null;
template = oWeb.ListTemplates["Document Library"];
System.Guid guid;
guid = oWeb.Lists.Add("Check","Check Document",template);
-------------------------------------------------------------------------------------
How do i Create column for Document Library programmatically?

Code under Main
SPSite oSite = new SPSite("http://phoenix");
SPWeb oWeb = oSite.OpenWeb("/");
oWeb.AllowUnsafeUpdates = true;
dim list as SPList = oWeb.Lists(DOC_LIB_NAME)
'creates a columns project name
list.Fields.Add("Project Name", SPFieldType.Text, True)
-------------------------------------------------------------------------------------
How do I Change permissions of document library or List in wss?

// get list
SPList list = web.Lists["Document Library"];
SPPermissionCollection permissions = list.Permissions;
for( int h = 0 ; h <>{
SPPermission permission = permissions[h];
if( permission.Member.ToString()= ="RoleName")
{
permission.PermissionMask = SPRights.AddListItems SPRights.EditListItems;
h = permissions.Count;
}
}
-------------------------------------------------------------------------------------
How do I add Permissions for a Custom based List ?
namespace ConsoleApplication1
{
class Class1
{
[STAThread] static void Main(string[] args) {
SPSite oSite = new SPSite(http://phoenix/);
SPWeb oWeb = oSite.OpenWeb("/");
oWeb.AllowUnsafeUpdates = true;
SPList DC = oWeb.Lists["Q1"];
SPUser user=oWeb.Users["Jayavel"];
DC.Permissions.Add(user, SPRights.AddListItems);
}
}
}
-------------------------------------------------------------------------------------
How do I Create Folders Programmatically in document library ?

Dim mysite As SPSite
Dim s As SPWeb
mysite = New SPSite(http://phoenix/)
s = mysite.OpenWeb()
s.AllowUnsafeUpdates = True
Dim subFolders As SPFolderCollection = s.Folders(“Dec2006”).SubFolders
Dim subFolder As SPFolder = subFolders.Add(“Dec2006/Test”)
Test is the folder in dec2006 doc library
-------------------------------------------------------------------------------------
How do I Upload files from local folder to document library through console application in wss ?

SPSite oSite = new SPSite(http://phoenix/);
//declaring instance for Opening Target Site
SPWeb oWeb = oSite.OpenWeb(a);
oWeb.AllowUnsafeUpdates = true;
SPListTemplate template = null;
template = oWeb.ListTemplates["Document Library"];
string DOCUMENT_PATH = file.Name;
string DOCUMENT_FULL = path of file in local folder;
string DOCUMENT_DESTINATION = "http://phoenix/Q_ID/" ;
string DESTINATION = DOCUMENT_DESTINATION + DOCUMENT_PATH;
//opening the files from directory as read mode
System.IO.FileStream objStream = new System.IO.FileStream(DOCUMENT_FULL, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader objReader = new System.IO.BinaryReader(objStream);
byte [] arrFileBytes = objReader.ReadBytes((int)objStream.Length);
objReader.Close();
objStream.Close();
System.Net.WebClient objWebClient = new System.Net.WebClient();
objWebClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
//Uploading files from local folder to specified document library
objWebClient.UploadData(DESTINATION, "PUT", arrFileBytes);
//prints a messages if a specified file uploaded successfully
-------------------------------------------------------------------------------------
How do I Upload files in document library by Web application (rename and saves the file in server temp location and upload) ?
Dim UPLOAD_LOCATION As String
Dim strFileName As String = Upload1.PostedFile.FileName
Dim c As String = System.IO.Path.GetFileName(strFileName)
UPLOAD_LOCATION = "C:\WINDOWS\Temp\"
Dim FILE_NAME As String FILE_NAME = DDL_Project_Name.SelectedItem.Text & extension
Try
'saves the file in temporary loaction inside server
Upload1.PostedFile.SaveAs(UPLOAD_LOCATION & FILE_NAME)
Dim destUrl As String = ConfigurationSettings.AppSettings("codcphoenix")
Dim site As SPWeb = New SPSite(destUrl).OpenWeb()
'Uploades file from temprary location to document library
Dim fStream As Stream = File.OpenRead(UPLOAD_LOCATION & FILE_NAME)
Dim contents(fStream.Length) As Byte
fStream.Read(contents, 0, CInt(fStream.Length))
fStream.Close()
'declaring instance the initate class
Dim a As Initate
'calls the function getdate a.getdate()
If site.GetFolder("Dec2006").Exists Then
site.AllowUnsafeUpdates = True
Dim destFolder As SPFolder = site.GetFolder("Dec2006")
‘ If it is sub folder add as site.getfolder(“Dec2006/Test”)
destFolder.Files.Add(FILE_NAME, contents, True)
End If
-------------------------------------------------------------------------------------
How to delete a sub folder in a document library programmatically ?
SPWeb web = new SPSite("site url").OpenWeb();
web.Folders[“Document library name”].SubFolders.Delete(“Folder Name”);
-------------------------------------------------------------------------------------

How do I Delete files from doc library in wss ?

Dim mysite As SPSite
Dim s As SPWeb mysite = New SPSite(“http://phoenix”)
Dim destFolder As SPFolder = s.GetFolder("Dec2006")
FILE_NAME = “Test.Doc” destFolder.Files.Delete(FILE_NAME)
-------------------------------------------------------------------------------------
How do I Check whether Specified list or doc lib available in wss site ?

Dim mysite As SPSite
Dim s As SPWeb mysite = New SPSite(“http://phoenix”)
s = mysite.OpenWeb()
Dim lists As SPListCollection = s.Lists
For j = 0 To lists.Count - 1 'Response.Write(SPEncode.HtmlEncode(lists(j).Title) & "
")
If (SPEncode.HtmlEncode(lists(j).Title) = DOC_LIB_NAME) Then
flag = 1
End If
Next j
-------------------------------------------------------------------------------------
How to restore a specific version back to the document library thro’ programmatically?

There are two ways we can restore the document.
1. SPFileVersionCollection.Restore() method
//restore specific version
versions.Restore(3);
2. SPFile.SaveBinary() method
file.SaveBinary(versions[3].OpenBinary());
But however the Restore method is more efficient as per msdn
-------------------------------------------------------------------------------------
How do Insert Values inside a List ?

Dim mysite As SPSite
Dim s As SPWeb
mysite = New SPSite(“http://phoenix”)
s = mysite.OpenWeb("Op")
Dim listItems As SPListItemCollection = s.Lists("OpSchedule").Items
s.AllowUnsafeUpdates = True
Dim item As SPListItem = listItems.Add()
‘adding value to normal column
item("Opsreview Month-Year") = "Test1"
‘adding value to hyperlink column
item("Summary URL") = http://phoenix/default.aspx,%20OpReports
‘adding value to date column
item("Summary Date") = convert.todatetime("13/1/2007 12:00:00 AM")
item.Update()
-------------------------------------------------------------------------------------
How do Backup wss using stsadm.exe ?
To perform a simple backup of a site, use the following syntax:
stsadm.exe -o backup -url http://server_name/site -filename file_name.dat
To back up a site and overwrite an existing backup file, use the following syntax:
stsadm.exe -o backup -url http://server_name/site -filename local_drive:\path_name\file_name.dat -overwrite

-------------------------------------------------------------------------------------

How do i Restore wss Using stsadm.exe ?

To restore a site from a backup file, either to a new site or a separate server, use the following syntax:
stsadm.exe -o restore -url http://server_name/site -filename file_name.dat

To restore a site from a backup file on a server share, and to overwrite any existing site at the new location, use the following syntax:
stsadm.exe -o restore -url http://server_name/site -filename \\share\folder\file_name.dat -overwrite

1 comment:

sturner333 said...

Jay:
I am using windows 2007. I can not load server 2003 sp1 to get the references I need in .net. Ideas