Sharepoint development using PowerShell - asp.net

I'm trying to create sharepoint webparts using powershell. But each time I loads (Context.Load()) something, I'm getting errors.
Here is my code.
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client").location))
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.runtime").location))
$tenantAdmin = "######ajoncloud.onmicrosoft.com"
$tenantAdminPassword = "#########"
$secureAdminPassword = $(convertto-securestring $tenantAdminPassword -asplaintext -force)
$siteURL = "https://ajoncloud.sharepoint.com/LND"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin,$secureAdminPassword)
$ctx.Credentials = $credentials
This part is working completely fine. But if I try the following statements, I get errors.
$web = $ctx.Web
$ctx.Load($web)
$ctx.ExecuteQuery()
This is the error I'm getting.
Exception calling "ExecuteQuery" with "0" argument(s): "The remote server returned an error: (403) Forbidden."

Your code is working fine when I try it myself. Maybe try the below piece of code and try to obtain a specific piece inside your SharePoint. Specify a certain list and try to obtain the fieldvalues. At first I got an error when running your code, but when I tried a different user and specified the below list it started working for both users.
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client").location))
[Reflection.Assembly]::LoadFile(([System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.runtime").location))
$tenantAdmin = "your admin account"
$tenantAdminPassword = "your admin password"
$secureAdminPassword = $(ConvertTo-SecureString $tenantAdminPassword -AsPlainText -Force)
$siteURL = "your site/subsite"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$ctx.credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($tenantAdmin,$secureAdminPassword)
$listTitle = "The name of your list"
$list = $ctx.Web.Lists.GetByTitle($listTitle)
$fields = $list.Fields
$qry = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(10000,'ID','Created','Modified','Title')
$items = $list.GetItems($qry)
$ctx.Load($fields)
$ctx.Load($items)
$ctx.ExecuteQuery()
foreach($item in $items){
$item.FieldValues.Title
}

Related

How to clear all events in Google Calendar using API V3 PHP

I spent a long time to work out how to do the following using Google Calendar using API V3 in PHP
insert a new event
read all existing events
delete each existing event
However I would still like to know how to clear an entire Google Calendar to make my code faster, as the read & delete method is a little slow.
I've been trying to work out how to use the supplied Google function "clear" for this, and the documentation supplied by Google simply shows that I should be able to use the following command to achieve this:
$service->calendars->clear('primary');
Also within the Google Code there is a comment relating to the "calendars" collection of methods (where the clear function exists):
Typical usage is:
<code>
$calendarService = new Google_Service_Calendar(...);
$calendars = $calendarService->calendars;
</code>
So I've put this together with the preceding authentication code. I am sure the authentication is working OK as I've used that elsewhere, but the clear code is obviously wrong as I get error message:
Notice: Undefined variable: service in C:\wamp\www\googleapi\clear\index.php on line 39
I've tried using 'primary' as well as the main owner, and I've tried making the calendar private and public but to no avail.
Anyone who has got the clear method to work, please point me in the right direction.
This is the code I'm running so far:
<?php
session_start();
require_once '../google-api-php-client-master/autoload.php';
//Google credentials
$client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
$service_account_name = 'xxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com';
$key_file_location = '../google-api-php-client-master/API Project-xxxxxxx.p12';
if (!strlen($service_account_name) || !strlen($key_file_location))
echo missingServiceAccountDetailsWarning();
$client = new Google_Client();
$client->setApplicationName("Whatever the name of your app is");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/calendar'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
try {
$client->getAuth()->refreshTokenWithAssertion($cred);
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
$_SESSION['service_token'] = $client->getAccessToken();
/* ------------------------- We are now properly authenticated ------------------- */
$calendarService = new Google_Service_Calendar($client);
$calendars = $calendarService->calendars;
$service->calendars->clear('primary');
?>
Just use your service calendar instance.
$service = new Google_Service_Calendar($client);
$calendar = $service->calendars->clear('primary');

Convert .Net example to PowerShell

I have a project to write a script that connects to a Web Service and retrieve information of selected records. Unfortunately there is no PowerShell support from the vendor. Their documents only provides .Net examples. The web service that I am trying to retrieve information is for HP Trim v7. Maybe some of you are familiar.
Here is the .Net example from vendor
Example – Title Word search
// Construct a request object
TrimRequest request = new TrimRequest();
// Construct a RecordStringSearchClause, with type
// TitleWord, and argument "reef"
RecordStringSearchClause clause = new RecordStringSearchClause();
clause.Type = RecordStringSearchClauseType.TitleWord;
clause.Arg = "reef";
// Construct a record search, and put our search clause in it
RecordSearch search = new RecordSearch();
search.Items = new RecordClause[] { clause };
// Put our search operation into our TrimRequest
request.Items = new Operation[] { search };
// Send it off. Whatever comes back will be in response
Engine engine = new Engine();
engine.Credentials = new System.Net.NetworkCredential(username, password);
TrimResponse response = engine.Execute(request);
And here is my PowerShell code
$url = "http://localhost/trimws/trim.asmx"
$Engine = New-WebServiceProxy -Uri $url -Class "proxy" -Namespace "Connection" -UseDefaultCredential
$RecordStringSearchClause = New-Object Connection.RecordStringSearchClause
$ClauseType = New-Object Connection.RecordStringSearchClauseType
$ClauseType.value__ = 4 ##Record Number
$RecordStringSearchClause.Type = $ClauseType
$RecordStringSearchClause.Arg = "39299763"
$RecordSearch = New-Object Connection.RecordSearch
$RecordClause = New-Object Connection.RecordClause ## doesn't work
$RecordSearch.Items = New-Object Connection.RecordClause { $RecordStringSearchClause } ## doesn't work
$RecordSearch.Items = $RecordStringSearchClause
$TrimRequest = New-Object Connection.TrimRequest
$TrimRequest.Items = $RecordSearch
$Engine.Execute($TrimRequest) ## returns nothing
Could any body help me to convert above .Net code into PowerShell script? (if technically possible)

MSDeploy API - Deleting a remote file through code

I am looking to remotely fire a delete command using the MSDeploy API through c# code.
I want to achieve the following command:
msdeploy.exe -verb:delete -dest:contentPath="/folderName/filename.txt"
instead of through running an unmanaged external executable, I want to execute this using the MSDeploy .Net API.
Assuming you're trying to delete an absolute filepath (rather than a file in a website), you're looking for something like this:
DeploymentObject destObject = DeploymentManager.CreateObject(
DeploymentWellKnownProvider.FilePath, "/foldername/filename.txt");
DeploymentObject sourceObject = DeploymentManager.CreateObject("auto", "");
DeploymentBaseOptions baseOptions = new DeploymentBaseOptions();
DeploymentSyncOptions syncOptions = new DeploymentSyncOptions
{
DeleteDestination = true;
};
DeploymentChangeSummary results = sourceObject.SyncTo(
destObject, baseOptions, syncOptions);
// results.ObjectsDeleted == 1
I've found the answer thanks to Richard Szalay's leading and i've used the ContentPath provider as this is a common provider used by VS Publishing so the chances of having permissions is high:
var deployBaseOptions = new DeploymentBaseOptions
{
ComputerName = "https://mywebserver.com:8172/msdeploy.axd?sitename=yourIISWebsiteName",
UserName = "username",
Password = "password",
UseDelegation = true,
AuthenticationType = "Basic"
};
var syncOptions = new DeploymentSyncOptions
{
DeleteDestination = true
};
var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath,
"yourIISWebsiteName" + "/fileToDelete.txt",
destBaseOptions);
var results = deploymentObject.SyncTo(deployBaseOptions, syncOptions);
The weird thing is that results always shows 3 files deleted even when there is only one...?!

start workflow using alfresco java script api or through web script

I want to start a workflow programatically. So written a web script.
Execute Script :
function startWorkflow()
{
var workflow = actions.create("start-workflow");
workflow.parameters.workflowName = "activiti$alfGroupReview";
workflow.parameters["bpm:workflowDescription"] = "Please review ";
workflow.parameters["bpm:groupAssignee"] = people.getGroup( "GROUP_site_collaborators");;
var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7);
workflow.parameters["bpm:workflowDueDate"] = futureDate;
workflow.execute(document);
return ;
}
For the above script, I am getting error "document is not defined". I am referring https://forums.alfresco.com/en/viewtopic.php?f=34&t=42677 and http://livinginjava.blogspot.in/2008/10/starting-alfresco-workflow-using.html links.
So I update my script to :
function startWorkflow()
{
var nodeRef = "workspace://SpacesStore/25285e6c-2995-49fe-aa50-1270cefc806a";
var docNode = search.findNode(nodeRef);
var workflow = actions.create("start-workflow");
workflow.parameters.workflowName = "activiti$alfGroupReview";
workflow.parameters["bpm:workflowDescription"] = "Please review ";
workflow.parameters["bpm:groupAssignee"] = people.getGroup( "GROUP_aloha_collaborators");;
var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + 7);
workflow.parameters["bpm:workflowDueDate"] = futureDate;
workflow.execute(docNode);
return ;
}
Here, nodeRef : is ref of a document from document library.
Now new error is :
500 Description: An error inside the HTTP server which prevented it from fulfilling the request.
Message: 06270056 Wrapped Exception (with status template): 06270273 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/justransform/startWF.get.js': null
Exception: org.alfresco.scripts.ScriptException - 06270273 Failed to execute script 'classpath*:alfresco/templates/webscripts/org/justransform/startWF.get.js': null
org.alfresco.repo.jscript.RhinoScriptProcessor.execute(RhinoScriptProcessor.java:195)
thanks in advance.
Using Alfresco Workflow API.
Note: wfDocs holds the array of doc nodes:
// 2 days from now
var dueDate2d = new Date((new Date()).getTime() + 2*(24*60*60*1000));
// Start workflow
var wfdef = workflow.getDefinitionByName("activiti$alfGroupReview");
if (wfdef) {
var wfparams = new Array();
wfparams["bpm:workflowDescription"] = "Please review";
wfparams["bpm:groupAssignee"] = people.getGroup( "GROUP_site_collaborators");
wfparams['bpm:workflowDueDate'] = dueDate2d;
wfparams['bpm:workflowPriority'] = 1;
wfparams['wf:notifyMe'] = true;
var wfpackage = workflow.createPackage();
for each (var n in wfDocs)
wfpackage.addNode(n);
var wfpath = wfdef.startWorkflow(wfpackage, wfparams);
var tasks = wfpath.getTasks();
for each (task in tasks)
task.endTask(null);
}
This code runs fine if:
docNode is not null. You should add a check for this.
Your group exists. Probably worth adding a check for this.
The workflow exists with the ID specified. Use the workflow console to confirm this. For example, the ID your provided is not an
out-of-the-box workflow. If it is custom, maybe you haven't deployed
the workflow successfully or you have the ID incorrect.
Also, do not use a variable called "workflow". Alfresco already defines a root-scoped object called "workflow". Speaking of that, feel free to use the workflow JavaScript API to invoke your workflow instead of an action. Either should work, though.
I ran your code successfully using the JavaScript console and a workflow id of "activiti$activitiParallelGroupReview" (and after changing your workflow variable to workflowAct).

Calling ASP-Actions by WWW::Mechanize (PERL)

i need to parse through a list generated by an ASP action (LoadDialog) and i have no clue how to get it done. If I execute the following i simply get an empty HTML file.
#!/usr/bin/perl -w
#
#
use strict;
use WWW::Mechanize;
use HTTP::Cookies;
my $url = "http://MYURL/LOGIN";
my $appurl = "http://MYURL/SOME.asp";
#SOME.asp calls http://MYURL/SOME.asp?Action=LoadDialog" to get results
my $username = 'username';
my $password = 'password';
#login to site
my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech->get($url);
$mech->form_name('login');
$mech->field(UserName => $username);
$mech->field(Password => $password);
$mech->click();
# get results from LoadDialog (?!)
$mech->get($appurl);
my $app_content = $mech->content();
print "$app_content\n";
Firebug tells me that ?Action=LoadDialog is getting called by the mentioned URL, but Mechanize doesnt realize it (guessing).
Simply chaning $myappurl to http://MYURL/SOME.asp?Action=LoadDialog gives me an empty HTML file as well.
Is there any chance to get the ASP generated content? I cant use any other Perl modules which "run a browser", I need to find a solution usable in a shell.
Thanks in Advance,
Marley

Resources