<?xml version="1.0" encoding="utf-8" ?>
<Configuration version="1.0">
	<!-- 
		In order to enable Scripting Agent:
		- rename this file to ScriptingAgentConfig.xml
		- edit it appropriately
		- run the task: enable-CmdletExtensionAgent "Scripting Agent"

		In order to include into your scriptlet characters prohibited in XML, use escape sequences, e.g.
		"&lt;","&gt;","&amp;" for "less than", greater than" and "ampersand respectively.

	-->

	<Feature Name="MailboxOperatorNumberProvisioning" Cmdlets="new-mailbox">
		<ApiCall Name="ProvisionDefaultProperties">
			#parameter list:
			#param([ProvisioningHandler]$provisioningHandler, [IConfigurable]$readOnlyIConfigurable)

			if($provisioningHandler.UserSpecifiedParameters["OperatorNumber"] -ne $null)
			{
				#if user has specified -OperatorNumber parameter, return
				return $null;
			}
			
			if($readOnlyIConfigurable.OperatorNumber -ne $null) 
			{
				#if previous agent has provisioned OperatorNumber, return
				return $null;
			}

			$user = new-object -type Microsoft.Exchange.Data.Directory.Recipient.ADUser;
			$user.OperatorNumber = "911";
			new-object -type Microsoft.Exchange.Data.Directory.Management.Mailbox -argumentlist $user
		</ApiCall>
	</Feature>

  
  <!--
		The script enforces naming convention on distribution group. The rules to be applied are:
		1. Bypass enforcement if the user is administrator. Note: we simplify this logic by only check role name
		2. The name should follow the pattern as: "MY-DIY-<current user alias>-<free string that less than 32 characters>"
	-->

  <Feature Name="Name-Check" Cmdlets="new-distributiongroup,set-distributiongroup">
    <ApiCall Name="Validate">
      #parameter list:
      #param([ProvisioningHandler]$provisioningHandler, [IConfigurable]$readOnlyIConfigurable)

      <!-- Proceed only if -Name or -DisplayName is specified-->
      if (($provisioningHandler.UserSpecifiedParameters["Name"] -eq $null) -and ($provisioningHandler.UserSpecifiedParameters["DisplayName"] -eq $null)) {return $null}

      $userId = (Get-User | where {$_.Sid -eq $provisioningHandler.UserScope.UserId}).Identity

      <!-- Do nothing if the user has recipient management role assigned. We don't enforce naming convention on admin -->
      foreach ($userRole in (Get-ManagementRoleAssignment -RoleAssignee $userId))
      {
        if ((Get-ManagementRole $userRole.Role).RoleType -eq [Microsoft.Exchange.Data.Directory.SystemConfiguration.RoleType]::RecipientManagement) {return $null;}
      }

      <!-- Compose the naming convention validation regular expression: "MY-DIY-<user alias>-<free string that less than 32 characters>" -->
      $regExpression = "MY-DIY-" + (Get-Mailbox $userId).Alias + "-.{1,32}"

      <!-- Do regular expression validation -->
      if ([System.Text.RegularExpressions.Regex]::IsMatch($readOnlyIConfigurable.DisplayName, "^(" + $regExpression + ")$", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) {return $null;}

      New-Object -type Microsoft.Exchange.Data.ProvisioningValidationError -argumentlist ("The name must follow the pattern as: MY-DIY-[Your Alias]-[Free string less than 32 characters]", [Microsoft.Exchange.Data.ExchangeErrorCategory]::Client )

    </ApiCall>
  </Feature>


  <Feature Name="Auditing" Cmdlets="new-mailbox">
		<ApiCall Name="Validate">
			#parameter list:
			#param([ProvisioningHandler]$provisioningHandler, [IConfigurable]$readOnlyIConfigurable)

			$newObjectGuid = $readOnlyIConfigurable.Guid.ToString();
		</ApiCall>

		<ApiCall Name="OnComplete">
			#parameter list:
			#param([ProvisioningHandler]$provisioningHandler, [bool]$succeeded, [Exception]$exception)

			if($succeeded) 
			{
				WriteToSQL($newObjectGuid);
			}
		</ApiCall>
	</Feature>

	<Common>
	function WriteToSQL
	{
		param([string]$newObjectGuid)

		$connectionString = GetConnectionString;
		$queryString = "INSERT into RecipientAudit (DistributionGroupGuid) VALUES ('$newObjectGuid')";
		[reflection.assembly]::LoadWithPartialName("System.Data");
		$sqlConnection = new-object -type System.Data.SqlClient.SqlConnection -argumentlist $connectionString;
		$command = new-object -type System.Data.SqlClient.SqlCommand -argumentlist $queryString;
		$command.Connection = $sqlConnection;
		$command.Connection.Open();
		$command.ExecuteNonQuery();
		$sqlConnection.Close();
	}	

	function GetConnectionString
	{
		return "server=MYSQLSERVER;uid=sa;password=myPassword;database=CmdletExtensions";
	}
   
   
	</Common>
</Configuration>
