Sharepoint testing in Pester - unit-testing

I am currently working on some PowerShell script for SharePoint farm configuration (for example a script for SPWebapplication creation, User profile service application creation, MMS service application creation or search service application creation). My requirement is to test this module using Pester framework. I have very basic understanding about Pester. A sample code for web app creation is below:
$webApplicationName = "A Name"
$hostingMainURL = "http://.....local"
$ContentDatabase = "Datacom_WebApp_ContentDB"
$applicationPoolDisplayName = "TestApppool"
$applicationPoolIdentity = (Get-SPManagedAccount "DEV\Apppool accountName")
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$ap = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication
$applicationPoolDisplayName -ApplicationPoolAccount $applicationPoolIdentity -
Port 80 -AuthenticationProvider $ap -DatabaseName $ContentDatabase
Write-Host "Set content database limits settings for $ContentDatabase..." -Foreground "green"
Set-SPContentDatabase -Identity $ContentDatabase -MaxSiteCount 1 -WarningSiteCount 0
New-SPSite -Url $hostingMainURL -owneralias $username -Name $webApplicationName -Description "Hosting root site collection"
I need a starting point from here. I need some advise on how I can create some test cases on Mocking for example:
Mock New-SPWebapplication
Mock Get-SPManagedAccount
Mock New-SPSite

inModuleScope 'ModuleCallingSpWeb' {
function Get-SPWebApplication {}
Mock -ModuleName ModuleCallingSpWeb Get-SPWebApplication
}

Related

Cannot test Swift_Mailer because service already initialized or test. alias ignored

I already found few informations like
Symfony2 access private services in tests
or
Replace Symfony service in tests for php 7.2
But I dont know why its not working.
I have an autowiring service.
class MailService {
public function __construct(\Swift_Mailer $mailer, Environment $twig)
{
$this->mailer = $mailer;
$this->twig = $twig;
}
}
config/services_test.yaml
services:
# default configuration for services in *this* file
_defaults:
#autowire: true # Automatically injects dependencies in your services.
#autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: true
test.swiftmailer.transport: '#Swift_Mailer'
And when I try to replace.
$mailer = $this->getMockBuilder(\Swift_Mailer::class)
->disableOriginalConstructor()
->getMock();
$mailer->expects($this->once())->method('send')->willReturn(1);
self::$container->set('swiftmailer.mailer.default', $mailer);
self::$container->set('swiftmailer.default', $mailer);
self::$container->set('swiftmailer.mailers', [$mailer]);
But I dont know why its not working.
Any ideas? :)

Moodle Error - Web Services Client - No access rights in module context

I have got the following setup in Moodle:
I have enabled Web Services
I have enabled the REST protocol
I have added a service called grades and enabled it
I have added the function mod_assign_get_grades to the service
I have assigned the webservice user as an authorized user for the service
I have also created and assigned a role to the user that will allow the user of the rest protocol
I have also created a token for the user and service
I have used the code below to make a request to the API:
/// SETUP - NEED TO BE CHANGED
$token = '068183c4c700bdcfe2b0bfe24a8043e2';
$domainname = 'http://localhost/Project/moodle';
$functionname = 'mod_assign_get_grades';
// REST RETURNED VALUES FORMAT
$restformat = 'xml'; //Also possible in Moodle 2.2 and later: 'json'
//Setting it to 'json' will fail all calls on earlier Moodle version
/// PARAMETERS - NEED TO BE CHANGED IF YOU CALL A DIFFERENT FUNCTION
$params = array('assignmentids' => array(1));
/// REST CALL
header('Content-Type: text/plain');
$serverurl = $domainname . '/webservice/rest/server.php'. '?wstoken=' . $token . '&wsfunction='.$functionname;
require_once('./curl.php');
$curl = new curl;
//if rest format == 'xml', then we do not add the param for backward compatibility with Moodle < 2.2
$restformat = ($restformat == 'json')?'&moodlewsrestformat=' . $restformat:'';
$resp = $curl->post($serverurl . $restformat, $params);
print_r($resp);
Upon execution I get the following error:
No access rights in module context
As far as I can tell I have assigned the appropriate capabilities and permissions and don't know where I'm going wrong?
Looks like the web service user I created did not have the privileges to access student grades. Using the admin account that I created when I used moodle I am able to run the script and return a response.

Using PowerShell to send data from SQL Server to service via SOAP

