Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Monday, 9 December 2013

SharePoint Get List AttachMents

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
debugger;
 var ctx=new SP.ClientContext("http://nit-hv5-idm2:11111/sites/hr/referral");
  var list = ctx.get_web().get_lists().getByTitle("Job Opening");
 var query = new SP.CamlQuery();
     query.set_viewXml('');
 var listFields = list.getItems(query);
 ctx.load(listFields);
ctx.executeQueryAsync(Function.createDelegate(this, function(sender,args){
debugger;var i=0;
   var listEnumerator = listFields.getEnumerator();
  while (listEnumerator.moveNext()) {
if(i++ == 0){
    var oField = listEnumerator.get_current();
    var attachments = oField.get_attachmentFiles();
    ctx.load(attachments);

ctx.executeQueryAsync(Function.createDelegate(this, function(sender, args){
debugger;
var enums = attachments.getEnumerator();
while (enums.moveNext()) {
var attacha = enums.get_current();
console.log(attacha.get_serverRelativeUrl());
}
 
console.log(attachments);
 

}), Function.createDelegate(this, function(){}));  

}
 }
}), Function.createDelegate(this, function(){}));
});

Read More

Monday, 23 September 2013

Get Multiple User's Multiple User Profile properties using CSOM

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
var ctx=new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle("Spotlight Employee");
var query = new SP.CamlQuery();
query.set_viewXml('');
this.listitems=list.getItems(query);
ctx.load(listitems);

ctx.executeQueryAsync(Function.createDelegate(this, function(){
   var listEnumerator = listitems.getEnumerator();
var ids=[], users=[], user, i=0;
while (listEnumerator.moveNext()) {
var oField = listEnumerator.get_current();
var id = oField.get_item("UserName").get_lookupId();
users[i] = ctx.get_web().getUserById(id);
ctx.load(users[i++]);
}//End while

ctx.executeQueryAsync(Function.createDelegate(this, function(){
for( i=0; i < users.length;i++){
console.log(users[i].get_loginName());
                                                                console.log(users[i].get_title());
}

}), Function.createDelegate(this, this.onFail));

}), Function.createDelegate(this, this.onFail));

});
Read More

Thursday, 5 September 2013

SharePoint 2013 Asset Library All Fields and Get Data

Please find Below Code to get all list fields with Static Name and thus to get different file properties


1. Code to get all list fields

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){
var ctx=new SP.ClientContext.get_current();
  var list = ctx.get_web().get_lists().getByTitle("TVC");
var listFields = list.get_fields();
ctx.load(listFields);
ctx.executeQueryAsync(Function.createDelegate(this, function(){

   var listEnumerator = listFields.getEnumerator();

while (listEnumerator.moveNext()) {
var oField = listEnumerator.get_current();
var fType = oField.get_fieldTypeKind();
if(fType === SP.FieldType.choice) {
  
}
oField.get_staticName() ? title=oField.get_staticName() :title='';
    console.log(title);
}
}), Function.createDelegate(this, function(){}));
});

2. Below are the List Fields

ContentTypeId
_ModerationComments
FileLeafRef
Modified_x0020_By
Created_x0020_By
File_x0020_Type
HTML_x0020_File_x0020_Type
_SourceUrl
_SharedFileIndex
PreviewOnForm
ThumbnailOnForm
_Author
FileType
ImageSize
Title
ImageWidth
ImageHeight
ImageCreateDate
_Comments
ThumbnailExists
PreviewExists
EncodedAbsThumbnailUrl
EncodedAbsWebImgUrl
NameOrTitle
Keywords
wic_System_Copyright
AlternateThumbnailUrl
MediaLengthInSeconds
PublishingStartDate
PublishingExpirationDate
VideoWidthInPixels
VideoHeightInPixels
VideoRenditionLabel
VideoRenditionBitRate
VideoSetDescription
VideoSetOwner
VideoSetThumbnailTimeIndex
VideoSetDefaultEncoding
VideoSetUserOverrideEncoding
VideoSetExternalLink
VideoSetEmbedCode
VideoSetShowDownloadLink
VideoSetShowEmbedLink
VideoSetRenditionsInfo
PeopleInMedia
NoCrawl
VideoCategory
ID
ContentType
Created
Author
Modified
Editor
_HasCopyDestinations
_CopySource
_ModerationStatus
FileRef
FileDirRef
Last_x0020_Modified
Created_x0020_Date
File_x0020_Size
FSObjType
SortBehavior
PermMask
CheckedOutUserId
IsCheckedoutToLocal
CheckoutUser
UniqueId
SyncClientId
ProgId
ScopeId
VirusStatus
CheckedOutTitle
_CheckinComment
LinkCheckedOutTitle
_EditMenuTableStart
_EditMenuTableStart2
_EditMenuTableEnd
LinkFilenameNoMenu
LinkFilename
LinkFilename2
DocIcon
ServerUrl
EncodedAbsUrl
BaseName
FileSizeDisplay
MetaInfo
_Level
_IsCurrentVersion
ItemChildCount
FolderChildCount
AppAuthor
AppEditor
SelectTitle
SelectFilename
Edit
owshiddenversion
_UIVersion
_UIVersionString
InstanceID
Order
GUID
WorkflowVersion
WorkflowInstanceID
ParentVersionString
ParentLeafName
DocConcurrencyNumber
Read More

