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

SharePoint Web Services Error : An item with the same key has already been added

Hi There,


Recently i found that none of my SharePoint 2013 application services are working. Crashing and throwing unknown multiple kind of errors in event viewer. One of the famous error that i found was below with Event ID 3.

[code]WebHost failed to process a request. Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/47208365 Exception: System.ArgumentException: An item with the same key has already been added. at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result) at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) Process Name: w3wp Process ID: 12724 [/code]


While troubleshooting i noticed that none of SharePoint Web Services are browsing and crashing with below error. I knew that it isn't any SharePoint specific error so i tried to recall the changes i have done on server.

Server Error in '/925bc7e108ff47198283782382a09c0d' Application.


An item with the same key has already been added.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: An item with the same key has already been added.

Source Error: 
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 

[ArgumentException: An item with the same key has already been added.]
   System.Runtime.AsyncResult.End(IAsyncResult result) +622882
   System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +196075
   System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +166




Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.33440




Resolution:

I noticed that somehow during troubleshooting of some other bug i removed the HTTPS bindings from IIS for SharePoint Web Services on Port 32844 which is must even if its not being used by SharePoint. I ran the below Command Prompt command and boom. The services are back.


[code]appcmd set site /site.name:"SharePoint Web Services" /+bindings.[protocol='https',bindingInformation='*:32844:'][/code]





Hope it help someone.

Happy SharePointing...!

How to get custom user profile property from SharePoint User Profile Service using JavaScript AJAX client side script

Hi There,

SharePoint provides a wonderful facility of client side scripts to get data from SharePoint objects. You can get custom user profile property from SharePoint User Profile Service using JavaScript AJAX calls. Below is an example.

I have an AD property with name "Initials" that do not comes in SharePoint OOTB  User Profile Service and you have to bind it manually.

I have set its internal name also "Initials" in my User Profile Service while binding it. We'll call this property using the same name. Remember that, you can only call a User Profile Property from its internal name.


I have bonded it with "Initials" attribute of AD and set the Direction to Import. Click Add.



Now the custom property is appearing when i edit any user profile.


Below is my JavaScript code.

[code]//Display User profile properties function getMyUserProfile(success, error) { var siteUrl = _spPageContextInfo.siteAbsoluteUrl; //You can replace this with your site URL too. i.e http://anysite.com $.ajax({ url: siteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties", method: "GET", headers: { "Accept": "application/json; odata=verbose" }, success: function (data) { var json = $.parseJSON(JSON.stringify(data.d)); alert("Hello " + json.DisplayName + " Your Job Title Is : " + json.Title + " Profile Picture URL is :"+ json.PictureUrl + " MySite URL is :"+ json.PersonalUrl); for (var i = 0; i < data.d.UserProfileProperties.results.length; i++) { if (data.d.UserProfileProperties.results[i].Key == "Initials") { alert("Your Custom Property Initials is : " + data.d.UserProfileProperties.results[i].Value); } } }, error: error }); } // Usage getMyUserProfile(function (properties) {}, function (data) { console.log(JSON.stringify(data)); }); [/code]
Boom...! It worked for me.

You can check some suggested codes here too which worked fine and provide another way to use the same code. I am also posting that samples below.

Sample 1:

[code]SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');

    var userProfileProperties;

    function getUserProperties() {
    var clientContext = new SP.ClientContext.get_current();
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    userProfileProperties = peopleManager.getMyProperties();
    clientContext.load(userProfileProperties);
    clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
    }
    function onRequestSuccess() {
    var Bild = userProfileProperties.get_userProfileProperties()['PictureURL']
    document.getElementById("div").innerHTML = userProfileProperties.get_userProfileProperties()['WorkEmail'];
    document.getElementById("div1").innerHTML = userProfileProperties.get_userProfileProperties()['PreferredName'];
    document.getElementById("div2").innerHTML = userProfileProperties.get_userProfileProperties()['WorkPhone'];
    $("#bild").attr('src', Bild);
    }

    function onRequestFail(sender, args) { alert( args.get_message());}[/code]

Sample 2:

[code]<script type="text/javascript">


    var workEmail = "";
    var EmployeeID = "";
    var Division = "";
    var userDisplayName = "";
    var AccountName = "";

    $.ajax({

        url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
        headers: { Accept: "application/json;odata=verbose" },
        success: function (data) {
            try {
                //Get properties from user profile Json response
                userDisplayName = data.d.DisplayName;
                AccountName = data.d.AccountName;
                var properties = data.d.UserProfileProperties.results;
                for (var i = 0; i < properties.length; i++) {

                    if (property.Key == "WorkEmail") {
                        workEmail = property.Value;
                    }

                    if (property.Key == "EmployeeID") {
                        EmployeeID = property.Value;
                    }
                    if (property.Key == "Division") {
                        Division = property.Value;
                    }

                }
                $('#AccountName').text(AccountName);
                $('#userDisplayName').text(userDisplayName);
                $('#EmployeeID').text(EmployeeID);
                $('#workEmail').text(workEmail);
                $('#Division').text(Division);


            } catch (err2) {
                //alert(JSON.stringify(err2));
            }
        },
        error: function (jQxhr, errorCode, errorThrown) {
            alert(errorThrown);
        }
    });

</script>

<br />
<h2>
<strong>Employee Details</strong></h2>
<br />
AccountName   <span id="AccountName"></span>
DisplayName   <span id="userDisplayName"></span>
EmployeeID    <span id="EmployeeID"></span>
Email Address <span id="workEmail"></span>
Division      <span id="Division"></span></div>[/code]

Traverse all users permissions on SharePoint 2010,2013 Site Collection PowerShell

Hi There,

I have found a very useful PowerShell script to traverse all users permissions on SharePoint 2010,2013 Site Collection using PowerShell. Thanks to Johan Mayer for updating the PowerShell code and making it more useful.

This PowerShell code will traverse or extract all users having permissions through any of SharePoint group and any level of permission. For example, if a User has permissions using three groups Readers, Contributors and Owners, it will show all groups one by one and describe the user permissions level in each group. Sample screenshot below.



PowerShell Script:

You can copy and paste this PowerShell script in a simple notepad file and save as .ps1 file. Now run SharePoint Management Shell and point to the file where you have just saved.

This script will traverse users permissions inside the lists/libraries too. You can filter the data once exported in CSV.