I'm fairly new to PowerShell and brand new (as in, today) to web services and SOAP. A vendor gave us documentation on their web service API that allows the creation of user accounts. I'm trying to use PowerShell to pull our users from SQL Server and send the data to their service. We will need to add users on an ongoing basis.
Below is a pared-down version of what I came up with and it actually seems to work; the vendor told me to include a dry_run parameter while testing and I'm getting a dry_run_success from the response_type.
My question is: Is this even close to being the appropriate way to do it with PowerShell?
# Open ADO.NET Connection to database
$dbConn = New-Object Data.SqlClient.SqlConnection;
$dbConn.ConnectionString = "Data Source=mydbserver;User ID=someuserid;Password=mypassword;Initial Catalog=mydatabase";
$dbConn.Open();
$sql = "select * from mytable";
$dbSqlCmd = New-Object Data.SqlClient.SqlCommand $sql, $dbConn;
$dbRd = $dbSqlCmd.ExecuteReader();
# Create a Web Service Proxy
$proxy = New-WebServiceProxy -Uri https://somedomain.com/service/wsdl
$namespace = $proxy.GetType().NameSpace
$param = New-Object($namespace + ".somemethod")
# Loop through records from SQL and invoke the web service
While ($dbRd.Read())
{
$param.user_id = $dbRd.GetString(0)
$param.password = $dbRd.GetString(1)
$param.display_name = $dbRd.GetString(2)
$request = $proxy.TheMethod($param)
if ($request.response_type -eq 'error')
{
$request.error.extended_error_text
}
}
# Clean up
$dbRd.Close();
$dbSqlCmd.Dispose();
$dbConn.Close();
A couple things you could improve:
Don't use select * in your SQL queries. Always specify the fields you need, in the order you need. As written, if someone were to restructure the table such that the user ID wasn't the first column, you'd have a mess on your hands because you're accessing the fields by their ordinal number
You're apparently storing those passwords in plaintext in your database. Anyone with access to your database knows the credentials for every one of your users. This is a very bad thing. Resolving this could be a very big discussion.
Your code keeps the database connection open until the script completes. Given the scope here, it's probably not going to cause a major problem, but your database access strategy should be to get in, get your data, get out & disconnect as quickly as possible.
$sql = "select user_id, password, display_name from mytable";
$QueryCmd = $dbConn();
$QueryCmd.CommandText = $sql;
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$QueryCmd.Connection = $dbConn;
$SqlAdapter.SelectCommand = $QueryCmd;
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet)
$dbConn.Close();
$dbConn.Dispose();
$MyResults = $DataSet.Tables[0];
$MyResults | foreach-object {
$param.user_id = $_.user_id;
$param.password = $_.password;
$param.display_name = $_.display_name;
$request = $proxy.TheMethod($param);
if ($request.response_type -eq 'error')
{
$request.error.extended_error_text;
}
}

how to change host web url from sharepoint provider hosted app

I want to change url of host web from provider hosted app.
Basically, after completion of some business logic in my provider hosted app, I want to navigate to another page of SharePoint portal (for example the search-center page).
When I do "response.redirect" or "window.location.href" it is loading within the App iframe. I want to load the same page in main window.
Please suggest.
Updating with my logic
I have a generic method to get List home page url
public string ListHomePage(ClientContext clientContext, string listName)
{
Web spWeb = clientContext.Web;
clientContext.Load(spWeb, web => web.Url);
clientContext.ExecuteQuery();
return TokenHelper.GetAppContextTokenRequestUrl(spWeb.Url, HttpContext.Current.Server.UrlEncode(spWeb.Url + "/Lists/" + listName));
}
and I am calling following code in App page.
Response.Redirect(ListHomePage(clientContext1, "Test ListName"));
The same can be achieved using below code as the AppPart loads inside a iframe
string redirectUrl = ListHomePage(clientContext1, "Test ListName");
string script = "<script type='text/javascript'>window.parent.location.href = '" + redirectUrl + "'; </script>";
//Here I am using Telerik ScriptManager to execute script
RadScriptManager.RegisterStartupScript(this, this.GetType(), "Load", script, false);

Create a web service with CodeIgniter

im using CodeIgniter 1.7 framework to make my Website.
Another team do the mobile version for iPhone.
So the other team ask me to do a web service for authentification.
They tell that they will send me :
POST REQUEST
Input : login , password, push_token
if failure authentification -> Output HTTP : error code 0
if success -> Output XML :
<DATA>
<User id='id_user' title='..' first_name='' last_name='' email='' postal='' country_id=''/>
</DATA>
Basically i have this function for authentification:
function check_login($username="", $password="")
{
$username = $_POST['username'];
$password = $_POST['password'];
...
...
}
im looking into this post Codeigniter web services but i don't understand how its really work because im new in webservice.
I would consider using json as a sole output with one value being TRUE or FALSE depending on success. It's easier to handle, and all it requires is for your site to be in utf8.
If your check_login() returns TRUE, use that as the condition for success.
Example of reply:
/* Class etc. */
function do_login() {
$arr_json = array('success' => FALSE);
if ($this->login_library->check_login()) {
$arr_json['success'] = TRUE;
$arr_json['user_id'] = $this->login_library->user_id;
}
echo json_encode($arr_json);
}
login_library is just an example for your library which does the login. The reply they receive only needs to be decoded through json_decode(). And then simply check if the key success is TRUE or not.
If needed, have an extra key called error_message or similiar, and you can run all post-values through form_validation. Then you can also have $arr_json['error_message'] = trim(validation_errors('', "\n")); before the echo aswell.
You should definately look into Phil Sturgeons CodeIgniter Rest Server:
https://github.com/philsturgeon/codeigniter-restserver
There's a pretty good documentation. He also made a screencast about it: http://philsturgeon.co.uk/blog/2011/03/video-set-up-a-rest-api-with-codeigniter
Furthermore you could have a look at this article, where Adam Whitney explains his approach:
Building a RESTful Service using CodeIgniter
http://adamwhitney.net/blog/?p=707