Wednesday, 4 September 2013

SharePoint Get Only List Items Count using Client Object Model

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function(){

           var ctx=new SP.ClientContext.get_current();
           var list = ctx.get_web().get_lists().getByTitle("TVC");
           ctx.load(list);

ctx.executeQueryAsync(Function.createDelegate(this, function(){
          console.log("List ID= "+list.get_id().toString());
          console.log("List Item Count= "+list.get_itemCount());
}), Function.createDelegate(this, function(){}));
});
Read More

Tuesday, 4 December 2012

SharePoint Create Page Layouts for Custom Content Types


Hi All,

If you want to create custom content types and page layouts from your custom content types then refer to the links below-

http://www.dotnetcurry.com/ShowArticle.aspx?ID=620
http://www.dotnetcurry.com/ShowArticle.aspx?ID=638

Thanks Sumit for this wonderful post.

Thanks.
Read More

Monday, 3 December 2012

Pass Web Part Property Value to User Control


Introduction:
In this article I will describe that how to pass web part properties into user control.
To do so I will take base of my below article where I explained that how to create user control, load it using webpart and deploy using feature.
http://sharepoint.infoyen.com/2012/04/11/create-and-deploy-user-control-in-sharepoint-using-feature/

Detail Steps:-
Once you read my article http://sharepoint.infoyen.com/2012/04/11/create-and-deploy-user-control-in-sharepoint-using-feature/ then you will understand that how to create, deploy user control using feature.
To pass webpart property into webpart follow below steps:-
1. Create web part property for example “EmpoyeeName” in webpart class “GenericUserControlPicker” , as mentioned below:-
private string employeeName = string.Empty;
 
[WebBrowsable(), Personalizable(),
WebDisplayName("Employee Name"),
WebDescription("Employee Name")]
public string EmployeeName
{
 get
 {
  return employeeName;
 }
 set
 {
  employeeName = value;
 }
}

2. Create regular c# .net property in user control as “EmpoyeeName” in user control class “HelloWorld”, as mentioned below:-
public string EmployeeName {get;set;}

3. Pass webpart property “EmployeName” value to user control as mentioned below code:
// this is line number 51 in "GenericUserControlPicker" class
userControl = (UserControl)LoadControl(UserControlPath);
// Check usercontrol is loaded or not.
// Also check if Employee Name has been entered or not
if(userControl!= null && !String.IsNullEmpty(EmployeeName))
{
 userControl.EmployeeName = EmployeeName;
}

4. Display webpart property “EmployeName” in user control, as mentioned below code:
protected void Page_Load(object sender, EventArgs e)
{
 lblTest.Text = EmployeeName;
}

Hope It Helps...
Thanks
Nikhil S.


Read More

Sharepoint Object Model User Profiles



Introduction
In this article I am going to explain you that How to use User Profiles and profile properties in Sharepoint Object model.
In SharePoint 2007, a userid is uniquely identified by his/her username. The username is Tied to the membershipprovider that the site is configured to authenticate against. A user can also have other information like phone number, email etc.
Even if business require then they can add custom property like Origin, Race etc.
Detail:-
First, your code must have references to the Microsoft.SharePoint, Microsoft.Office.Server, and System.Web Assemblies. With those references available, you can use the SPSite class and the UserProfileManager class as entry points into the user profile subsystem within MOSS.
As per my opinion; there are few below important points while using user profiles programmatically:
1. Retrieving User Profiles
2. Read Profile Property
3. Modify User Profile
4. Create a User Profile
5. Create a User Profile property
The Code:-
Main class I am going to explain in only 1st point. In rest other point I will only highlight code block which is related to respective point.
1. Retrieving User Profiles
We can get user profile object by using GetUserProfile method of UserProfileManager.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
 