[code]function Get-SPUserEffectivePermissions( [object[]]$users, [Microsoft.SharePoint.SPSecurableObject]$InputObject) { begin { } process { $so = $InputObject if ($so -eq $null) { $so = $_ } if ($so -isnot [Microsoft.SharePoint.SPSecurableObject]) { throw "A valid SPWeb, SPList, or SPListItem must be provided." } foreach ($user in $users) { # Set the users login name $loginName = $user if ($user -is [Microsoft.SharePoint.SPUser] -or $user -is [PSCustomObject]) { $loginName = $user.LoginName } if ($loginName -eq $null) { throw "The provided user is null or empty. Specify a valid SPUser object or login name." } # Get the users permission details. $permInfo = $so.GetUserEffectivePermissionInfo($loginName) # Determine the URL to the securable object being evaluated $resource = $null if ($so -is [Microsoft.SharePoint.SPWeb]) { $resource = $so.Url } elseif ($so -is [Microsoft.SharePoint.SPList]) { $resource = $so.ParentWeb.Site.MakeFullUrl($so.RootFolder.ServerRelativeUrl) } elseif ($so -is [Microsoft.SharePoint.SPListItem]) { $resource = $so.ParentList.ParentWeb.Site.MakeFullUrl($so.Url) } # Get the role assignments and iterate through them $roleAssignments = $permInfo.RoleAssignments if ($roleAssignments.Count -gt 0) { foreach ($roleAssignment in $roleAssignments) { $member = $roleAssignment.Member # Build a string array of all the permission level names $permName = @() foreach ($definition in $roleAssignment.RoleDefinitionBindings) { $permName += $definition.Name } # Determine how the users permissions were assigned $assignment = "Direct Assignment" if ($member -is [Microsoft.SharePoint.SPGroup]) { $assignment = $member.Name } else { if ($member.IsDomainGroup -and ($member.LoginName -ne $loginName)) { $assignment = $member.LoginName } } # Create a hash table with all the data $hash = @{ Resource = $resource "Resource Type" = $so.GetType().Name User = $loginName Permission = $permName -join ", " "Granted By" = $assignment } # Convert the hash to an object and output to the pipeline New-Object PSObject -Property $hash } } } } end {} } $site = $gc | Get-SPSite http://localhost:2020 $groups = $site.RootWeb.sitegroups foreach ($grp in $groups) { foreach ($user in $grp.users) { $user = $user.LoginName $webPermissions = $site | Get-SPWeb –Limit All | Get-SPUserEffectivePermissions $user $listPermissions = $site | Get-SPWeb –Limit All | %{$_.Lists | Get-SPUserEffectivePermissions $user} ($webPermissions + $listPermissions) | ConvertTo-Csv -NoTypeInformation | Add-Content -Path c:\perms.csv } Add-Content -Path c:\perms.csv -Value $justData -Encoding UTF8 } $site.Dispose() $gc | Stop-SPAssignment[/code]

You can also download the script from here.

Enjoy...!

SharePoint 2013 Blog Post Error : TypeError: Unable to get property 'id' of undefined or null reference

Hi There,

Its a brand new installation with no customization on SharePoint site. I created a blog type subsite called "News" in SharePoint and faced the below error. This error comes up when i created a blog post in SharePoint from User1 account and then open the same post with User2 account which had read only permissions on the site. 



TypeError: Unable to get property 'id' of undefined or null reference
OR
TypeError: Unable to get property 'trim' of undefined or null reference

My current version of SharePoint was RTM 15.0.4420.1017. I installed the SharePoint Server SP1 (15.0.4569.1000) and the error "TypeError: Unable to get property 'id' of undefined or null reference" went away. Mean while i tested the same thing on another RTM version of SharePoint where it worked fine without any issue and installation of SP1. Hope it will help someone...!

Happy SharePointing...!

How to use CAML query with SharePoint 2013 List

Hi There,

So its a very basic question that how would you use a CAML query to fetch items from a SharePoint list? Its very simple to use and very fast as compared to other list query options. Below is the stuff to understand.

I have a list that have Posts of my blog as its a blog site. I have to query below few columns using their internal names. 


To find internal name of the columns, you can use a tool "SP CAML Query Helper Online"  or try with any other method. This tool is very helpful in building CAML query. In below screenshot i am using internal name of "# Comments" which is  "NumComments".


The Code:
                  I am getting most recent three items from the list based on the created date and order by Created date descending. 

The columns you wan to select from the list should be in ViewFields.


private SPListItemCollection GetListItems(SPList oList)
{
string sQuery = @"<OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy>";
string sViewFields = @"<FieldRef Name=""ID"" /><FieldRef Name=""LinkTitleNoMenu"" /><FieldRef Name=""Author"" /><FieldRef Name=""LikesCount"" /><FieldRef Name=""NumComments"" />";
string sViewAttrs = @"Scope=""Recursive""";
uint iRowLimit = 3;

var oQuery = new SPQuery();
oQuery.Query = sQuery;
oQuery.ViewFields = sViewFields;
oQuery.ViewAttributes = sViewAttrs;
oQuery.RowLimit = iRowLimit;
oQuery.ViewFieldsOnly = true;

SPListItemCollection collListItems = oList.GetItems(oQuery);

return collListItems;

}


This pass this method your list object and it will return the desired data.

Hope this will help someone to get idea.

Happy SharePointing...!

SharePoint: The EXECUTE permission was denied on the object 'xp_sqlagent_notify

Hi There,

I was working with SharePoint SSRS and the reports were working fine. However when i click "View Report History" it gave me the below error.


Microsoft.ReportingServices.Diagnostics.Utilities.ReportServerStorageException: An error occurred within the report server database.  This may be due to a connection failure, timeout or low disk condition within the database. ---> System.Data.SqlClient.SqlException: The EXECUTE permission was denied on the object 'xp_sqlagent_notify', database 'mssqlsystemresource', schema 'sys'. 

  

I found an answer here but i was looking for some systematic way than running SQL Server queries. So i found a solution here which worked for me.

So the solution is:

1. Open SharePoint Central Administration > Application Management > Manage Service Applications
2. Click on your SQL Server Reporting Services Service Application
3. Click on “Provision Subscriptions and Alerts” link
4. Type a username and password for SQL Server which grants privilege to your SSRS service application pool. 
5. Save and try again

Boom....! It worked.

Happy SharePointing :)