Tuesday, June 26, 2012

How to create SharePoint User Group and Assign Permissions


There are some cases where you want to create a group pro grammatically and want to assign permission. e.g. on the Feature receiver (Feature Activated) code.

In this post i am going to explain you how to create group and to assign permissions to this group.
First get the collection of site groups.

SPGroupCollection groups = web.SiteGroups;

web.BreakRoleInheritance(false);
Add the group to this collection. I have created "Test Group" in this example.

groups.Add("Test Group", web.CurrentUser, null, "");
SPGroup grp= web.SiteGroups["Test Group"];          

AllowMembersViewMembership property of this group to false.

This  Gets or sets a Boolean value that specifies whether only group members are    allowed to view the list of members in the group.
grp .OnlyAllowMembersViewMembership = false;
        grp .Update();

Now create a Role Assignment object of this group.

SPRoleAssignment asgn = new SPRoleAssignment(web.SiteGroups[ "Test Group"]);

Create a Role Definition, Here i have used the "Administrator" role, other available roles are

1) None
2) Guest
3) Reader
4) Contributor
5) WebDesigner
6) Administrator  

            SPRoleDefinition role = web.RoleDefinitions.GetByType(SPRoleType.Administrator);

Now assign the Role to the Role Assignment and add the  Role Assignment to the web and update the web

            asgn.RoleDefinitionBindings.Add(role);
            web.RoleAssignments.Add(asgn);
            web.Update();

Now deploy the solution and check the group and its permissions.

I have used this code on the feature activated code that creates group and assign permissions to this.

Tuesday, June 19, 2012

Create SharePoint Lookup Field Programmatically


Lets see how to create a lookup field in a list programmatically

Lets you have a list named "Expense" and another list "Expense Category"

In the "Expense" list you want a lookup field from "Expense Category" list on "Expense Category" field

First add a lookup field named "Category" in the "Expense" list as

   SPList Expense = web.Lists.TryGetList("Expense");
   SPList ExpenseCategory = web.Lists.TryGetList("Expense Category");

   SPFieldCollection _fields = Expense.Fields;

   _fields.AddLookup("Category", ExpenseCategory.ID, true);

In above code i get the collection of fields from the "Expense" list and added a lookup field named "Category" and passed the

GUID of "Expense Category" list from lookup is to be set and set required to true.

Now get the recently created lookup field as

   SPFieldLookup Category = Expense.Fields["Category"] as SPFieldLookup;

Set the lookup field from the "Expense Category" list, Field "Expense Category" and update the field

   Category.LookupField = ExpenseCategory.Fields["Expense Category"].InternalName;


   Category.Update();


deploy the solution and verify the lookup field created in the list

Friday, June 15, 2012

Programmaticlly Create Choice Field with Default Value in SharePoint


In this post i am explaining how to create a choice field in the list and set its default value pro-grammatically

First create a string collection of choice values that you want to use

  StringCollection _statusTypes = new StringCollection();
            _statusTypes.Add("Complete");
            _statusTypes.Add("Incomplete");

Get the field collection from the list and add new choice field to this


 SPList list = web.Lists[listname];
            SPFieldCollection _fields = list.Fields;


  _fields.Add("MyChoiceField", SPFieldType.Choice, true, false, _statusTypes);

Here "MyChoiceField" is the name of field with _statusTypes choice values.

Next to set the default value of the choice field use the code below

Get the choice field
        SPFieldChoice fieldChoice = (SPFieldChoice)list.Fields["MyChoiceField"];
Set its default value              
      fieldChoice.DefaultValue = "Incomplete";
Set the format dropdown or radio button            
      fieldChoice.EditFormat = SPChoiceFormatType.RadioButtons;
and update the field
      fieldChoice.Update();
Now deploy the solution and add new item in the list you will see the default value set for this choice field

Sunday, May 27, 2012

Run Workflow from Hyperlink in SharePoint List

There is an  easy way for the users to start a workflow from the link instaed of selecting from item menu and then select the workflow from the available workflows and then start workflow from the workflow start form.

In this example i am going to update the list item with the workflow that is triggred from the hyprtlink in the SharePoint list


1) First create a workflow to update any list item in the SharePoint site List.
In the workflow settings click the "Allow this workflow to be manually started" and leave other checkboxes unchecked.

2) Publish the workflow, then go to the list to which this workflow is associated, select any item and then from the item menu select workflows. This will lead you to the workflows form attached with this list.




3) Click on your workflow that you created earliar to update item and this will redirect you the workflow start form.




4) Copy the url of this form from the address bar. This would be like
yoursite/_layouts/IniWrkflIP.aspx?List={9a6f5d9b-f075-43a3-a940-dafd1191477b}&ID=117&TemplateID={7b6230c2-8e22-4e7d-b167-6e68bce3a22c}&Source=yoursite/yourlist/forms/allitems.aspx

This url contains List={guid of list}, ID item id list item, TemplateID={GUID of the workflow} and source={after completion of the workflow it will redirect to this url}

5) Now create a field in this list called "start workflow" of type hyperlink. We will use this field to trigger the workflow.

6) Create another list workflow on this list called "populate start workflow link". Check the "Start workflow automatically when an item is created" in the properties window of this workflow

a) In step 1 of the workflow, create a variable named link of string type and set its value to the url of the workflow start form we copied in the step 4 as described in the following image.After the url put a comma',' and put a white space and then put a word you want to display in list otherwise it will show whole url. In this example i have used the "Publish". See image below


