Convert .Net example to PowerShell - asp.net

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)

Related

Azure Resource Manager DNS: Sample code to create a DNS record

I'm currently trying to move out from using old Microsoft.Azure.Management.Dns package to the new Azure.ResourceManager.Dns.
However I've been having issues in our code that creates Dns records such as an Arecord.
I've tried to go through the official documentation https://learn.microsoft.com/en-us/dotnet/api/azure.resourcemanager.dns.dnsarecordcollection.createorupdate?view=azure-dotnet
But the classes that represent an Arecord are either read only or private so I have no idea how to update this simple lines:
RecordSet set = DnsManagementClient.client.RecordSets.Get(resourceGroupName, zone, recordSetName, RecordType.A);
set.ARecords = set.ARecords ?? new List<ARecord>();
set.ARecords.Add(new ARecord(ipAddress));
DnsManagementClient.client.RecordSets.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, zone, recordSetName, RecordType.A, set, ifNoneMatch: "*");
Currently documentation only talks about Zones, can an example be added to the official documentation on how to add or update a DNS record (A,CNAME,etc..)
https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/dns/Azure.ResourceManager.Dns
I'm expecting a method to create an A record that let's you specify an IP address, and currently all the classes that potentially can be used to do that are either read-only or internal.
DnsARecordData has an internal list of Arecords, DnsARecordData.DnsARecords is where we can invoke the Add method to create the record. The reason DnsARecordData doesn't have a setter method is due to the .Net framework design guideline..
An example of how to create an A record using Azure.Resourcemanager.Dns can be found here:
// Create or update A record
string myARecordName = "myrecord";
DnsARecordData dnsARecordData = new() {TtlInSeconds = (long)TimeSpan.FromHours(1).TotalSeconds};
dnsARecordData.DnsARecords.Add(new DnsARecordInfo { IPv4Address = IPAddress.Parse("127.0.0.1") });
DnsARecordCollection dnsARecordCollection1 = dnsZoneResource.GetDnsARecords();
dnsARecordCollection1.CreateOrUpdate(WaitUntil.Completed, myARecordName, dnsARecordData);
// Create or update CName pointing to A record
string myCnameName = "mycname";
DnsCnameRecordData dnsCnameRecordData = new() { Cname = $"{myARecordName}.{DnsZone}", TtlInSeconds = (long)TimeSpan.FromMinutes(10).TotalSeconds, };
DnsCnameRecordCollection cnameRecordCollection = dnsZoneResource.GetDnsCnameRecords();
cnameRecordCollection.CreateOrUpdate(WaitUntil.Completed, myCnameName, dnsCnameRecordData);
I tried in my environment and got below results:
You can create A record set using Azure.ResourceManager.Dns package. The version of NuGet package is beta-1.
NuGet Package:
Azure.ResourceManager.Dns 1.0.0 beta-1
Code:
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Dns;
using Azure.ResourceManager.Resources;
using System.Net;
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
// first we need to get the resource group
string rgName = "rg-name";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName);
string dnsZoneName = "dns name";
DnsZoneCollection dnsZoneCollection = resourceGroup.GetDnsZones();
DnsZoneData data1 = new DnsZoneData("Global")
{
};
ArmOperation<DnsZoneResource> lro = await dnsZoneCollection.CreateOrUpdateAsync(WaitUntil.Completed, dnsZoneName, data1);
DnsZoneResource dnsZone = lro.Value;
RecordSetACollection recordSetACollection = dnsZone.GetRecordSetAs();
string name = "cname1";
var parm = new ARecordSetData();
parm.TTL =600;
parm.ARecords = new List<ARecord>();
parm.ARecords.Add(new ARecord("1.2.3.4"));
ArmOperation<RecordSetAResource> recordSetAResource = recordSetACollection.CreateOrUpdate(WaitUntil.Completed, name,parm);
RecordSetAResource recordSetAs = recordSetAResource.Value;
Console:
Portal:
For more reference:
azure-sdk-for-net/Sample2_ManagingRecordSetPtrs.md at dvbb-mgmt-track2-dns-2 · dvbb/azure-sdk-for-net (github.com)

Sharepoint development using PowerShell

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
}

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).

How can I send another variable with FileReference Upload?

I have a problem with the filereference class using the upload function.
I want to send the folderLocation variable with fileReference.upload().
Below I try to describe my strategy.
var folderLocation : String = "photos/myUniqueFolder/";
private var serverSideScript:String = "http://localhost/project/phpFlexMechanism/upload.php";
urlRequest = new URLRequest(serverSideScript);
fileReferenceList.addEventListener(Event.SELECT, fileSelectedHandler);
private function fileSelectedHandler(event:Event):void {
// upload the file to the server side script
fileReference.addEventListener(Event.COMPLETE, uploadCompleteHandler);
fileReference.upload(urlRequest);
}
In PHP I use this to get the the file and uploaded
$folder = $_POST['folder'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$fileName = $_FILES['Filedata']['name'];
$fileSize = $_FILES['Filedata']['size'];
move_uploaded_file($tempFile, "../user/$folder/uploadImages/" . $fileName);
But how can I send the folder through the "upload reference"?
I would think that, since you FileReference needs a URLRequest, you would be able to piggy back that information through the URLRequest itself by using the flash.net.URLVariables object.
I've not had time to test this, but have you tried:
// put this right after you instantiate urlRequest;
var urlVars:URLVariables = new URLVariables();
urlVars.targetFolder = folderLocation;
urlRequest.method = "post";
urlRequest.data = urlVar;
That should let you do:
//replace your last line with these two.
$folder = $_REQUEST[ "targetFolder" ];
move_uploaded_file($tempFile, "../user/$folder/uploadImages/" . $fileName);
in PHP.
the easiest thing you can do is just send it through with a get header in the upload function
so the code looks as follows
private var serverSideScript:String = "http://localhost/project/phpFlexMechanism/upload.php?extraVar=value&extraVarB=value2";
fileReference.upload(urlRequest);
then in the php script you just use
$_GET['extraValue']
$_GET['valueVarB']

Resources