Quantcast
Channel: Windows – Benohead’s Software Blog
Viewing all 24 articles
Browse latest View live

The c# project is targeting “.NET Framework,Version=v4.0″, which is not installed on this machine.

$
0
0

Since I needed some space on my hard disk to install some software I went through the list of installed software and saw that Visual Studio 2010 was installed but I actually only use Visual Studio 2012 (or Visual Studio 2005 for some very old stuff which hasn’t been ported yet). So I thought it makes sense to uninstall Visual Studio 2010. And ended up wasting alot of time…

After uninstalling VS 2010, I started getting the following message in VS2012 whenever I opened a project targeted at the .NET framework v4.0:

The C# project xxx is targeting ‘.NETFramework,Version=v4.0″, which is not installed on this machine. to proceed, you must select an option below.

1.Change the target to .NET Framework 4.5…..

2.Download the targeting pack for “.NET Framework, Version = v4.0″…

3.Do not load the project

When you choose option 2 you are redirected to a web page where you actually cannot download the v4.0 .NET framework. Checking in the registry, I saw that the .NET framework was gone. I also found the installation package for the .NET framework v4.0. Unfortunately, it refuses to install since the v4.5 framework is already installed.

So my next great idea was to uninstall the v4.5 framework. Then I could install the v4.0 version. Of course, after that VS 2012 wouldn’t start anymore. So I installed the v4.5 framework again. During the installation, it told me that it’s an in-place update for the v4.0 framework. I immediately thought that it might cause trouble but didn’t have a choice anyway. After installing the v4.5 framework VS2012 worked again but as expected, I still got the same error message when opening projects targeting the v4.0 framework.

Running out of other options, I finally reinstalled VS2010. It took forever but in the end I was able to open all projects in VS2012.

So this is kind of a waste of space but if you cannot have your project target the v4.5 framework but need to target the v4.0 framework, you will need to have VS2010 installed additionally to VS2012 (even though you actually do not need VS2010).

If anybody has found a solution not requiring VS2010 to stay installed, please leave a comment. My hard disk space is running low and I’d love to be able to get rid of VS2010.

The post The c# project is targeting “.NET Framework,Version=v4.0″, which is not installed on this machine. appeared first on Benohead.


JavaScript: Workaround for Object.defineProperty in IE8

$
0
0

Even though Internet Explorer 8 is now very old and outdated, there are unfortunately still many corporate users who are still stuck with this old browser. Many things are broken in IE8. One of them is the implementation of Object.defineProperty.

I noticed it when using the polyfill for String.startswith you can find on MDN looks. It looks like this:

if (!String.prototype.startsWith) {
  Object.defineProperty(String.prototype, 'startsWith', {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(searchString, position) {
      position = position || 0;
      return this.lastIndexOf(searchString, position) === position;
    }
  });
}

While Object.defineProperty is fully supported in IE9, it’s only partially supported in IE8. Internet Explorer 8 only supports defineProperty for DOM objects. If you use it for anything else, IE will complain that there is nothing like Object.defineProperty.

This is especially bad since calling defineProperty will cause and error which will prevent the rest of your JavaScript code to run.

So what can we do about it ?

The first thing I tried was:

        if (defineProperty){
            Object.defineProperty(String.prototype, 'startsWith', {
                enumerable: false,
                configurable: false,
                writable: false,
                value: function (searchString, position) {
                    position = position || 0;
                    return this.indexOf(searchString, position) === position;
                }
            });
        }

Unfortunately I then got an error in the if. So the easiest way to do this turned out to be to try to execute the defineProperty and ignore exceptions:

if (!String.prototype.startsWith) {
    try{ 
        if (defineProperty){
            Object.defineProperty(String.prototype, 'startsWith', {
                enumerable: false,
                configurable: false,
                writable: false,
                value: function (searchString, position) {
                    position = position || 0;
                    return this.indexOf(searchString, position) === position;
                }
            });
        }
    } catch (e) { };
}

After that, you can check again whether startsWith exists and add this function:

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString, position) {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
    };
}

 

The post JavaScript: Workaround for Object.defineProperty in IE8 appeared first on Benohead.

Powershell: Check whether a file is locked

$
0
0

When opening a StreamReader for a file in powershell, you will get an exception if the file is locked:

The process cannot access the file ‘xxx’ because it is being used by another process.

You can use this to check whether a file is locked. You just need to setup a trap which will say that the file is locked if an exception occurs and then open the file:

trap {
	Write-Output "$filename is locked"
	continue
}
$stream = New-Object system.IO.StreamReader $filename
if ($stream) {$stream.Close()}

Of course, you might also get an exception if the file doesn’t exist, so non-existing files will be reported as locked. So before checking the file, we need to make sure the file exists:

$file = gi (Resolve-Path $filename) -Force
if ($file -is [IO.FileInfo]) {
	trap {
		Write-Output "$filename is locked"
		continue
	}
	$stream = New-Object system.IO.StreamReader $file
	if ($stream) {$stream.Close()}
}

So if the file doesn’t exist, you will get an exception before we define the trap and the trap will only be activated if you cannot open the file. Here’s the output when the file doesn’t exist:

