Pages

Subscribe:

Sunday, October 30, 2011

Read a file in Sharepoint document library


The below Code snippet might be helpful when you want to read a text file or a csv file that you uploaded in your document library via code.
I had a csv file with three columns; and I wanted to extract the data and add them into a list as an new item.
Code : The code reads each line of the csv file and then split the entries(columns) by “,” . If you have a text file then you can either split by space or by characters whatever is your requirement.
string line;
StreamReader file;
string contents = string.Empty;
SPFile spfile = properties.ListItem.File;
if (spfile.Exists)
{
string filePath = oWeb.Url + spfile.ServerRelativeUrl; -> oWeb is SPWeb instance
file = new StreamReader(spfile.OpenBinaryStream());
while ((line = file.ReadLine()) != null) -> Reading line by line of the csv file
{
char[] splitter = { ‘,’ };
String[] Array = line.ToString().Split(splitter);
// Now my Array has all the columns of the first line. I then added it to a new list as an item
using (SPSite oSiteCollection = new SPSite(SiteID))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(WebID))
{
SPList myList = oWeb.Lists["My Custom List"];
SPItem newEntry = myList.Items.Add();
newEntry["Col1"] = Array[0];
newEntry["Col2"] = Array[1];
newEntry["Col3"] = Array[2];
newEntry.Update();
myList.Update();
}}

Enable\Disable Ribbon button by Users Group Sharepoint 2010


In this post we will see a detailed example of how to enable and disable a ribbon button according to the Logged in user’s group. The idea here is to enable the ribbon button if the current user is a part of a pre-specified group (say ListOwners) and disable the same if the user is not one of the added users of the group.
The example uses “EnabledScript” attribute of the CommandUIHandler of the ribbon button to decide whether the button should be enabled or disabled for the loggedin user.
Code Overview -
1.  The below example enables the ribbion button if the current user is a part of a pre-specified group (say ListOwners)
2. The button remains\gets disabled if the user does not exist in the specified group.
3. A separate JavaScript file CheckUserInGroup.js which is deployed in /_layouts/RibbonScripts contains the EnableIfUserInGroup() function. This function is called in EnabledScript and it executes to check if the user exists in the pre-specified group.
Lets Start with creating a Ribbon button first  -
Steps -
1. Create a empty project.
2. Deploy it as a Farm solution.
3. Right click on the feature and click “Add feature”.
4. Right click on the project and add a new “Empty Element” item.
5. Next add the below code to add a custom Ribbon button to your document library.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/” >
<CustomAction
Id=”ButtonForGroupUsersOnly”
Location=”CommandUI.Ribbon”
RegistrationId=”101″
RegistrationType=”List”
Title=”Owners Group Button”>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location=”Ribbon.Library.ViewFormat.Controls._children”>
<Button Id=”Ribbon.Library.ViewFormat.UsersBtn”
Command=”usersBtnCommand”
LabelText=”Group Users Button”
Image32by32=”/_layouts/1033/IMAGES/buttonIcon.jpg”
TemplateAlias=”o1″ />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command=”usersBtnCommand”
CommandAction=”javascript:OwnerBtnscript();“/> 
–> Refer Your Function here. This runs after your button is clicked
EnabledScript=”javascript:EnableIfUserInGroup();” -> Enable Ribbon function here
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>
//Referencing the Script
<CustomAction
Id=”OwnersButton.Script”
Location=”ScriptLink”
ScriptSrc =”/_layouts/RibbonScripts/CheckUserInGroup.js”/>
</Elements>
The Group Users Button created in the above code will be in the disabled mode on page load. The code inEnableIfUserInGroup(); will determine if the current  user is added to the specified group and the button needs to be enabled.
The CustomAction ScriptLink refers to the path of the CheckUserInGroup.js file which containsEnableIfUserInGroup(); and other JavaScript functions.
6. Next add a Javascript file in your project “CheckUserInGroup.js” and add it under Layouts -> RibbonScripts folder. Create Layouts folder using Add-> “Sharepoint Layouts Mapped Folder” .
7. Next, the following goes in your CheckUserInGroup.js file
<script src=”/_layouts/SP.js” type=”text/ecmascript”></script>
<script type=”text/javascript”>
// The below is called by EnabledScript in ribbon button
function EnableIfUserInGroup() {
var _userInGroup;
if (UserExistInGroup == null)
CheckUser();
else {
_userInGroup = UserExistInGroup;
UserExistInGroup = null;
return _userInGroup;
}
}
// The below checks if the user exists in the group
function CheckUser()
{
var clientContext = new SP.ClientContext();
var groupCollection = clientContext.get_web().get_siteGroups();
// Get the Our Group’s ID
var _group = groupCollection.getById(10); ->> ID of the Group that we are checking against e.g. ListOwners group
var users = _group.get_users(); ->> Get all Users of the group
clientContext.load(_group);
clientContext.load(users,’Include(loginName)’);
this._currentUser = clientContext.get_web().get_currentUser(); ->> Get current user
clientContext.load(this._currentUser,’Include(loginName)’);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
RefreshCommandUI(); ->> Refreshes the Ribbon again to pick up the new value for UserExistInGroup
}
//The below Checks  if User is the member of the specified group
function onQuerySucceeded() {
if(users.count >0)
{
UserExistInGroup = false;
for(var i=0; i < users.count; i++)
{
if(users[i].get_loginName() == this._currentUser.get_loginName())
{
UserExistInGroup = true;
}
}
}}
function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
</script>
8. Next Build and deploy.