namespace UserProfilesConsoleApp
{
 class Program
 {
   static void Main(string[] args)
   {
     using ( SPSite site = new SPSite("site url"))
     {
 ServerContext context = ServerContext.GetContext(site);
 UserProfileManager profileManager = new UserProfileManager(context);
 // you can also get current user from web object.
        // syntex: SPWeb.CurrentUser
 UserProfile profile = profileManager.GetUserProfile(@"domainuser");
 Console.WriteLine("Profile {0}", profile.MultiloginAccounts[0]);
        // you got user profile object. now you can use any property of it.
        // like profile.ID, profile.PersonalSite.RootWeb.Titl e, profile.PersonalSite.Url etc..
 
     }
   }
 }
}


2. Read Profile Property
We can read property using UserProfileManager.Properties
foreach (Property prop in profileManager.Properties)
{
  Console.WriteLine("t{0} : {1}",
  prop.DisplayName, profile[prop.Name].Value);
}

3. Modify User Profile
profile["Origin"] = "India";
//Make sure that you call the Commit method 
//when you are finished making changes to the profile
profile.Commit();

4. Create a User Profile
UserProfileManager profileManager = new
UserProfileManager(context);
string acId = @"domainavinash";
if (!profileManager.UserExists(acId))
{
  UserProfile profile = profileManager.CreateUserProfile(acId);
  if (profile == null)
 Console.WriteLine("ould not create user profile, an error occurred.");
  else
 Console.WriteLine("User profile has been created.");
}
else
 Console.WriteLine("User profile for this account " + acId + " already exists.");

5. Create user Profile Property
PropertyCollection pc = profileManager.Properties;
Property p = pc.Create(false);
p.Name = "TestProperty";
p.DisplayName = "Test Property";
p.Type = "String";
p.Length = 50;
p.PrivacyPolicy = PrivacyPolicy.OptIn;
p.DefaultPrivacy = Privacy.Organization;
pc.Add(p);

Reference:-

Thanks
Nikhil S.

Read More

Add User To SharePoint Group Programmatically


Introduction:

Below I found this article will describe that how to add Share point user to share point group programmatically.
This will use below terms:-
1. AllowUnsafeUpdates: Before we update we will set AllowUnsafeUpdates to true.
2. SPGroup: We will create object sharepoint group in which we need to user.
3. AddUser: SPGroup.AddUser will add user into group.

The Code:-

This going to detail about a generic function in which you pass group name and user name, then function will add user into group. For deployment, WSP creation and feature basic; please read below articles:-
http://sharepoint.infoyen.com/2012/04/01/create-webpart-in-sharepoint step by step using WSP/
http://sharepoint.infoyen.com/2012/04/22/feature-receiver-in-sharepoint/
See below detailed code:-
// groupName will be string for e.g. "Site Owner"
// userLoginAccName will be "DomainName\UserName" for e.g. "Infoyen\\avinash"
public void AddUserToGroup(string groupName, string userLoginAccName)
{
 // you can also use SPContext to get SPWeb object
 Uri sitePath = new Uri("http://localhost/");
 
    using (SPSite site = new SPSite(sitePath.ToString()))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser requiredUser = web.EnsureUser[userLoginAccName];
 
                if (requiredUser != null)
                {
                    SPGroup requiredGroup = web.Groups[groupName];
                    if (requiredGroup != null)
                    requiredGroup.AddUser(requiredUser);
                }
            }
            catch (Exception ex){//Handle exception
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}


Thanks
Nikhil S.


Read More

AllowUnsafeUpdates VS RunWithElevatedPrivileges

AllowUnsafeUpdates: If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.
For detail click here AllowUnsafeUpdates

RunWithElevatedPrivileges : There are certain object model calls model that require site-administration privileges. To bypass access-denied error, we use RunWithElevatedPrivileges property when request is initiated by a nonprivileged user. We can successfully make calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
For detail click here RunWithElevatedPrivileges

Thanks!
Nikhil S.
Read More

RunWithElevatedPrivileges in SharePoint

In this article I am going to explain you that How to use RunWithElevatedPrivileges in sharepoint object model.
RunWithElevatedPrivileges
Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.The next example shows the syntax that is required to define an anonymous method in the call to RunWithElevatedPrivileges.




SPSecurity.RunWithElevatedPrivileges(delegate()

{

    // implementation details omitted

});




Detail:-
The RunWithElevatedPrivileges method accepts a delegate parameter that adds a reference to a method that containsthe code that is to be executed with elevated privileges.
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
      string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
      string Visits = ElevatedsiteColl.Usage.Visits.ToString();
      string RootAuditEntries =
          ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
    }
  }
});

