fatal: remote error: CAPTCHA required - Bitbucket - Powershell Script - c#

I wants to checkout the branch and commit the code changes using powershell script. This powershell script will be called from c# code.
But some times i'm getting the following issue
fatal: remote error: CAPTCHA required Your Bitbucket account has been
locked. To unlock it and log in again you must solve a CAPTCHA. This
is typically caused by too many attempts to login with an incorrect
password. The account lock prevents your SCM client from accessing
Bitbucket and its mirrors until it is solved, even if you enter your
password correctly.
If i logout in browser and login again by entering the CAPTCHA it is working fine. But if i host my application on server and if issue occurs, Logging out and login again is not the proper fix.
Can you please suggest good approach of handling this issue.
My Powershell code for Cloning the branch:
param(
[parameter(position=0)]
[string]$checkoutDirectory,
[parameter(position=1)]
[string]$checkoutBranch
)
function CheckoutTheCode($checkoutRepoUrl, $checkoutDirectory, $checkoutBranch)
{
[hashtable]$Return = #{}
try
{
if(Test-Path -Path $checkoutDirectory )
{
Remove-Item -Recurse -Force $checkoutDirectory
}
New-Item -ItemType directory -Path $checkoutDirectory
# Cloning
git clone --single-branch -b $checkoutBranch $checkoutRepoUrl $checkoutDirectory
$Return.Branch = $checkoutBranch
$Return.Directory = $checkoutDirectory
$Return.Status = $true
$Return.Message = "Success"
}
catch
{
$Return.Message = $Error[0].Exception
$Return.Status = $false
}
Return $Return
}
My Powershell code for Commit changes:
param(
[parameter(position=0)]
[string]$checkoutDirectory,
[parameter(position=1)]
[string]$commitMessage
)
function CommitTheCode($checkoutDirectory, $commitMessage)
{
[hashtable]$Return = #{}
try
{
cd $checkoutDirectory
git add .
git commit -m $commitMessage
git push
$Return.Status = $true
$Return.Message = "Success"
}
catch
{
$Return.Message = $Error[0].Exception
$Return.Status = $false
}
Return $Return
}
CommitTheCode $checkoutDirectory $commitMessage

The following steps worked for me (without asking a Bitbucket admin to click a button)
For Windows,
go to the credential manager (you can find this by searching for it in Start menu)
remove all credentials related to your bitbucket account
try again with your script.

Related

Trouble mounting ActiveDirectory Drive in PowerShell using .Net Core

We're creating a micro-service to do a few things in AD. This service requires that active directory be mounted to AD as a PSDrive.
I understand how the mounting works and can do it successfully in PowerShell on the server.
For the module to be added we had to specify the physical location to ActiveDirectory.psd1 for it to import.
I suspect this is the reason why the following script does not execute successfully.
Script:
New-PSDrive -PSProvider ActiveDirectory -Name AD -Root \"\" -Server (Get-ADDomainController -Discover -Service PrimaryDC).Name
If executed like this, the exception thrown says that the parameter Server is invalid.
When removing this parameter, the exception says that the provider ActiveDirectory does not exist.
Am I taking the right approach to this?
Here is the C# code:
string moduleDirectory = Configuration["AppSettings:Directories:PowerShellModules"];
var requiredPowerShellModules = new Dictionary<string, string>()
{
{ "ActiveDirectory", $"{moduleDirectory}\\ActiveDirectory\\ActiveDirectory.psd1" }
};
foreach (KeyValuePair<string, string> module in requiredPowerShellModules)
{
bool hasModule = Modules.HasModule(module.Key, powerShell);
if (!hasModule)
{
Modules.ImportModule(module.Value, powerShell);
if (!Modules.HasModule(module.Key, powerShell))
{
throw new Exception($"Unable to import PowerShell module: \"{module.Key}\" at path \"{module.Value}\"");
}
}
}
//Check if AD Drive mounted
var adDriveResult = powerShell.AddScript("Get-PSDrive AD -ErrorAction SilentlyContinue").Invoke();
//Mount AD Drive if not exists
if (adDriveResult.Count != 1)
powerShell
.AddScript("New-PSDrive -PSProvider ActiveDirectory -Name AD -Root \"\" -Server (Get-ADDomainController -Discover -Service PrimaryDC).Name ") //
.Invoke();
The issue was caused by an outdated version of ActiveDirectory powershell module.
Version 1.0.0.0 was on the server, instead of 1.0.1.0.

How can I persist changes to Console.Title past the lifecycle of a process in C#?

