August 29, 2013

SharePoint Add People Picker using C or aspx, get SPUser from PeoplePicker, Save User and Read pragramatically from/to SPList / Application Page using C#


Create People Picker at run-time using SharePoint C# code, Programmatically.


Code:
protected void CreatePeoplePicker()  
      {  
        permissionPplPicker = new PeopleEditor();  
        permissionPplPicker.MultiSelect = true;  
        permissionPplPicker.AllowEmpty = false;  
        permissionPplPicker.AutoPostBack = true;  
        permissionPplPicker.PlaceButtonsUnderEntityEditor = true;  
        permissionPplPicker.ID = "PeopleEditor";  
        permissionPplPicker.SelectionSet = "User,SPGroup";  
        permissionPplPicker.Rows = 1;  
        permissionPplPicker.BorderStyle = BorderStyle.Outset;  
         //To apply style to people picker or Add SP default css file  
        LiteralControl styleControl = new LiteralControl();  
        styleControl.Text = "<style type='text/css'>.ms-inputuserfield{ font-size:8pt; font-family:Verdana,sans-serif; border:1px solid #a5a5a5;} div.ms-inputuserfield a{color:#000000;text-decoration: none;font-weight:normal;font-style:normal;} div.ms-inputuserfield{padding-left:1px;padding-top:2px;}</style> ";  
        this.Controls.Add(styleControl);  
        this.Controls.Add(permissionPplPicker);  
      } 




Create People picker SharePoint Application page .aspx Page ,



Code:
<table style="MARGIN-TOP: 8px" class='ms-formtable' border='0' cellspacing='0' cellpadding='0' width="100%">  
                   <tr>  
         <td class='ms-formlabel' valign='top' width='190' nowrap>  
           <h3 class='ms-standardheader'>  
             <nobr>People picker control<span class='ms-formvalidation' title="This is Required filed."> *</span></nobr>  
           </h3>  
         </td>  
         <td class='ms-formbody' valign='top'><span dir='none'>  
           <SharePoint:PeopleEditor ID=" pplPicker " runat="server" AutoPostBack="false" MultiSelect="false" MaximumEntities="1" ValidatorEnabled="true" SelectionSet="User" CssClass="ms-long" Width="99%" EnableViewState="true" />  
           <SharePoint:InputFormRequiredFieldValidator ID="ADValidator" runat="server" Display="Dynamic" SetFocusOnError="true"  
             ControlToValidate="pplPicker" BreakBefore="true" ErrorMessage="You must specify a value for this required field." />  
         </span></td>  
       </tr></table> 


Get SPUser or SharePoint web user from People picker Programmatically C#




Code:
SPUser oUser = null;

if (pplPicker.Entities.Count > 0)
     {
        PickerEntity ppl = (PickerEntity) pplPicker.Entities[0];
        oUser = SPContext.Current.Web.EnsureUser(ppl.DisplayText);
      }

For more than one User we can iterate pplPicker.Entities collection in foreach loop.

Or you can use ResolvedEntities in place of .Entities

Save or update people picker User / SPUser programmatically in/to SharePoint List Item


Code:
using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
    {
      using (SPWeb oWeb = oSite.OpenWeb("//Site Relative Url//", false))
        {
  try
   {
    /*Getting Item by List Item ID and saving User to the list */
    SPListItem user = oWeb.Lists["User List"].GetItemById(Convert.ToInt32(ItemID))

    /* oUsercan be get from people picker by referring above code*/
    user["Team Lead"] = oUser;
    adminWeb.AllowUnsafeUpdates = true;
    user.Update();
   }
  catch(SPException ex){ }
  finally
  {
   adminWeb.AllowUnsafeUpdates = false;
   adminWeb.Dispose();
  }
  }
 }

Get SharePoint user / SPUser from SharePoint List using C# / Programmatically




Code:
/* Calling GetSPUserMethod to get User from List*/

SPListItem oItem = oWeb.Lists["User List"].GetItemById(Convert.ToInt32(ItemID));
SPUser oUser = GetSPUser(oItem, "User");
protected SPUser GetSPUser(SPListItem item, string user)
        {
            SPUser oUser = null;
            SPFieldUserValue userValue = new SPFieldUserValue(item.Web, Convert.ToString(item[user]));

            if (userValue != null)
            {
                oUser = userValue.User;
            }
            return oUser;
        }



 --
Regards,
Praveen Pandit
MCTS; MCPD
Keep Sharing Knowledge!!

August 08, 2013

How to Write and Pass CamlQuery to get Sharepoint 2010 / SharePoint 2013 list items in SPQuery or in CamlQuery objects





if in you Client object Model code CamlQuery returning all data or C# Server object model SPQuery / CamlQuery returning all data so there may be issue with way of writing Query, it happens due to small mistake while copy pasting query from caml query builder to our code. It is very small thing that need to take care while pasting query to CamlQuery or SPQuery object,

Client Object Model:

   <View><Query>
            
<Where>
                 <And>
                   <Eq>
                      <FieldRef Name='Title' />
                        <Value Type='Text'>" + t1 + @"</Value>
                   </Eq>                
                 </And>
                </Where>
   </Query></View>


Server Object Model



<View><Query>
            <Where>
                 <And>
                   <Eq>
                      <FieldRef Name='Title' />
                        <Value Type='Text'>" + t1 + @"</Value>
                   </Eq>                 
                 </And>
                </Where>
 </Query></View>



 Sample

         


Code:
using (ClientContext clientContext = new ClientContext(txtSiteUrl.Text))
     {
       CamlQuery oQuery = new CamlQuery();
       oQuery.ViewXml = @"<View><Query><Where>
                                          <And>
                                            <Eq>
                                               <FieldRef Name='Title' />
                                              <Value Type='Text'>" + t + @"</Value>
             </Eq>                                          
                                          </And>
                                       </Where></Query></View>";

     List oList = clientContext.Web.Lists.GetByTitle("myList");
     if (oList != null)
        {
            ListItemCollection  oColl=oList.GetItems(oQuery);
            clientContext.Load(oColl);
            clientContext.ExecuteQuery();   
        }
     }




In short while working in Client object Model you should append your Query between <Query><View> </View></Query>like below:

<View><Query>Your Caml Query</View></Query>

And while working in Server object model remove Query tag from caml query which is copied from caml query builder like 

<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>Praveen</Value></Eq></Where>



Please share any issue or findings in this.

 



 --
Regards,
Praveen Pandit
MCTS; MCPD
Keep Sharing Knowledge!!