Friday, October 28, 2011

Programmatically create a new content type in sharepoint 2010

Here is the code snippet for creating a content type in a document library using object model.

Public void CreateContentType(string _contentTypename, sting _fullFilePath,SPweb currentWeb)
{

SPFile myFile = currentWeb.GetFile(fullFilePath);

if (currentWeb.AvailableContentTypes[contentTypename] == null)
{
var myContentType = new SPContentType(currentWeb.AvailableContentTypes[new SPContentTypeId("0x0101")], currentWeb.ContentTypes, “contenttypename”)
{
DocumentTemplate = myFile.ServerRelativeUrl,
Description = “My custom Content type”
}

currentWeb.ContentTypes.Add(myContentType);
}

SPDocumentLibrary myDocLib = (SPDocumentLibrary) currentWeb.Lists["doclibname"];

myDocLib.ContentTypesEnabled = true;
myDocLib.ContentTypes.Add(currentWeb.AvailableContentTypes["contenttypename"]);

myDocLib.Update()

}

Create content Type Client object model Sharepoint 2010

Steps to create a Content type using Client object model are

1. To create a content type using the client object model in Visual Studio 2010, create a new project (File ➪ New ➪ Project) and select a Console project template.
2. After the project starts, you will add references to the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll assemblies located in the 14\ISAPI folder also listed under the .NET component listing in the Add References dialog box.
3. Next, write the code below in you main method. Please note that unlike, server object model, client object model makes use of an Information class that contains the template of the content type. The information class works in a similar manner to the SPContentType class with the exception of the parent ’ s reference; rather than pass in a reference to the parent ’ s content type, client object model code gets the parent ’ s ID.

static void Main(string[] args)
{
// Get a reference to the site collection
ClientContext clientContext = new ClientContext(“http://SPsite”);
Web web = clientContext.Web;

// Load reference to content type collection
ContentTypeCollection contentTypes = web.ContentTypes;
clientContext.Load(contentTypes);
clientContext.ExecuteQuery();
// Create a Content Type Information object
ContentTypeCreationInformation _customcontenttype = new ContentTypeCreationInformation();
customcontenttype.Name = “Custom Content type”;
customcontenttype.ParentContentType = contentTypes.GetById(“ADD PARENT CONTENT TYPE ID”);
customcontenttype.Group = “Custom content type group”;
// Create the content type
ContentType myContentType= contentTypes.Add(customcontenttype);
clientContext.ExecuteQuery();
}

4. After the Information object is completed, a ContentType object is added to the ContentTypes collection that you loaded with the ClientContext using the Information object.

Tuesday, September 20, 2011

Failed to Create The Configuration Database

SharePoint Products Configuration Wizard
Configuration Failed
Failed to create the configuration database
An exception of type System.IO.FileNotFoundException was thrown. Additional exception information: Could not load file or assembly 'Microsoft.IdentityModel, version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.



Cause.

This error is not related to installing or configuring SQL Server 2008 for SharePoint 2010. This error is about the Geneva Framework.


Solution.

Please uninstall the Geneva Framework. Run SharePoint 2010 setup and click on "Install Software Prerequisites" to download and install the version of Geneva Framework needed by SharePoint 2010.