Powershell is able to change the Title text of a terminal that outlives the process that sets it.
https://github.com/dahlbyk/posh-git/blob/a8adab23190584668b562954e778169c04364755/src/posh-git.psm1
Is an example of "Posh Git" a Powershell script for git, that shows the status of a git repository in the title bar and prompt when working inside powershell.
At work we have a Console C# app, that I wish to do the same thing (Setting the title window, but having it persist past the app's lifecycle)
It can be run from either PowerShell or cmd.
At the moment I set the title like this:
var path = RepositoryHelpers.TryGetContainerRootPath(workingDirectory);
using (var containerRepo = new Repository(path))
{
Console.Title = $"GitSAFE - {containerRepo.Head.FriendlyName}";
}
However, the Console.Title property is reset once the process is over.
How can I persist changes to the Console Title using C#?
Technically you can't persist the change you are asking about. However you can create a profile script that sets the title every time you launch powershell. On a windows machine you can create a file at C:\Users\_your_user_id\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. You could put your commands in there. The down side to this is that every user has to update his profile. There is also a machine profile that influences startup scripts that you can set through global policy.
One possible mitigation is you could create a script that checks for a startup script that you can configure using windows infrastructure. Here's a snippet of my profile that does this:
Write-Host "Hello From Your Profile: $PsScriptRoot"
$gitDrive = $env:GitDrive
if ($gitDrive -ne "" -and $gitDrive -ne $null) {
if (Test-Path "$($gitDrive)") {
Write-Host "Your GitDrive is $($gitDrive)"
}
else {
Write-Host "Your GitDrive is $($GitDrive) but that path does not exist." -Fore Yellow
Write-Host "Update the environment variable to point to your enlistment." -Fore Yellow
exit
}
if (Test-Path "$($gitDrive)AutoStart.PS1") {
. "$($gitDrive)AutoStart.PS1"
}
exit
}
else {
Write-Host "Add your GitDrive environment variable to your profile."
}
As long as you have an environment variable that points to your git repos folder its AutoStart.ps1 scripts runs at every shell. YMMV but this works on my machine.

How to check whether folder exists on multiple servers?

I have written below PowerShell script in one server to search for folder existence in other servers.
$Servers = Get-Content C:\scripts\serverlist.txt
foreach ($Server in $Servers) {
$Test = Test-Path -Path "\\$Server\c$\Documents and Settings\"
if ($Test -eq $true) {
Write-Host "Path exists on $Server."
} else {
Write-Host "Path NOT exist on $Server."
}
}
I am getting correct answer if I search for folders present in same server, but if I search for folders present in other server am getting "Path NOT exist on $Server" even though it is present.
Later I tried this one. With this also am facing the same issue
Get-Content c:\Users\jason\Documents\Scripts\Serverlist.txt |
Select-Object #{Name='ComputerName';Expression={$_}},
#{Name='FolderExist';Expression={Test-Path "\\$_\c$\program files\folder"}}
Also, please let me know if there is any method for this using C#.

How to update url stored in Sharepoint add-in app file?

I created an High-Trust add-in for SharePoint 2013 with custom ribbon action and custom menu action.
For this, I have an ASP.NET MVC WebSite with the methods in the controller which match with the virtual urls put as custom action url. So, in the different elements.xml files, I filled action urls using the token 'remoteUrl', so no problem with the mapping.
When i create a package with VS2013, I write the url of my website which is on VM reachable from SP Server, and the client ID (I got from SP while registring my app). When I click on 'Finish', VS2013 generates a file '.app' which can be imported in SP online store or SP internal store.
Here is my problem, if I need to change the address of my website (which is stored in the app file, VS2013 just replaces the token 'RemoteUrl' with the url I give to it), is there any clean way to update the app file or may be if possible, directly the app stored in the SP application store (local to the server) ?
I found nothing for this problem. I saw few things about updating app with events and web services, but I didn't understood.
[EDIT] : I didn't understood that I have to change app version each time I need to update it that's why It didn't worked. Also, it seems that there is no other way to update the url in app file than modifying the AppManifest.xml in app file (which is a zip).
In one of my projects we used to do it with the following PowerShell script. It extracted the app file (it's just a ZIP) and modified multiple nodes in the manifest XML.
For packaging it uses a local copy of 7zip.
function ModifyAppPackage($appPackagePath, $applicationUrl, $clientId){
[Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem");
$item = get-item $appPackagePath;
$zipFilePath = Join-Path $item.Directory.FullName $($item.BaseName + ".zip");
Copy-Item $item $zipFilePath;
$unzipDirectory = Join-Path $PSScriptRoot "\Temp";
New-Item -ItemType Directory -Force -Path $unzipDirectory;
if (Test-Path -Path $unzipDirectory\*)
{
Remove-Item $unzipDirectory\* -Force -Confirm:$false -Recurse:$true;
}
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipFilePath, $unzipDirectory);
$modifiedFile = Join-Path $unzipDirectory "modified.txt"
if (Test-Path -Path $modifiedFile)
{
$modifiedContent = Get-Content $modifiedFile
if ($modifiedContent -eq $applicationUrl)
{
Remove-Item $unzipDirectory -Confirm:$false -Recurse:$true;
Remove-Item $zipFilePath;
return;
}
Remove-Item $modifiedFile;
}
$modifiedFileContent = $applicationUrl;
$modifiedFileContent >> $modifiedFile;
$manifestFileName = "AppManifest.xml";
$manifestFilePath = Join-Path $unzipDirectory $manifestFileName;
$manifestXml = [xml](get-content $manifestFilePath);
$nameSpaceManager = New-Object System.Xml.XmlNamespaceManager($manifestXml.NameTable);
$nameSpaceManager.AddNamespace("ns", $manifestXml.DocumentElement.NamespaceURI);
$startPageElement = $manifestXml.SelectSingleNode("/ns:App/ns:Properties/ns:StartPage", $nameSpaceManager);
$StartPage = $applicationUrl + "?{StandardTokens}"
$startPageElement.'#text' = $StartPage
$InstalledEventEndpointElement = $manifestXml.SelectSingleNode("/ns:App/ns:Properties/ns:InstalledEventEndpoint", $nameSpaceManager);
$InstalledEventEndpoint = $applicationUrl + "/Services/AppEventReceiver.svc"
$InstalledEventEndpointElement.'#text' = $InstalledEventEndpoint
$clientIdElement = $manifestXml.SelectSingleNode("/ns:App/ns:AppPrincipal/ns:RemoteWebApplication", $nameSpaceManager);
$clientIdElement.ClientId = $clientId;
$manifestXml.Save($manifestFilePath);
if (Test-Path -Path $zipFilePath)
{
Remove-Item $zipFilePath;
}
$pathToZipExe = $("$PSScriptRoot\7za.exe");
[Array]$arguments = "a", "-tzip", "$zipFilePath", "$unzipDirectory\*.*", "-r";
& $pathToZipExe $arguments;
# Cleanup
Remove-Item $unzipDirectory -Confirm:$false -Recurse:$true;
Remove-Item $appPackagePath -Confirm:$false;
# Rename new zip to .app
Rename-Item $zipFilePath $appPackagePath -Force -Confirm:$false;
return $true;
}
I think it would be possible to store the url in one of custom list in the app. Refer the url from the list. Whenever you need to change the url it can be done from the app itself.

Azure, Increase Worker Count Programatically, Management API / Cmdlets? (without reboot) [duplicate]

Is it possible to update the value of a setting in an Azure Cloud Service with Azure Powershell?
So far there is no way to update just a single setting (the Service Management API does not allow it - it only accepts the whole service configuration). So, in order to update a single setting, you will have to update the entire configuration. And you can do this with PowerShell:
# Add the Azure Account first - this will create a login promppt
Add-AzureAccount
# when you have more then one subscription - you have explicitly select the one
# which holds your cloud service you want to update
Select-AzureSubscription "<Subscription name with spaces goes here>"
# then Update the configuration for the cloud service
Set-AzureDeployment -Config -ServiceName "<cloud_service_name_goes_here>" `
-Configuration "D:/tmp/cloud/ServiceConfiguration.Cloud.cscfg" `
-Slot "Production"
For the the `-Configuration' parameter I have provided full local path to the new config file I want to use with my cloud service.
This is verified and working solution.
As astaykov says, you can't update a single cloud config value using Powershell.
But you can read all of the settings, update the one you wish to change, save it to a temp file, and then set all the settings again, like so:
UpdateCloudConfig.ps1:
param
(
[string] $cloudService,
[string] $publishSettings,
[string] $subscription,
[string] $role,
[string] $setting,
[string] $value
)
# param checking code removed for brevity
Import-AzurePublishSettingsFile $publishSettings -ErrorAction Stop | Out-Null
function SaveNewSettingInXmlFile($cloudService, [xml]$configuration, $setting, [string]$value)
{
# get the <Role name="Customer.Api"> or <Role name="Customer.NewsletterSubscription.Api"> or <Role name="Identity.Web"> element
$roleElement = $configuration.ServiceConfiguration.Role | ? { $_.name -eq $role }
if (-not($roleElement))
{
Throw "Could not find role $role in existing cloud config"
}
# get the existing AzureServiceBusQueueConfig.ConnectionString element
$settingElement = $roleElement.ConfigurationSettings.Setting | ? { $_.name -eq $setting }
if (-not($settingElement))
{
Throw "Could not find existing element in cloud config with name $setting"
}
if ($settingElement.value -eq $value)
{
Write-Host "No change detected, so will not update cloud config"
return $null
}
# update the value
$settingElement.value = $value
# write configuration out to a file
$filename = $cloudService + ".cscfg"
$configuration.Save("$pwd\$filename")
return $filename
}
Write-Host "Updating setting for $cloudService" -ForegroundColor Green
Select-AzureSubscription -SubscriptionName $subscription -ErrorAction Stop
# get the current settings from Azure
$deployment = Get-AzureDeployment $cloudService -ErrorAction Stop
# save settings with new value to a .cscfg file
$filename = SaveNewSettingInXmlFile $cloudService $deployment.Configuration $setting $value
if (-not($filename)) # there was no change to the cloud config so we can exit nicely
{
return
}
# change the settings in Azure
Set-AzureDeployment -Config -ServiceName $cloudService -Configuration "$pwd\$filename" -Slot Production
# clean up - delete .cscfg file
Remove-Item ("$pwd\$filename")
Write-Host "done"

Categories

Resources