Resolve-Path : Cannot find path ‘D:\Temp\AuditAnalysis\test.xlsx2′ because it does not exist.
At D:\Temp\AuditAnalysis\test_lock.ps1:13 char:25
+ $file = gi (Resolve-Path <<<< $filename) -Force
+ CategoryInfo : ObjectNotFound: (D:\Temp\AuditAnalysis\test.xlsx2:String) [Resolve-Path], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.ResolvePathCommand

Get-Item : Cannot bind argument to parameter ‘Path’ because it is null.
At D:\Temp\AuditAnalysis\test_lock.ps1:13 char:11
+ $file = gi <<<< (Resolve-Path $filename) -Force
+ CategoryInfo : InvalidData: (:) [Get-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetItemCommand

Here’s the full code with parameter handling:

############################################################
#                      Test file lock
#                      by Henri Benoit
############################################################

Param(
    [parameter(Mandatory=$true)]
    $filename
)

Write-Output "Checking lock on file: $filename"

$file = gi (Resolve-Path $filename) -Force
if ($file -is [IO.FileInfo]) {
	trap {
		Write-Output "$filename is locked"
		continue
	}
	$stream = New-Object system.IO.StreamReader $file
	if ($stream) {$stream.Close()}
}
exit

If the file is locked it will display the following:

Checking lock on file: test.xlsx
test.xlsx is locked

If it is not locked, only the first line will be displayed:

Checking lock on file: test.xlsx

If you want to check whether a file is locked within your powershell code, you can define this in a function and instead of writing something to the output, you can use Set-Variable to set a variable to true and return this variable.

If you actually do not care whether the file is locked or not but just want to read the contents of the file no matter what, you could use this to check whether the file is locked and if yes copy the file before reading it.

Of course you might want to also define an additional function checking whether the file exists by trapping the error in Resolve-Path.

The post Powershell: Check whether a file is locked appeared first on Benohead.

Export an App Service certificate to a pfx file with PowerShell

$
0
0

In order to debug a webjob running in an Azure App Service and accesses a service using a certificate, I needed to create a local copy of the certificate to be able to run the webjob on a local machine. The Azure portal unfortunately only provides these options:

  1. Import an existing App service certificate
  2. Upload a certificate
  3. Delete a certificate

So there is no option to download a certificate. But this can be used using PowerShell and the AzureRM module.

First, we’ll need to set a few variables with the data required to get the certificate:

$azureLoginEmailId = "me@benohead.com"
$subscriptionName = "mysubscriptionname"
$resourceGroupName = "myresourcegroupname"
$certificateName = "nameofthecertificateiwanttodownload"
$pfxPassword = "mygreatpassword"

We’ll later use $pfxPassword to set a password in the created PFX file.

Then I need to login into Azure to be able to access the resources:

Login-AzureRmAccount

You will see a popup where you can enter your credentials.

Then you need to select the appropriate subscription:

Select-AzureRmSubscription -SubscriptionName $subscriptionName

Now, we’re ready to access the certificate resource which can be used to get the actual certificate from the key vault:

$certificateResource = Get-AzureRmResource -ResourceName $certificateName -ResourceGroupName $resourceGroupName -ResourceType "Microsoft.Web/certificates" -ApiVersion "2015-08-01"

The returned resource object has next to the location, name, ID, type and resource group name also a Properties member which contains details about the certificate:

  • subjectName
  • hostNames
  • issuer
  • issueDate
  • expirationDate
  • thumbprint
  • keyVaultId
  • keyVaultSecretName
  • keyVaultSecretStatus
  • webSpace

All the pieces of information we need to retrieve the certificate from key vault are encoded in the keyVaultId except the keyVaultSecretName (which is also in the list above):

/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourcegroups/xxxxx/providers/microsoft.keyvault/vaults/xxxxx

So by splitting it to an array using / as a separator, you get resource group name for the key vault in the 5th element from the end and the key vault name in the last element.

So you can extract them like this:

$keyVaultId = $certificateResource.Properties.keyVaultId
$keyVaultData = $keyVaultId.Split("/")
$keyVaultDataLength = $keyVaultData.Length
$keyVaultName = $keyVaultData[$keyVaultDataLength - 1]
$keyVaultResourceGroupName = $keyVaultData[$keyVaultDataLength - 5]

You also get the secret name like this:

$keyVaultSecretName = $certificateResource.Properties.keyVaultSecretName

Now we can grant our user permissions to perform a “get” operation on the key vault:

Set-AzureRmKeyVaultAccessPolicy -ResourceGroupName $keyVaultResourceGroupName -VaultName $keyVaultName -UserPrincipalName $azureLoginEmailId -PermissionsToSecrets get

And you can fetch the secret containing the certificate:

$keyVaultSecret = Get-AzureKeyVaultSecret -VaultName $keyVaultName -Name $keyVaultSecretName

This secret contains a Base64 representation of the certificate which you can convert back to a certificate object using:

$pfxCertObject=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($keyVaultSecret.SecretValueText),"", [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

Now, the only step left is to write the certificate to a local PFX file:

[io.file]::WriteAllBytes(".\appservicecertificate.pfx", $pfxCertObject.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12, $pfxPassword))

And there you are !

If you have found this page, you probably have also seen a couple of MSDN blog entries about a similar topic:

That’s also where I started but since I had to adapt the code from these two blog entries, I decided to document it in this blog post. Hope this helps !

 

The post Export an App Service certificate to a pfx file with PowerShell appeared first on Benohead's Software Blog.

Viewing all 24 articles
Browse latest View live