b) Now create another action "Update List Item". In the Item select current item and the set the field "start workflow" to this varibale as described in the below image. I have used the "Publish" field in this example.



c) Now save and publish the workflow. Whenever new item will be created a link will be created in the list and that link will redirect you to the satrt workflow form.






This is an effective and easy way for the end users to start workflow from the hyperlink field in the list


Thursday, May 3, 2012

Bulk Delete List Items


How to delete multiple Items from a SharePoint List

There are scenarios where you want to delete multiple list items at once. Insetad of using delete method of SPListItem you can use the following code that deletes multiple list items that uses batch process.

  void DeleteBulkItems(SPWeb web,SPList list, String Ids)
        {
            StringBuilder sbDelete = new StringBuilder();

            sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

            string command = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar     Name=\"Cmd\">Delete</SetVar></Method>";

            string[] _DeletedIDs = Ids.Split(',');

            foreach (String item in _DeletedIDs)
            {
                sbDelete.Append(string.Format(command, item.ToString()));
            }

            sbDelete.Append("</Batch>");

           web.ProcessBatchData(sbDelete.ToString());
        }

In this method 3 parametrs are there SPWeb, SPList(List name from where you want to delete items) and Ids (List item ids to be deleted).

In above code snippet you can see that i am using a xml batch with command delete to delete list items with the specified List Item ids.

Here is the code snippet from where above function is called ;

SPweb web =SPContext.Current.Web;
SPList list=web.Lists["your list title"];
  SPListItemCollection _coll =  list.Items
  string IDs = string.Empty;
            if (_coll.Count > 0)
            {

                foreach (SPListItem item in _coll)
                {
                    IDs = IDs + string.Format("{0},", item.ID);
}
 

    }


  IDs = IDs.TrimEnd(',');
                DeleteBulkItems(web, list, IDs);

In above code i have used a string variable and that stores the ids of list items separetd by comma and in the end called the "DeleteBulkItems" function with the parameterts and the ids of the items to be deleted.

This is an eaxample of  batch process that deletes the list items.

Thursday, April 26, 2012

SharePoint Modal Dialog


How to use SharePoint Modal Dialog i.e. SPModalDialog

Here are some of the common functions related with this

To open a dialog use the below function in javascript on the html part of the page

function NewItemDialog(url, title) {
        var options = {
            url: url,
            width: 900,
            height: 700,
            title: title,
            dialogReturnValueCallback: DialogCallback
        };
        SP.UI.ModalDialog.showModalDialog(options);
    }

Here options are used to set the properties of the dialog. Some more properties are  showClose, allowmaximize etc.

Most imaportant thing is the "dialogReturnValueCallback" this property is used to get the dialog return value when the dialog is closed.

I called this function from code behind and setting the url and title described below:

string url = SPContext.Current.Web.Url + "/SitePages/NewForm.aspx?PID=" + tocid; lnknewitem.NavigateUrl = "javascript: NewItemDialog('" + url + "','New Item');";

IN above code snippet i used a link button and set its navigate url programmatically and called the Dialog open function.

And the DialogCallback function is


 function DialogCallback(dialogResult, returnValue) {

     
          if (returnValue == "1") {
            var meesageId = SP.UI.Notify.addNotification("Loading", false);
            SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
        }

     
    }

If you want to return value from the modal dialog while closing then use the below function on the modal dialog close function


SP.UI.ModalDialog.commonModalDialogClose(dialogResult, returnVal);

ie.

SP.UI.ModalDialog.commonModalDialogClose(1, "1");

Now when dialogcallback function will fire it will check the return value if it is "1" then it will add notification and refresh the parent page.

you can pass dialogResult, returnVal according to your choice and you can get these values on the parent form using DialogCallback function as described above


To simply close the dialog use the below function on client click event of the button

function CloseForm() {

        window.frameElement.cancelPopUp();

        return false;

    }



If you want to open the new custom page in modal dialog and ribbon is displayed on the modal dialog then use this css trick to hide ribbon

 #s4-ribbonrow
    {
        display: none;
    }








Tuesday, April 10, 2012

A Sandbox Solution,what is and what is not

We all know the limitations of a sandbox solution in SharePoint. A sandbox solution is deployed to a particular site collection's solution gallery rather than to farms's solution gallery as in case of Farm solution. There are also some more limitation in the sandbox solution.

Here I am going to list some of major  limitations:-

1) You can not use any SharePoint control in sandbox solution.e.g spgrid, sharepoint datetime control, people picker etc. You have to rely on the asp.net controls.

2) You do not have access to the layouts folder.

3) You can not use Visual web parts in this rather you can use Visual Studio 2010 SharePoint Power Tools to use visual web parts in sandbox solution.

3) You can not use run with elevated privileges function to override current user's privileges.

4) You can use asp.net file upload control to upload files to SharePoint document library rather you can use silver light client context to upload files.

5) To debug the code you have to attach to the process SPUCWoker process and not to the w3p process as in farm solution.

6) You cannot use SPUtility.SendEmail method to send emails in sandbox solutions

To send email you can follow this useful link

There is SharePoint User Code service that is responsible for the sandbox solution executions.
A sandboxed solution is also not allowed to access anything outside the site collection to which it is deployed. An implication of this is that Features deployed in sandboxed solutions can only be scoped to a site collection or website