Friday, August 5, 2016

Powershell Script to Get SharePoint SiteUsage information


Hi Readers,

There was a requirement to get the sites that were not used , so that we can archive them.
I found some blogs with getting last modified information using the database but the issue is it wasn's correct as all the sites had a modified date which is very recent. This may be due to search crawls.

I came up with some functions that will be useful, here the last modified date and time and the people with full control access will be listed. the purpose of this script will be informing the people with full permissions.

#Get the last Modified information of a site
function GetSiteModifiedInformation
{
    #First Argument will be the site collection url
 $siteUrl=$args[0]
    #Ouput file name or path
 $filename=$args[1]

    #Check if file url is provided
 if($siteUrl -eq $null -or $siteUrl -eq '')
 {
  Write-Host "Please provide a siteUrl" -ForegroundColor Red
  return;
 }
 
    
    Write-Host "Getting Site Information" -ForegroundColor Yellow
    #Get Site using url
    $web=Get-Spweb $siteUrl

    Write-Host "Site Name : "$web.Title
    Write-Host "Created : "$web.Created
    $maxDate=GetLastModifiedListTime $web
    
    #Iterate subsites and get info from subsites
    foreach($spsite in $web.Webs)
    {
        $val=GetLastModifiedListTime $spsite
        
        if($val -gt $maxDate)
        {
            $maxDate = $val
        }
    }

    #Get all users of the site
    $userString='';
    $users = $web.siteusers
    foreach ($user in $users) {
        #Filter users with full control
        if ($web.DoesUserHavePermissions($user,[Microsoft.SharePoint.SPBasePermissions]::FullMask)) {
            $userString= $userString+$user.Name+';'
        }
    }

    Write-Host "Last Modified "$maxDate
    Write-Host $userString
    $name=$web.Title;

    #Add site information to file name
    Add-Content $filename "$siteUrl,$name,$maxDate,$userString"
    $web.Dispose()
}

function GetLastModifiedListTime
{
    #A SPWeb Object is required here
    $site= $args[0]

    #create a date variable with minimum date value
    $date = [DateTime]::MinValue
 
 foreach($list in $web.Lists)
 {
        #Get the most recently updated sharepoint list
  if($date -lt $list.LastItemModifiedDate -and !$list.Hidden)
  {
   $date=$list.LastItemModifiedDate
  }

 }
    return $date
}

#Another helper function that can be used to input a text file
#with sites urls
function GetAllSiteInfo
{
    $siteList =$args[0]
    $output=$args[1]
    $sites= Get-Content $siteList
    foreach($site in $sites)
    {
        GetSiteModifiedInformation $site $output
    }
}


Happy Coding
Guruparan Giritharan

Monday, May 30, 2016

ID3242: The security token could not be authenticated or authorized.

Hello Readers,

We had to setup a new content source in our search and suddenly we got this error while going to the Content sources in Search Service Application.

I googled n didn't find much information so i went through the ULS logs and found these entries.

 An operation failed because the following certificate has validation errors:  Subject Name: CN=###############.com Issuer Name: CN=###############.com Thumbprint: 9238C86F4CF817870AFAB778E9E5E140D7ADE82F  Errors:   The root of the certificate chain is not a trusted root authority..

STS Call: Failed to issue new security token. Exception: System.IdentityModel.Tokens.SecurityTokenValidationException: ID4257: X.509 certificate 
'CN=###############.com' validation failed by the token handler.

An exception occurred when trying to issue security token: ID3242: The security token could not be authenticated or authorized..

the actual issue was that one of the certificates were not added to 'SPTrustedRootAuthority'

Fixing this is simple

$cert = Get-PfxCertificate C:\###############.pfx
New-SPTrustedRootAuthority -Name "###############" -Certificate $cert

If you have a certificate that requires a password
Use IE and go to 'Central Admin'/_admin/ManageTrust.aspx and upload the certifcate.

That's how i got the issue fixed.
Hope it helps :)

Happy Coding
Guruparan Giritharan

Saturday, January 9, 2016

Example on working with JSON and HttpURLConnection in Android

Hello Readers,

The new Android platforms use a class called HttpUrlConnection to work with external service calls,
This post is on a method which can send a JSON as body and receive a JSON as response you can use this method whenever you need to post a JSON to a rest location and get a json from a rest location.
This method will send the JSON string as the body of the request.

You'll have to pass the following
URL : the request url
JSON : the json to be sent can be NULL on get scenarios
Timeout : Connection timeout
Method : Http method POST / GET / PUT etc

public static String getJSON(String url, String json, int timeout, String method) {
    HttpURLConnection connection = null;
    try {

        URL u = new URL(url);
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod(method);
        
        //set the sending type and receiving type to json
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        connection.setAllowUserInteraction(false);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);

        if (json != null) {
            //set the content length of the body
            connection.setRequestProperty("Content-length", json.getBytes().length + "");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            //send the json as body of the request
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(json.getBytes("UTF-8"));
            outputStream.close();
        }

        //Connect to the server
        connection.connect();

        int status = connection.getResponseCode();
        Log.i("HTTP Client", "HTTP status code : " + status);
        switch (status) {
            case 200:
            case 201:
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                bufferedReader.close();
                Log.i("HTTP Client", "Received String : " + sb.toString());
                //return received string
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } catch (IOException ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } catch (Exception ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception ex) {
                Log.e("HTTP Client", "Error in http connection" + ex.toString());
            }
        }
    }
    return null;
}


Happy Coding
-Guru-