Monday, March 14, 2016

Bootstrap DateTime Picker with AngularJS Directive



Problem: I wanted to use the eonasdan’s Boostrap Datetime picker in my Share Point hosted App.

Solution: I have wrapped the eonasdan’s Bootstrap DateTime picker by creating a directive in my controller.



AngularMain.controller("MyController", function() {})
    .directive('bootdatepicker', ['$timeout', renderBootStrapDatePicker]);

function renderBootStrapDatePicker($timeout) {
    var format = "DD/MM/YYYY";
    return {
        restrict: 'EA',
        require: 'ngModel',
        link: function(scope, element, attributes, ngModelCtrl) {
            // Initialize the DateTime Picker with a format
            element.datetimepicker({
                format: format
                    /*,
                                                defaultDate: function () { return moment().format(format); }*/
            });

            // Get the DateTime Picker
            var datePicker = element.data('DateTimePicker');

            element.on('dp.change', function() {
                $timeout(function() {

                    var selectedDate = moment(datePicker.date()).format("DD/MM/YYYY");
                    ngModelCtrl.$setViewValue(selectedDate);
                });
            });

        }
    };

The following is 'RenderBootStrap' directive is bound to the view.
I hope, this may help someone.. :)

Thursday, January 21, 2016

SharePoint 2013: Users Permissions Detail Report in a SharePoint Farm


PowerShell Script Details

1. Gets all the lists with users with broken permissions.
2. Gets the all users added on the root with specific permission level.
3. Gets all the users added in a SharePoint Permission Group.





# Script Written By: Muhammad Salman Malik.
clear

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}


$permissionsArray = @()
$path = "C:\UsersPermissionsOverView.csv"
$siteCounter = 0;

function getUserName($oUser){
    $userName = "";

    if($oUser.UserLogin.StartsWith("c:"))
    {
        $userName = $oUser.DisplayName
    }
    else
    {
        $userName = $oUser.LoginName;
    }

    return $userName;
}

# get all the webapplication
$weApplications= get-spwebapplication 
$incrementProgress = 100/$weApplications.Count
$progressComplete = 0;

# iterate all the webapplication
foreach($webApp in $weApplications)
{ 
 foreach ($site in $webApp.sites)
 {
        $siteCounter++;
  write-host "Site Collection: " $site.Url -f Cyan  
        write-progress -Activity "Site Collection: " $site.Url -PercentComplete $progressComplete 
        $web = $site.RootWeb 
         
        if ($web.Lists.Count -gt 0)
        {                       
        foreach($list in $web.Lists)
        {
            # Find Lists in Site with Unique Permissions (Break inheritance)
            if($list.HasUniqueRoleAssignments -eq $True -and ($List.Hidden -eq $false))
            {  
                write-progress -Activity "List: " $list.Title -PercentComplete $progressComplete
                foreach ($user in $web.SiteUsers)
       {                                                                                                                                

                    foreach($listRoleAssignment in $list.RoleAssignments )
                    {
                        
                        if($listRoleAssignment.Member.userlogin -eq $user.UserLogin)  
                        {
                            #Write-Host "User: " $user.LoginName -f Yellow
                            $listUserPermissions=""
                            foreach ($RoleDefinition  in $ListRoleAssignment.RoleDefinitionBindings)
                            {
                                $listUserPermissions += $RoleDefinition.Name +";"
                            }                            

                            
                            $permissionObject = New-Object PSObject -Property @{
                            "Type" = "List User"
                            "Web Url" = $web.Url
                            "Web Name"= $web.Title
                            "List/DocumentLibrary" = $list.Title
                            "User" = getUserName -oUser $user
                            "Group" = "-"
                            "Permissions" = $listUserPermissions
                            }

                            $permissionsArray += $permissionObject
                        }
                    }
                }
                
             }
         }
        }

        # Find users added to the root with own Permission level (Without any Group)
        foreach ($user in $web.users)
  {
              $listUserPermissions=""
        foreach($listRoleAssignment in $web.RoleAssignments )
              {
                    #Is it a User Account?
                    if($listRoleAssignment.Member.userlogin -eq $user.UserLogin)  
                    {
                            $listUserPermissions=""
                            foreach ($RoleDefinition  in $ListRoleAssignment.RoleDefinitionBindings)
                            {
                                $listUserPermissions += $RoleDefinition.Name +";"
                            }
                    }
              }

      $permissionObject = New-Object PSObject -Property @{
                "Type" = "Root User"
                "Web Url" = $web.Url
                "Web Name"= $web.Title
                "List/DocumentLibrary" = "-"
                "User" = getUserName -oUser $user
                "Group" = "-"
                "Permissions" = $listUserPermissions
            } 
            $permissionsArray += $permissionObject       
     }

        # Find users added to a group
        foreach ($group in $web.Groups)
  {
              $groupUserPermissions=""
        foreach($groupRoleAssignment in $group.ParentWeb.RoleAssignments.GetAssignmentByPrincipal($group) )
              {                                      
                    foreach ($roleDefinition  in $groupRoleAssignment.RoleDefinitionBindings)
                    {
                        $groupUserPermissions += $roleDefinition.Name +";"
                    }                   
              }

      
    foreach ($user in $group.users)
    { 
       $permissionObject = New-Object PSObject -Property @{
                    "Type" = "Group User"
                    "Web Url" = $web.Url
                    "Web Name"= $web.Title
                    "List/DocumentLibrary" = "-"
                    "User" = getUserName -oUser $user
                    "Group" = $group.name
                    "Permissions" = $groupUserPermissions
                }
                $permissionsArray += $permissionObject                      
     
       }
     } 

    }
    $progressComplete = $progressComplete + $incrementProgress;
    write-progress -Activity "Processed Web Application: " $webApp.Url -PercentComplete $progressComplete
}

# Total Count of the site collection
Write-Host "Total Site Collections Count: " $siteCounter -f Yellow
$permissionsArray | Export-Csv -path $path -Delimiter ";"

Wednesday, December 23, 2015

SharePoint-hosted apps: Add Fields (Columns) to SharePoint List in Host Web using JSOM



var onQuerySucceeded = function(sender, args) {
    alert("List Field Updated");
}

var onQueryFailed = function (sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

var createFields = function (listName) {
    var clientContext = new SP.ClientContext.get_current();
    var factory = new SP.ProxyWebRequestExecutorFactory(appWebUrl);
    context.set_webRequestExecutorFactory(factory);
    var parentContext = new SP.AppContextSite(clientContext, hostWebUrl);

    // Get List
    var list = parentContext.get_web().get_lists().getByTitle(listName);
    var fieldCollection = list.get_fields();

    /*
    $(fieldsCollection).each(function (index, fieldValue) {
        fieldCollection.addFieldAsXml(fieldValue, true, SP.AddFieldOptions.defaultValue);
    });*/
    
    fieldCollection.addFieldAsXml("", true, SP.AddFieldOptions.defaultValue);
    fieldCollection.addFieldAsXml("", true, SP.AddFieldOptions.defaultValue);
    clientContext.load(fieldCollection);

    clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

// Add custom columns to the SharePoint List in Host Web
createFields("Projects");


SharePoint-hosted apps: Create a Custom List in Host Web using SharePoint REST API



var getQueryStringParameters = function(qsPara) {
    var paramArray = document.URL.split("?")[1].split("&");

    for (var i = 0; i < paramArray.length; i++) {
        var paraName = paramArray[i].split("=");
        if (paraName[0] === qsPara) {
            return paraName[1];
        }
    }
}

var getHostWebUrl = function () {
    var hostWebUrl = decodeURIComponent(getQueryStringParameters("SPHostUrl"));
    return hostWebUrl;
}


var createList = function (listName, baseTemplate, description) {
    var deferred = $.Deferred();
    var appWebUrl = _spPageContextInfo.webAbsoluteUrl;
    var hostWebUrl = getHostWebUrl();
    var executor = new SP.RequestExecutor(appWebUrl);
    var httpRequestUrl = appWebUrl + "/_api/SP.AppContextSite(@target)/web/Lists?@target='" + hostWebUrl + "'";

    executor.executeAsync({
        method: "POST",
        url: httpRequestUrl,
        body: "{ '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': " + baseTemplate + ", 'ContentTypesEnabled': true, 'Description': '" + description + "', 'Title': '" + listName + "' }",
        headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose"
        },
        success: function (data, status, jqXHR) {
            deferred.resolve();
        },
        error: function (data) {
            deferred.reject();
        }
    });


    return deferred.promise();
}

// Create a List named as 'Projects' in Host Web 
createList("Projects", "100", "This lists consist of projects used by SharePoint CV App")


Tuesday, December 1, 2015

SharePoint-hosted apps: Send Emails using SharePoint REST API


var sendEmails = function (emailCollection) {

    var oDeferred = $.Deferred(),
        email, iCounter = 0;
    // create an object for a http request
    var oHttpRequest = {
        url: "{0}/_api/SP.Utilities.Utility.SendEmail",
        type: "POST",
        contentType: "application/json; odata=verbose",
        headers: {
            "accept": "application/json; odata=verbose",
            "contentType": "application/json; odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        }
    }

    oHttpRequest.url = String.format(oHttpRequest.url, _spPageContextInfo.siteAbsoluteUrl);

    // Iterate the email collections and send emails
    for (email in emailCollection) {
        oHttpRequest.data = JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': emailCollection[email].From,
                'To': { 'results': [emailCollection[email].To] },
                'Subject': emailCollection[email].Subject,
                'Body': emailCollection[email].Body
            }
        });

        try {
            return $.ajax(oHttpRequest)
                .done(function () {
                    iCounter += 1;
                    if (iCounter == emailCollection.length) // Once all the emails are send then resolve the promise object.
                        oDeferred.resolve();
                }).fail(function (xhr, textStatus, errorThrown) {
                    alert(textStatus);
                });
        }
        catch (err) {
            err.message;
        }
    }
    return oDeferred.promise();
}


// Example Email Object
var emailCollection = [];
var oEmail = {};
oEmail["From"] = "salman.malik@de.sp.com";
oEmail["To"] = "salman.malik@de.sp.com";
oEmail["Subject"] = "Test Email From Sharepoint App";
oEmail["Body"] = "It is a test email generated from Sharepoint App";
emailCollection.push(oEmail);


sendEmails(emailCollection);

Thursday, November 19, 2015

SharePoint 2013: Install Solutions with PowerShell Remoting

Remoting Configurations

1. Check remoting service is running by executing get-service winrm
2. Enable the remoting by executing Enable-PSRemoting –force
3. Run the command on the server Enable-WSManCredSSP -Role Server
4. Run the following command on the client
set-item wsman:localhost\client\trustedhosts -value *

Enable-WSManCredSSP -Role Client –DelegateComputer *

 

$remoteMachine = "de-c-qs-ws.domain.de"
$userName = "domain\user";
$password = "Password";
$filePath = "C:\solutions\solution.wsp"


$pass =  $password | ConvertTo-SecureString -AsPlainText -Force>
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pass
$session = New-PSSession $remoteMachine -Authentication Credssp -Credential $credentials

Write-Host "Loaded PowerShell Assembly" -f Green;
Invoke-Command -Session $session -ScriptBlock { Add-PSSnapin Microsoft.SharePoint.PowerShell; }

Invoke-Command -Session $session -ScriptBlock { Install-SPSolution -Identity $args[0] -GACDeployment } -ArgumentList $newSolution.SolutionId                                              
$newSolution = Invoke-Command -Session $session -ScriptBlock { Add-SPSolution -LiteralPath $args[0] } -ArgumentList $filePath
Write-Host "Added Solution: " $filePath -f Green;#>
                      
Remove-PSSession -Session $session
#Write-Host "Installed Solution: " $filePath -f Green;

Tuesday, September 22, 2015

SharePoint 2013: Find and Replace string in Calculated columns
// Replace '.' with '-'
=REPLACE([IP Adresse],FIND(".",[IP Adresse]),1,"-")

// Replace all the '.' to '-'. This means '192.168.191.51' becomes '192-168-191-51'

=REPLACE(REPLACE(REPLACE([IP Adresse],FIND(".",[IP Adresse]),1,"-"),FIND(".",REPLACE([IP Adresse],FIND(".",[IP Adresse]),1,"-")),1,"-"),FIND(".",REPLACE(REPLACE([IP Adresse],FIND(".",[IP Adresse]),1,"-"),FIND(".",REPLACE([IP Adresse],FIND(".",[IP Adresse]),1,"-")),1,"-")),1,"-")