Must read it:
In RunWithElevatedPrivileges you must then create an instance of the SPSite class and the SPWeb class. You cannot use the objects available through the Microsoft.SharePoint.SPContext.Current property. That is because those objects were created in the security context of the current user.

Thanks!
Nikhil S.


Read More

SPWeb.AllowUnsafeUpdates



SPWeb.AllowUnsafeUpdates : It Gets or sets a Boolean value that specifies whether to allow updates to the database as a result of a GET request or without requiring a security validation. Whenever your code modifies SharePoint data in some way or Whenever we need to update SharePoint objects like SPWeb, SPList, SPListItem, etc , without requiring a security validation, we need to set SPWeb.AllowUnsafeUpdates = true. 


Following is the code snippet for the same.



SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
 
// Perform the list/list item/web update 
web.allowUnsafeUpdates = false;

Detail:- The Microsoft idea behind introducing the AllowUnsafeUpdates property is to protect YOU from cross-site scripting attacks. The way this works is that if your application is running in an HTTPContext (i.e. it’s a web part for instance) and the request is a GET request then SharePoint will refuse to do any changes unless the value of AllowUnsafeUpdates is set to true and by default it will be false for GET requests. If you try to do any updates to lists, webs or any SharePoint objects that require an SPSite to be created first, and if you don’t set AllowUnsafeUpdates to true you will get this exception: 

System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. —> 


System.Runtime.InteropServices.COMException (0x8102006D): The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. 


Usually when you create your own SPSite or SPWeb objects, i.e. when you are not getting them from the SPContext (such as SPContext.Web), and when you try to update anything such as web or list properties, list items metadata etc, you may get the exception listed above. This is a clear indication thatAllowUnsafeUpdates of the SPWeb is false and this is preventing you from doing the update. This problem is resolved easily by setting theAllowUnsafeUpdates of the parent web object to true. 


Few examples:- Scenario 1 (using SPWeb.EnsureUser):- 

EnsureUser looks for the specified user login inside SPWeb.SiteUsers collection, and if the login isn’t found, turns toActiveDirectory for the purpose of retrieving the user information from there. If such information is found, it will be added to SPWeb.SiteUsers and for the next time it will be returned directly fromSPWeb.SiteUsers. That means we are modifying SPWeb by adding user. Therefore we need to use AllowUnsafeUpdates property to avoid exception.


public static SPUser VerifyUser(SPWeb web, string loginName)
{
    SPUser myUser = null;
try
{
web.AllowUnsafeUpdates = true;
myUser = web.EnsureUser(loginName);
}
catch (Exception ex) {// write to log}
finally
{
web.AllowUnsafeUpdates = oldAllowUnsafeUpdate;
}
    return myUser;
}



Scenario 2 (using BreakRoleInheritance):- 
When we use Methods BreakInheritance, ResetRoleInheritance and BreakRoleInheritance, it reset AllowUnsafeUpdates to false. 

using (SPSite spSite = new SPSite("url"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {
        bool oldAllowUnsafeUpdates = spWeb.AllowUnsafeUpdates;
        try
        {
SPList spList = spWeb.Lists["some list"];
SPListItem spLisItem = spList.GetItemById(someId);
// need to set since we are going to modify SPListItem
spWeb.AllowUnsafeUpdates = true; 
spLisItem.BreakRoleInheritance(false);
SPRoleDefinition reader = spWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
SPGroup someGrp = spWeb.Groups["some group"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(someGrp);
roleAssignment.RoleDefinitionBindings.Add(reader);
// need to set since BreakRoleInheritance method reset AllowUnsafeUpdates to false
spWeb.AllowUnsafeUpdates = true;
spListItem.RoleAssignments.Add(roleAssignment);
        }
        catch (Exception ex)
        {
            // logging
        }
        spWeb.AllowUnsafeUpdates = oldAllowUnsafeUpdates;
spWeb.Update();
    }
}



Scenario 3 (using SPListItem.Update):-

using (SPSite spSite = new SPSite("url"))
{
    using (SPWeb web = spSite.OpenWeb())
    {
        try
        {
SPList list = web.Lists["SomeList"];
SPListItem item = list.GetItemById(12);
item["Title"] = "Some Changes";
web.AllowUnsafeUpdates = true;
item.Update();
web.AllowUnsafeUpdates = false;
        }
        catch (Exception ex)
        {
            // handle exception
        }
     }
}

References:- 





Thanks! Nikhil S.
Read More

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates