Adding bookmark to web browser from external applications - c#

Does anyone know if it is possible to add bookmark to web browsers (Safari, IE, FF, Chrome, Opera) from external applications ?

For IE :
You need to create a link file here :
c#
Environment.GetFolderPath(Environment.SpecialFolder.Favorites)
Powershell
[Environment]::GetFolderPath( [System.Environment+SpecialFolder]::Favorites)
Chrome:
You need to add entry in json format file bookmarks (with no extension):
on Win7 is
C:\Users\<YOURUSERNAME>\AppData\Local\Google\Chrome\User Data\Default\
Firefox:
The bookmarks are stored in a SQLite:
../Application Data/Mozilla/Firefox/Profiles/{your firefox profile}/places.sqlite
Using System.Data.SQLite you can try to add link, but I can't help you more.
Can't help you for Safari and Opera

In Powershell V2 ISE (x86), this code will list all the Special Folders on the system or even this -
$objShell = New-Object -com "Wscript.Shell"
$objShell.SpecialFolders | WHERE {$_.ToString() -match "Fav"}
You can then access & manipulate the C:\Users\username\Favorites folder. I don't know if this will extend to all browsers [except IE]

Here is the solution I came up with for adding bookmarks to Chrome from PowerShell:
$fileBookmarks="$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Bookmarks"
$dataBookmarks=Get-Content $fileBookmarks -Encoding UTF8| Out-String |ConvertFrom-Json
function createNewChromeBookmark ($Bookmarks, [string]$BookmarkName, [string]$BookmarkURL) {
function getBookmarkIDs($object){
$object | ForEach-Object{
"{0:0000}" -f [int]($_.id);
if([bool]($_.PSobject.Properties.name -match "children")){
GetBookmarkIDs($_.children);
}
}
};
$nextBookmarkID = [int](getBookmarkIDs -object $Bookmarks.roots.bookmark_bar|Sort-Object -Descending|Select-Object -First 1) + 1
$currentChomeTime=[System.DateTimeOffset]::Now.ToUnixTimeMilliseconds()*10000;
$newBookmark= [PSCustomObject]#{
date_added=$currentChomeTime
guid=[guid]::NewGuid()
id=$nextBookMarkID
name="$BookmarkName"
type="url"
url="$BookmarkURL"
}
return $newBookmark;
}
$newBookmark = createNewChromeBookmark -Bookmarks $dataBookmarks -BookmarkName "Your Bookmark Name" -BookmarkURL "https://[Your URL Here]";
$dataBookmarks.roots.bookmark_bar.children += $newBookmark;
$dataBookmarksJSON = ConvertTo-Json -InputObject $dataBookmarks -Depth 200
Set-Content -Path $fileBookmarks -Value $dataBookmarksJSON -Encoding UTF8

Related

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

Jenkins build blocks because of a windows form

We have a .net application where it checks whether the build is on release mode and open up a simple windows form to input the version as a pre build event. I made this form to automatically close in 10 seconds if the user does not give an input. But unfortunately, in Jenkins, the build gets stuck on this step without going forward. So my guess was since Jenkins runs on command line it waits until the user input for continue. But even when I add automatically close the form it does not continue. Is there a way to build this job without UI blocking Jenkins?
You are not using Jenkins in the optimal way. Here are a few tips to help you out:
Get rid of your windows form to increment version
Add a CommonAssemblyInfo.cs in your visual studio solution with an initial version number
Force Jenkins to increment the version automatically [described below]
Commit the file by jenkins using git publisher or using svn.exe with commit flag
Reading Version number using powershell:
param([string]$assemblyInfoPath, [string]$workSpace)
$contents = [System.IO.File]::ReadAllText($assemblyInfoPath)
$versionString = [RegEx]::Match($contents,"(AssemblyFileVersion\("")(?:\d+\.\d+\.\d+\.\d+)(""\))")
Write-Host ("AssemblyFileVersion: " +$versionString)
$version = gc $assemblyInfoPath | select-string -pattern "AssemblyVersion"
$version -match '^\[assembly: AssemblyVersion\(\"(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<revision>[0-9]+)\.(?<build>[0-9]+)\"\)\]'
$BuildVersionNumber = $matches["major"]+"."+$matches["minor"]+"."+$matches["revision"]+"."+$matches["build"]
Write-Host ("WorkSpace: " + $env:WORKSPACE.ToString()+"\version.txt")
#[Environment]::SetEnvironmentVariable("BUILD_NUMBER", $BuildVersionNumber, "Machine")
$path = $env:WORKSPACE.ToString() + "\version.txt"
$BuildVersionNumber | out-file -encoding ASCII -filepath $path
Increment Version using powershell:
#
# This script will increment the build number in an AssemblyInfo.cs file
#
param([string]$assemblyInfoPath, [string]$workSpace)
$contents = [System.IO.File]::ReadAllText($assemblyInfoPath)
$versionString = [RegEx]::Match($contents,"(AssemblyFileVersion\("")(?:\d+\.\d+\.\d+\.\d+)(""\))")
Write-Host ("AssemblyFileVersion: " +$versionString)
#Parse out the current build number from the AssemblyFileVersion
$currentBuild = [RegEx]::Match($versionString,"(\.)(\d+)(""\))").Groups[2]
Write-Host ("Current Build: " + $currentBuild.Value)
#Increment the build number
$newBuild= [int]$currentBuild.Value + 1
Write-Host ("New Build: " + $newBuild)
#update AssemblyFileVersion and AssemblyVersion, then write to file
Write-Host ("Setting version in assembly info file ")
$contents = [RegEx]::Replace($contents, "(AssemblyVersion\(""\d+\.\d+\.\d+\.)(?:\d+)(""\))", ("`${1}" + $newBuild.ToString() + "`${2}"))
$contents = [RegEx]::Replace($contents, "(AssemblyFileVersion\(""\d+\.\d+\.\d+\.)(?:\d+)(""\))", ("`${1}" + $newBuild.ToString() + "`${2}"))
[System.IO.File]::WriteAllText($assemblyInfoPath, $contents)
$version = gc $assemblyInfoPath | select-string -pattern "AssemblyVersion"
$version -match '^\[assembly: AssemblyVersion\(\"(?<major>[0-9]+)\.(?<minor>[0-9]+)\.(?<revision>[0-9]+)\.(?<build>[0-9]+)\"\)\]'
$BuildVersionNumber = $matches["major"]+"."+$matches["minor"]+"."+$matches["revision"]+"."+$matches["build"]
Write-Host ("WorkSpace: " + $env:WORKSPACE.ToString()+"\version.txt")
#[Environment]::SetEnvironmentVariable("BUILD_NUMBER", $BuildVersionNumber, "Machine")
$path = $env:WORKSPACE.ToString() + "\version.txt"
$BuildVersionNumber | out-file -encoding ASCII -filepath $path
Usage in Jenkins:
Version Format in CommonAssembly: 1.0.0.0
After incrementing: 1.0.0.1
As Tom mentioned in the comments, you should look add the option to start your forms application with a parameter that indicates that the main form should not be shown and some magic should happen. For example, check for a "/s" and let the application run silently if it is present:
MyWinformsApplication.exe /s
Also, as Tom mentioned, a console application can still open a window and this is really useful to have in Jenkins as you can then write insightful messages to the console which will be logged by Jenkins. You can always use these at a later stage to check if something went wrong.
As an additional note - if you add Console.WriteLine() to your WinForms application, Jenkins will pick the string up and add it to the console log.

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"

PowerShell - X509Certificates.X509Store get all certificates?

I want to get all certificates from my system.
So I used the System.Security.Cryptography.X509Certificates class.
When I remove the () after the X509Store I getting the same results like I entered "My"
What is the right membername to see all certificates? It is possible?
MSDN StoreName Enumeration
$store=new-object System.Security.Cryptography.X509Certificates.X509Store("CA")
# Put in CA, My, root etc.
$store.open("ReadOnly")
$store.Certificates
$store.Certificates.count
You can get them from your local cert drive:
Get-ChildItem Cert:\CurrentUser\CA # user certs
Get-ChildItem Cert:\LocalMachine\CA # machine certs
Get-ChildItem Cert:\LocalMachine\My
This is fun if you have WinRM installed but in a much more standard way to find all certificate it is much better to use something like
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("\\$server_name\My","LocalMachine")
$store.Open("ReadOnly")
$store.Certificates
The following PowerShell script will ask for the DNS name of a remote computer, then it asks for Domain Admin credentials so it can connect and query. The resulting $AllCerts var has every certificate from every store. It then also exports them to a CSV file in the $env:temp folder and opens the folder in Windows Explorer.
function Get-Cert( $computer=$env:computername ){
$cred = Get-Credential -Message "Enter credentials for a Domain Admin"
$ro=[System.Security.Cryptography.X509Certificates.OpenFlags]"ReadOnly"
$lm=[System.Security.Cryptography.X509Certificates.StoreLocation]"LocalMachine"
$Stores = (Invoke-Command $computer {Get-ChildItem cert:\LocalMachine} -Credential $cred).Name
$AllStores = #()
foreach ($store in $Stores){
$AllStores += new-object System.Security.Cryptography.X509Certificates.X509Store("\\$computer\$store",$lm)
}
$AllStores.Open($ro)
$AllStores.Certificates
}
write-host "Enter remote computer to poll certificate information from" -ForegroundColor Cyan
$remoteComputer = read-host
$AllCerts = Get-Cert $remoteComputer
$AllCerts = $AllCerts | Select Subject,Issuer,Thumbprint,NotBefore,NotAfter
$AllCerts | Where-Object {$_.NotAfter -lt (Get-Date)} | format-list
$AllCerts | export-csv -NoTypeInformation $env:temp\$($remoteComputer)_AllCerts.csv
start $env:temp
Fantastic Script, I had issue with it naming and could be me easily, but changed this and very happy with the output, thanks!
From:
$AllCerts | export-csv -NoTypeInformation $env:temp\$($remoteComputer)_AllCerts.csv
start $env:temp
To:
$AllCerts | export-csv c:\temp\AllCerts.csv -NoTypeInformation

Categories

Resources