create customer payment profile in authorize.net - authorize.net

I am facing a very strange behavior in using the API to create the customer profiles. Although i have read the documentation thoroughly but did not succeed.
I am creating a customer profile at first when no profile is available along with a payment profile but next time when a user return and add the payment profile ( as the customer profile already exist) i am using only createCustomerPaymentProfile. The thing is, in first step i am not including $billto->setZip("44628"); and it goes well. But when i make only payment Profile it demands me to include the zip code too other wise it gives error
"There is one or more missing or invalid required fields."
I am using the exact same code which is in the php section of the documentation just a change in text/parameters.
create customer profile
create customer payment profile
For making the customer profile :
private function createCustomerProfile($data)
{
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("auth");
$merchantAuthentication->setTransactionKey("transkey");
// Set the transaction's refId
$refId = 'ref' . time();
$paymentProfile=$this->newPaymentProfile($data);
// Create a new CustomerProfileType and add the payment profile object
$customerProfile = new AnetAPI\CustomerProfileType();
$customerProfile->setDescription("Customer 2 Test PHP");
$customerProfile->setMerchantCustomerId($name. time());
$customerProfile->setEmail($email);
$customerProfile->setpaymentProfiles($paymentProfile);
// Assemble the complete transaction request
$request = new AnetAPI\CreateCustomerProfileRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setProfile($customerProfile);
// Create the controller and get the response
$controller = new AnetController\CreateCustomerProfileController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
$paymentProfiles = $response->getCustomerPaymentProfileIdList();
//Insert into database for the profile and payment profile update
} else {
echo "ERROR : Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
}
return $response;
For making the customer payment profile
private function createCustomerPaymentProfile($data){
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("name");
$merchantAuthentication->setTransactionKey("transkey");
// Set the transaction's refId
$refId = 'ref' . time();
$paymentProfile=$this->newPaymentProfile($data);
// Assemble the complete transaction request
$paymentprofilerequest = new AnetAPI\CreateCustomerPaymentProfileRequest();
$paymentprofilerequest->setMerchantAuthentication($merchantAuthentication);
// Add an existing profile id to the request
$paymentprofilerequest->setCustomerProfileId($data['profile_id']);
$paymentprofilerequest->setPaymentProfile($paymentProfile[0]);
$paymentprofilerequest->setValidationMode("liveMode");
// Create the controller and get the response
$controller = new AnetController\CreateCustomerPaymentProfileController($paymentprofilerequest);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") ) {
echo "Create Customer Payment Profile SUCCESS: " . $response->getCustomerPaymentProfileId() . "\n";
//Insert into database for the profile and payment profile update
} else {
echo "Create Customer Payment Profile: ERROR Invalid response\n";
$errorMessages = $response->getMessages()->getMessage();
echo "Response : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
}
return $response;
}
for the re-usability purpose i have make a common make payment profile which return the payment profile array
private function newPaymentProfile($data){
// Set credit card information for payment profile
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber($data['account_number']);
$creditCard->setExpirationDate($data['date']);
$creditCard->setCardCode($data['securiy_no']);
$paymentCreditCard = new AnetAPI\PaymentType();
$paymentCreditCard->setCreditCard($creditCard);
// Create the Bill To info for new payment type
$billTo = new AnetAPI\CustomerAddressType();
$billTo->setFirstName($data['holder_name']);
$billTo->setAddress($data['billing_address']);
$billTo->setPhoneNumber($data['phone']);
$billTo->setfaxNumber($data['fax']);
// Create a new CustomerPaymentProfile object
$paymentProfile = new AnetAPI\CustomerPaymentProfileType();
$paymentProfile->setCustomerType('individual');
$paymentProfile->setBillTo($billTo);
$paymentProfile->setPayment($paymentCreditCard);
$paymentProfiles[]=$paymentProfile;
return $paymentProfiles;
}

Related

Authorize.net Sandbox Accept page testing- always declined?

I’m attempting to test Accept Hosted payment page(redirect-method) with my sandbox. For this, I’m using the GetAnAcceptPaymentPage from the Java sample code application to generate a token string for a payment, specified the autoLoginId and transactionKey for my sandbox, and setting $1.00 as the amount. I’m then posting the returned token string to https://test.authorize.net/payment/payment with a “token” form element containing that string. This much appears to be working, and I do get a payment page showing the $1.00 amount. However, no matter what values I enter onto that payment page, pressing the “Pay” button just shows “The transaction has been declined.” in red text at the bottom of the form. I’ve confirmed that my sandbox is set to “Live” mode, and have looked at the following link to use what I believe should be valid values for testing: https://developer.authorize.net/hello_world/testing_guide/. I'm hoping someone can tell me why I can't get any result other than "The transaction has been declined".
public String getTokenValue() {
ApiOperationBase.setEnvironment(Environment.SANDBOX);
MerchantAuthenticationType merchantAuthenticationType = new MerchantAuthenticationType();
merchantAuthenticationType.setName("xxxxx");
merchantAuthenticationType.setTransactionKey("xxxxxx");
ApiOperationBase.setMerchantAuthentication(merchantAuthenticationType);
// Create the payment transaction request
TransactionRequestType txnRequest = new TransactionRequestType();
txnRequest.setTransactionType(TransactionTypeEnum.AUTH_CAPTURE_TRANSACTION.value());
txnRequest.setAmount(new BigDecimal(1.00).setScale(2, RoundingMode.CEILING));
OrderExType order = new OrderExType();
order.setInvoiceNumber("2");
txnRequest.setOrder(order);
CustomerProfilePaymentType cpp = new CustomerProfilePaymentType();
cpp.setCustomerProfileId("xxxx");
cpp.setCreateProfile(true);
txnRequest.setProfile(cpp);
SettingType setting1 = new SettingType();
setting1.setSettingName("hostedPaymentButtonOptions");
setting1.setSettingValue("{\"text\": \"Proceed\"}");
SettingType setting2 = new SettingType();
setting2.setSettingName("hostedPaymentOrderOptions");
setting2.setSettingValue("{\"show\": false}");
SettingType setting3 = new SettingType();
setting3.setSettingName("hostedPaymentPaymentOptions");
setting3.setSettingValue("{\"cardCodeRequired\": true}");
SettingType setting4 = new SettingType();
setting4.setSettingName("hostedPaymentIFrameCommunicatorUrl");
setting4.setSettingValue("{\"url\": \"http://example.com/abc\"}");
ArrayOfSetting alist = new ArrayOfSetting();
alist.getSetting().add(setting1);
alist.getSetting().add(setting2);
alist.getSetting().add(setting3);
alist.getSetting().add(setting4);
GetHostedPaymentPageRequest apiRequest = new GetHostedPaymentPageRequest();
apiRequest.setTransactionRequest(txnRequest);
apiRequest.setHostedPaymentSettings(alist);
GetHostedPaymentPageController controller = new GetHostedPaymentPageController(apiRequest);
controller.execute();
GetHostedPaymentPageResponse response = new GetHostedPaymentPageResponse();
response = controller.getApiResponse();
if (response != null) {
if (response.getMessages().getResultCode() == MessageTypeEnum.OK) {
System.out.println(response.getToken());
} else {
System.out.println("Failed to get hosted payment page: " + response.getMessages().getResultCode());
}
}
return response.getToken();
}
>>> order.setInvoiceNumber("2");
Set the invoice number to a different value than 2, this value is used in Sandbox to trigger decline for testing purposes.

PowerBi Api - How to get GroupId and DatasetId of Dashboard via API

I have been reading https://powerbi.microsoft.com/en-us/blog/announcing-data-refresh-apis-in-the-power-bi-service/
In this post, it mentions "To get the group ID and dataset ID, you can make a separate API call".
Does anybody know how to do this from the dashboard URL, or do I have to embed the group id and dataset id in my app alongside the dashboard URL???
To get the group ID and dataset ID, you can make a separate API call.
This sentence isn't related to a dashboard, because in one dashboard you can put visuals showing data from many different datasets. These different API calls are Get Groups (to get list of groups, find the one you want and read it's id) and Get Datasets In Group (to find the dataset you are looking for and read it's id).
But you should already know the groupId anyway, because the dashboard is in the same group.
Eventually, you can get datasetId from particular tile using Get Tiles In Group, but I do not know a way to list tiles in dashboard using the Rest API.
This is a C# project code to get the dataset id from Power BI.
Use the below method to call the 'Get' API and fetch you the dataset Id.
public void GetDatasetDetails()
{
HttpResponseMessage response = null;
HttpContent responseContent = null;
string strContent = "";
PowerBIDataset ds = null;
string serviceURL = "https://api.powerbi.com/v1.0/myorg/admin/datasets";
Console.WriteLine("");
Console.WriteLine("- Retrieving data from: " + serviceURL);
response = client.GetAsync(serviceURL).Result;
Console.WriteLine(" - Response code received: " + response.StatusCode);
try
{
responseContent = response.Content;
strContent = responseContent.ReadAsStringAsync().Result;
if (strContent.Length > 0)
{
Console.WriteLine(" - De-serializing DataSet details...");
// Parse the JSON string into objects and store in DataTable
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = 2147483647; // Set the maximum json document size to the max
ds = js.Deserialize<PowerBIDataset>(strContent);
if (ds != null)
{
if (ds.value != null)
{
foreach (PowerBIDatasetValue item in ds.value)
{
string datasetID = "";
string datasetName = "";
string datasetWeburl = "";
if (item.id != null)
{
datasetID = item.id;
}
if (item.name != null)
{
datasetName = item.name;
}
if (item.qnaEmbedURL != null)
{
datasetWeburl = item.qnaEmbedURL;
}
// Output the dataset Data
Console.WriteLine("");
Console.WriteLine("----------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("Dataset ID: " + datasetID);
Console.WriteLine("Dataset Name: " + datasetName);
Console.WriteLine("Dataset Web Url: " + datasetWeburl);
} // foreach
} // ds.value
} // ds
}
else
{
Console.WriteLine(" - No content received.");
}
}
catch (Exception ex)
{
Console.WriteLine(" - API Access Error: " + ex.ToString());
}
}
points to remember:
Make sure these classes exist in your project
PowerBIDataset is a class with List
PowerBIDatasetValue is a class with id, name and webUrl (all string data type) data members
provide below constants in your project class
const string ApplicationID = "747d78cd-xxxx-xxxx-xxxx-xxxx";
// Native Azure AD App ClientID -- Put your Client ID here
const string UserName = "user2#xxxxxxxxxxxx.onmicrosoft.com";
// Put your Active Directory / Power BI Username here (note this is not a secure place to store this!)
const string Password = "xyxxyx";
// Put your Active Directory / Power BI Password here (note this is not secure pace to store this! this is a sample only)
call this GetDatasetDetails() method in the Main method of your project class
and finally
use the below 'Get' API to get the Group Id
https://api.powerbi.com/v1.0/myorg/groups

ARB Subscription creation in Authorize.net using bank account

First of all, I am just asking that is it possible to create ARBsubscription using bank account. Almost all the example showing using credit card. But I want to do it using bank account. I am using "anet_php_sdk". Although there is also ARB with credit card in the sample code. But I changed a bit like -
<?php
require_once 'anet_php_sdk/AuthorizeNet.php';
define("AUTHORIZENET_API_LOGIN_ID", "YOURLOGIN");
define("AUTHORIZENET_TRANSACTION_KEY", "YOURKEY");
$subscription = new AuthorizeNet_Subscription;
$subscription->name = "PHP Monthly Magazine";
$subscription->intervalLength = "1";
$subscription->intervalUnit = "months";
$subscription->startDate = "2017-05-12";
$subscription->totalOccurrences = "12";
$subscription->trialOccurrences = "1";
$subscription->amount = "45.00";
$subscription->bankAccountAccountType = "CHECKING";
$subscription->bankAccountRoutingNumber= "121042882";
$subscription->bankAccountAccountNumber= "123456789123";
$subscription->bankAccountNameOnAccount= "Test Test1";
$subscription->bankAccountEcheckType = "WEB";
$subscription->bankAccountBankName = "Bank of Earth";
/*$subscription->creditCardCardNumber = "4007000000027";
$subscription->creditCardExpirationDate= "2018-10";
$subscription->creditCardCardCode = "123";*/
$subscription->billToFirstName = "test";
$subscription->billToLastName = "test1";
// Create the subscription.
$request = new AuthorizeNetARB;
$response = $request->createSubscription($subscription);
echo "<pre>";
print_r($response);
die();
$subscription_id = $response->getSubscriptionId();
?>
Yes, you can use a bank account with subscriptions. Page 22 of their guide lists all of the available fields to do so.
In your example you have both a credit card and bank payment account which is invalid. You need to remove the credit card lines of code.

Zend Framework Reg Ex not working on update form

I have a client input form that has the following two reg expressions that works when creating a client but not when updating a client. The update form is a class that extends the crate form.
// Create text input for mobile
$mobile = new Zend_Form_Element_Text ('mobile');
$mobile->setLabel ('Mobile Number:')
->setDescription('Enter mobile in the format 353XXYYYYYYY')
->setOptions(array('size'=>'14'))
->setRequired(false)
->addValidator('Regex',false,array(
'pattern'=>'/^\d{12}$/',
'messages'=>array(
Zend_Validate_Regex::INVALID => '\'%value%\' Invalid mobile number it does not match the required format 353XXYYYYYYY',
Zend_Validate_Regex::NOT_MATCH =>'\'%value%\'does not match the required format 353XXXXXXXX')
)
)
->addFilter('HtmlEntities')
->addFilter('StringTrim');
// Create text input for landline
$landline = new Zend_Form_Element_Text ('landLine');
$landline->setLabel ('Phone Number:')
->setDescription('Enter phone number in the format +353(0) X YYY YYYZ')
->setOptions(array('size'=>'20'))
->setRequired(false)
->addValidator('StringLength', false, array('min' => 8))
->addValidator('Regex', false, array(
'pattern' => '/^\+353\(0\)\s\d\s\d{3}\s\d{3,4}$/',
'messages' => array(
Zend_Validate_Regex::INVALID =>
'\'%value%\' In valid Phone number does not match required number format +353(0) X YYY YYYZ',
Zend_Validate_Regex::NOT_MATCH =>
'\'%value%\' does not match required number format of +353(0) X YYY YYYZ'
)
))
->addFilter('HtmlEntities')
->addFilter('StringTrim');
When I enter an invalid mobile or land line number when creating a client the reg expression works and prevents the record from being saved.
However when I enter an invalid mobile or land line number when updating a client the reg expression fails and an 404 error occurs.
I think that the issue may be related to the get section of my update action within my controller as shown below but I can't figure out what is causing this as the route I have configured in my ini file retrieves the record as required.
public function updateAction(){
// generate input form
$form = new PetManager_Form_UpdateClient;
$this->view->form=$form;
/* if the requrest was made via post
test if the input is valid
retrieve current record
update values and save to DB */
if($form->isValid($this->getRequest()->getPost())){
$input=$form->getValues();
$client = Doctrine::getTable('PetManager_Model_Clients')
->find($input['clientid']);
$client->fromArray($input);
if($client->email=='')
{$client->email=NULL;}
if($client->mobile=='')
{$client->mobile=NULL;}
if($client->landLine=='')
{$client->landLine=NULL;}
if($client->address3=='')
{$client->address3=NULL;}
$client->save();
$sessionClient = new Zend_Session_Namespace('sessionClient');
$id = $client->clientid;
$fname = $client->firstName;
$lname = $client->lastName;
$sessionClient->clientid=$id;
$sessionClient->clientfName=$fname;
$sessionClient->clientlName=$lname;
$sessionClient->clientfName=$fname;
$this->_helper->getHelper('FlashMessenger')
->addMessage('The record for '.$fname.' '.$lname. ' was successfully updated.');
$this->_redirect('clients/client/success');
}else{
/* if GET request
set filters and validators for GET input
test if input is valid, retrieve requested
record and pree-populate the form */
$filters = array(
'id'=>array('HtmlEntities','StripTags','StringTrim')
);
$validators = array(
'id'=>array('NotEmpty','Int')
);
$input = new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$qry = Doctrine_Query::create()
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties co')
->where('c.clientid=?',$input->id);
$result = $qry->fetchArray();
if(count($result)==1){
$this->view->form->populate($result[0]);
}else{
throw new Zend_Controller_Action_Exception('Page not found',404);
}
}else{
throw new Zend_Controller_Action_Exception('Invalid Input');
}
}
}
All help greatly appreciated.
Ok I've sorted this I stupidly left out a check in my update action to see if the request was being made by post as this is the action defined in my form.
The corrected code is shown below in case this helps anyone else.
// action to update an individual clients details
public function updateAction()
{
// generate input form
$form = new PetManager_Form_UpdateClient;
$this->view->form=$form;
/* if the requrest was made via post
test if the input is valid
retrieve current record
update values and save to DB */
if ($this->getRequest()->isPost()) {
if($form->isValid($this->getRequest()->getPost())){
$input=$form->getValues();
$client = Doctrine::getTable('PetManager_Model_Clients')
->find($input['clientid']);
$client->fromArray($input);
if($client->email=='')
{$client->email=NULL;}
if($client->mobile=='')
{$client->mobile=NULL;}
if($client->landLine=='')
{$client->landLine=NULL;}
if($client->address3=='')
{$client->address3=NULL;}
$client->save();
$sessionClient = new Zend_Session_Namespace('sessionClient');
$id = $client->clientid;
$fname = $client->firstName;
$lname = $client->lastName;
$sessionClient->clientid=$id;
$sessionClient->clientfName=$fname;
$sessionClient->clientlName=$lname;
$sessionClient->clientfName=$fname;
$this->_helper->getHelper('FlashMessenger')
->addMessage('The record for '.$fname.' '.$lname. ' was successfully updated.');
$this->_redirect('clients/client/success');
}
}else{
/* if GET request
set filters and validators for GET input
test if input is valid, retrieve requested
record and pree-populate the form */
$filters = array(
'id'=>array('HtmlEntities','StripTags','StringTrim')
);
$validators = array(
'id'=>array('NotEmpty','Int')
);
$input = new Zend_Filter_Input($filters,$validators);
$input->setData($this->getRequest()->getParams());
if($input->isValid()){
$qry = Doctrine_Query::create()
->from('PetManager_Model_Clients c')
->leftJoin('c.PetManager_Model_Counties co')
->where('c.clientID=?',$input->id);
$result = $qry->fetchArray();
if(count($result)==1){
$this->view->form->populate($result[0]);
}else{
$t=count($result);
throw new Zend_Controller_Action_Exception('Page not found',404);
}
}else{
throw new Zend_Controller_Action_Exception('Invalid Input');
}
}
}

Using the Reporting Services Web Service, how do you get the permissions of a particular user?

Using the SQL Server Reporting Services Web Service, how can I determine the permissions of a particular domain user for a particular report? The user in question is not the user that is accessing the Web Service.
I am accessing the Web Service using a domain service account (lets say MYDOMAIN\SSRSAdmin) that has full permissions in SSRS. I would like to programmatically find the permissions of a domain user (lets say MYDOMAIN\JimBob) for a particular report.
The GetPermissions() method on the Web Service will return a list of permissions that the current user has (MYDOMAIN\SSRSAdmin), but that is not what I'm looking for. How can I get this same list of permissions for MYDOMAIN\JimBob? I will not have the user's domain password, so using their credentials to call the GetPermissions() method is not an option. I am however accessing this from an account that has full permissions, so I would think that theoretically the information should be available to it.
SSRS gets the NT groups from the users' NT login token. This is why when you are added to a new group, you are expected to log out and back in. The same applies to most Windows checks (SQL Server, shares, NTFS etc).
If you know the NT group(s)...
You can query the ReportServer database directly. I've lifted this almost directly out of one of our reports which we use to check folder security (C.Type = 1). Filter on U.UserName.
SELECT
R.RoleName,
U.UserName,
C.Path
FROM
ReportServer.dbo.Catalog C WITH (NOLOCK) --Parent
JOIN
ReportServer.dbo.Policies P WITH (NOLOCK) ON C.PolicyID = P.PolicyID
JOIN
ReportServer.dbo.PolicyUserRole PUR WITH (NOLOCK) ON P.PolicyID = PUR.PolicyID
JOIN
ReportServer.dbo.Users U WITH (NOLOCK) ON PUR.UserID = U.UserID
JOIN
ReportServer.dbo.Roles R WITH (NOLOCK) ON PUR.RoleID = R.RoleID
WHERE
C.Type = 1
look into "GetPolicies Method" you can see at the following link.
http://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010.getpolicies.aspx
Hopefully this will get you started. I use it when copying Folder structure, and Reports from an old server to a new server when I want to 'migrate' my SSRS items from the Source to the Destination Server. It is a a Method to Get the Security Policies for an item on one server, and then set the Security Policies for an identical item on another server, after I have copied the item from the Source Server to the Destination Server. You have to set your own Source and Destination Server Names.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web.Services.Protocols; //<=== required for SoapException
namespace SSRS_WebServices_Utility
{
internal static class TEST
{
internal static void GetPoliciesForAnItem_from_Source_ThenSetThePolicyForTheItem_on_Destination(string itemPath)
{
string sSourceServer = "SOURCE-ServerName";
Source_ReportService2010.ReportingService2010 sourceRS = new Source_ReportService2010.ReportingService2010();
sourceRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
sourceRS.Url = #"http://" + sSourceServer + "/reportserver/reportservice2010.asmx";
string sDestinationServer = "DESTINATION-ServerName";
Destination_ReportService2010.ReportingService2010 DestinationRS = new Destination_ReportService2010.ReportingService2010();
DestinationRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
DestinationRS.Url = #"http://" + sDestinationServer + "/reportserver/reportservice2010.asmx";
Boolean val = true;
Source_ReportService2010.Policy[] curPolicy = null;
Destination_ReportService2010.Policy[] newPolicy = null;
try
{
curPolicy = new Source_ReportService2010.Policy[1];
curPolicy = sourceRS.GetPolicies(itemPath, out val); //e.g. of itemPath: "/B2W/001_OLD_PuertoRicoReport"
//DestinationRS.SetPolicies(itemPath, newPolicy);
int iCounter = 0;
//int iMax = curPolicy.Length;
newPolicy = new Destination_ReportService2010.Policy[curPolicy.Length];
foreach (Source_ReportService2010.Policy p in curPolicy)
{
//create the Policy
Destination_ReportService2010.Policy pNew = new Destination_ReportService2010.Policy();
pNew.GroupUserName = p.GroupUserName;
pNew.GroupUserName = p.GroupUserName;
Destination_ReportService2010.Role rNew = new Destination_ReportService2010.Role();
rNew.Description = p.Roles[0].Description;
rNew.Name = p.Roles[0].Name;
//create the Role, which is part of the Policy
pNew.Roles = new Destination_ReportService2010.Role[1];
pNew.Roles[0]=rNew;
newPolicy[iCounter] = pNew;
iCounter += 1;
}
DestinationRS.SetPolicies(itemPath, newPolicy);
Debug.Print("whatever");
}
catch (SoapException ex)
{
Debug.Print("SoapException: " + ex.Message);
}
catch (Exception Ex)
{
Debug.Print("NON-SoapException: " + Ex.Message);
}
finally
{
if (sourceRS != null)
sourceRS.Dispose();
if (DestinationRS != null)
DestinationRS.Dispose();
}
}
}
}
To invoke it use the following:
TEST.GetPoliciesForAnItem_from_Source_ThenSetThePolicyForTheItem_on_Destination("/FolderName/ReportName");
Where you have to put your own SSRS Folder Name and Report Name, i.e. the Path to the item.
In fact I use a method that loops through all the items in the Destination folder that then calls the method like this:
internal static void CopyTheSecurityPolicyFromSourceToDestinationForAllItems_2010()
{
string sDestinationServer = "DESTINATION-ServerName";
Destination_ReportService2010.ReportingService2010 DestinationRS = new Destination_ReportService2010.ReportingService2010();
DestinationRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
DestinationRS.Url = #"http://" + sDestinationServer + "/reportserver/reportservice2010.asmx";
// Return a list of catalog items in the report server database
Destination_ReportService2010.CatalogItem[] items = DestinationRS.ListChildren("/", true);
// For each FOLDER, debug Print some properties
foreach (Destination_ReportService2010.CatalogItem ci in items)
{
{
Debug.Print("START----------------------------------------------------");
Debug.Print("Object Name: " + ci.Name);
Debug.Print("Object Type: " + ci.TypeName);
Debug.Print("Object Path: " + ci.Path);
Debug.Print("Object Description: " + ci.Description);
Debug.Print("Object ID: " + ci.ID);
Debug.Print("END----------------------------------------------------");
try
{
GetPoliciesForAnItem_from_Source_ThenSetThePolicyForTheItem_on_Destination(ci.Path);
}
catch (SoapException e)
{
Debug.Print("SoapException START----------------------------------------------------");
Debug.Print(e.Detail.InnerXml);
Debug.Print("SoapException END----------------------------------------------------");
}
catch (Exception ex)
{
Debug.Print("ERROR START----------------------------------------------------");
Debug.Print(ex.GetType().FullName);
Debug.Print(ex.Message);
Debug.Print("ERROR END----------------------------------------------------");
}
}
}
}