Viser opslag med etiketten Azure. Vis alle opslag
Viser opslag med etiketten Azure. Vis alle opslag

onsdag den 15. januar 2014

Managing CRM 2011 and 2013

I fixed a series of bugs and tested my CRM powershell module against both 2011 and 2013. Enjoy.

PSCRM.zip

Add-CRMRoleMember
Disable-CrmLanguage
Disable-CrmOrganization
Disable-CRMSystemUser
Enable-CrmLanguage
Enable-CrmOrganization
Enable-CRMSystemUser
Get-CrmAvailableLanguage
Get-CrmLanguage
Get-CrmOrganization
Get-CRMRole
Get-CRMSystemUser
Get-CRMSystemUserSettings
Get-CrmUsermappingFile
Import-CrmOrganization
New-CrmConfig
New-CRMCustomerAdminRole
New-CrmOrganization
New-CRMSystemUser
Remove-CrmOrganization
Remove-CRMRole
Remove-CRMRoleMember
Remove-CRMSystemUser
Select-CrmOrganization
Set-CRMSystemUser
Set-CRMSystemUserSettings

tirsdag den 14. januar 2014

Microsoft Dynamics Nav 2013 goodies

One of the cool things about Nav 2013 is the ClickOnce deployment. Running Nav in a multi Tenant depoyment with many customers can make this a bit of a headache. First of all you need several deployments, one for each customer (seems stupid when all you need is a different ClientUserSettings.config ( maybe we could create a iis module or something to handle this ? ) anyway, for now lets keep it like that. Next if you read this page they promise us gold in the form of having several installations at the same computer. That will not work following microsofts guide thou, you need to have different assemblyIdentity names for that to work. Thank god we have powershell …

 

$baseclientpath = 'C:\NAV2013R2\Install\RoleTailoredClient\program files\Microsoft Dynamics NAV\71\RoleTailored Client\'
$baseclientcommonpath = 'C:\NAV2013R2\Install\RoleTailoredClient\CommonAppData\Microsoft\Microsoft Dynamics NAV\71\'
$templatepath = 'C:\NAV2013R2\Install\ClickOnceInstallerTools\Program Files\Microsoft Dynamics NAV\71\ClickOnce Installer Tools\TemplateFiles\'
$clickoneroot = "C:\inetpub\wwwroot\ClickOnce\$tenantid\"
$clickoneDeployment = "$($clickoneroot)Deployment\"
$clickoneApp = "$($clickoneroot)Deployment\ApplicationFiles\"

#if ( (Test-Path $clickoneroot) -ne $true) {
Copy-Item $templatepath $clickoneroot -recurse -force

if ( (Test-Path "$($clickoneroot)default.html") -ne $true) {
Copy-Item "$($clickoneroot)NAVClientInstallation.html" "$($clickoneroot)default.html"
}

Write-Host "Remove Nav ClickOnce Client Application"
if ( (Test-Path $clickoneApp) -eq $true) { Remove-Item $clickoneApp -force -recurse }
Write-Host "Copy fresh Nav ClickOnce Client Application"
Copy-Item $baseclientpath $clickoneApp -recurse -force

Write-Host "Copy fresh templates"
Copy-Item "$($templatepath)Deployment\ApplicationFiles\Microsoft.Dynamics.Nav.Client.exe.manifest" $clickoneApp
Copy-Item "$($templatepath)Deployment\ApplicationFiles\Icon.ico" $clickoneApp
Copy-Item "$($templatepath)Deployment\Microsoft.Dynamics.Nav.Client.application" $clickoneDeployment
Copy-Item "$($baseclientcommonpath)ClientUserSettings.config" $clickoneApp


Write-Host "Remove OpenXml and ReportLayout"
Remove-Item "$($clickoneApp)Add-ins\OpenXml" -recurse -force
Remove-Item "$($clickoneApp)ReportLayout" -recurse -force
Remove-Item "$($clickoneApp)Finhlink.exe" -force
Remove-Item "$($clickoneApp)finsql.exe" -force
Remove-Item "$($clickoneApp)finsql.exe.config" -force

Write-Host "Update ClientUserSettings"
$xml = [xml](Get-Content "$($clickoneApp)ClientUserSettings.config")
($xml.configuration.appSettings.add | ?{$_.key -eq 'Server'}).value = $alternateId
($xml.configuration.appSettings.add | ?{$_.key -eq 'ClientServicesPort'}).value = $ClientServicesPort.ToString()
($xml.configuration.appSettings.add | ?{$_.key -eq 'ServerInstance'}).value = $navinstancename
($xml.configuration.appSettings.add | ?{$_.key -eq 'TenantId'}).value = $tenantid
($xml.configuration.appSettings.add | ?{$_.key -eq 'ClientServicesCredentialType'}).value = 'UserName'
($xml.configuration.appSettings.add | ?{$_.key -eq 'DnsIdentity'}).value = $navcertificatesubject
($xml.configuration.appSettings.add | ?{$_.key -eq 'HelpServer'}).value = $helpserver
($xml.configuration.appSettings.add | ?{$_.key -eq 'HelpServerPort'}).value = $helpserverport
($xml.configuration.appSettings.add | ?{$_.key -eq 'ProductName'}).value = $tenantproductname
$xml.Save("$($clickoneApp)ClientUserSettings.config")

$manifestfile = "$($clickoneApp)Microsoft.Dynamics.Nav.Client.exe.manifest"
$applicationfile = "$($clickoneDeployment)Microsoft.Dynamics.Nav.Client.application"
$baseclickoneurl = "https://$alternateId/ClickOnce/$tenantid"
$manifesturl = "$($baseclickoneurl)/Deployment/ApplicationFiles/Microsoft.Dynamics.Nav.Client.exe.manifest"
$codebaseurl = "$($baseclickoneurl)/Deployment/Microsoft.Dynamics.Nav.Client.application"

Write-Host "Update manifest file"
$xml = [xml](Get-Content $manifestfile)
$xml.assembly.assemblyIdentity.name = "Microsoft.Dynamics.Nav.$tenantid" # Microsoft.Dynamics.Nav.ClickOnceClient
$xml.assembly.assemblyIdentity.version = $clientversion
$xml.Save($manifestfile)

Write-Host "Update application file"
$xml = [xml](Get-Content $applicationfile)
$xml.assembly.description.publisher = 'Microsoft Corporation and Proinfo A/S'
$xml.assembly.description.product = $tenantproductname
$xml.assembly.assemblyIdentity.name = $tenantproductname
$xml.assembly.deployment.deploymentProvider.codebase = $codebaseurl
$xml.assembly.assemblyIdentity.version = $clientversion
$xml.assembly.dependency.dependentAssembly.assemblyIdentity.name = "Microsoft.Dynamics.Nav.$tenantid"
$xml.Save($applicationfile)


& C:\NAV2013R2\mage\mage.exe -Update $manifestfile -FromDirectory $clickoneApp

& C:\NAV2013R2\mage\mage.exe -update $applicationfile -appmanifest $manifestfile -appcodebase $manifesturl
Write-Host "Microsoft Dynamics Nav 2013 for $tenantid published at https://$alternateId/ClickOnce/$tenantid"
#}

mandag den 25. februar 2013

ASP.NET and/or MVC websites and Claims based Authentication

Implementing WIF on a website is pretty straight forward. There are ton’s of guide out there on how to do it …. By doing a bit of magic in web.config you can make any website support claims based authentication. ( even Exchange 2010 and Citrix  )

If you are a developer, implementing WIF on your website is just as easy. You install WIF SDK and run FedUtil.exe who will handle configuring your web.config for you …

But what if you want absolute control over the login process. You often end up, with a mix of stuff in web.config and some in code. So I decided to figure out, what it would take, to support getting a user signed on, without ever touching web.config.

You will need to handle 4 actions. Requesting login, Handle login, Handle sign-out and handling Cleanup. So lets start with requesting login. But before we can do that, we need to have a basic setup of WIF. WIF normally do most of it’s magic though 3-4 modules, that get’s its configuration though web.config, and is saved in a static (shared) variable you can access simply by typing

Dim fam As Microsoft.IdentityModel.Web.WSFederationAuthenticationModule = Microsoft.IdentityModel.Web.FederatedAuthentication.WSFederationAuthenticationModule

But we want to control. To make things simple, we function like this

Public Function GetAuthenticationModule() As WSFederationAuthenticationModule
Dim fam As New WSFederationAuthenticationModule
fam.ServiceConfiguration = New Microsoft.IdentityModel.Configuration.ServiceConfiguration()
' use this, to allow any realm
' fam.ServiceConfiguration.AudienceRestriction.AudienceMode = IdentityModel.Selectors.AudienceUriMode.Never
' Add known Audience's ( Realms )
' This would proberly come from a database or what ever
For Each Realm in my.settings.Realms
Dim AllowedUri = fam.ServiceConfiguration.AudienceRestriction.AllowedAudienceUris.Where(Function(x) x.AbsoluteUri = IDP.TargetRealm).FirstOrDefault()
If AllowedUri Is Nothing Then
fam.ServiceConfiguration.AudienceRestriction.AllowedAudienceUris.Add(New Uri(IDP.TargetRealm))
End If
Next
fam.ServiceConfiguration.IssuerNameRegistry = New CustomTrustedIssuerNameRegistry()

Dim certificate As System.Security.Cryptography.X509Certificates.X509Certificate2 = CustomSecurityTokenServiceConfiguration.Current.EncryptingCertificate
AttachCert(fam.ServiceConfiguration, certificate)
' If you later decide to let WIF set the identity and save a FedAuth cookie, use thise to allow it to work incase you got
' your website hosted in Azure. The reason is Azure's Loadbalencing are using true round robin and doesnt support Sticky sessions.
' So in order to make all websites able to read the cookie, you need to a "common" ground for reading the encrypted token
'Dim sessionTransforms As New List(Of CookieTransform)(New CookieTransform() {New DeflateCookieTransform(), New RsaEncryptionCookieTransform(certificate),
' New RsaSignatureCookieTransform(certificate)})
'Dim sessionHandler As New Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler(sessionTransforms.AsReadOnly())
'fam.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler)
Return fam
End Function

Private Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
Sub AttachCert(configuration As Microsoft.IdentityModel.Configuration.ServiceConfiguration, certificate As System.Security.Cryptography.X509Certificates.X509Certificate2)
configuration.ServiceCertificate = certificate
Dim certificates = New List(Of System.IdentityModel.Tokens.SecurityToken)() From { _
New System.IdentityModel.Tokens.X509SecurityToken(Configuration.ServiceCertificate) _
}
Dim encryptedSecurityTokenHandler = TryCast((From handler In Configuration.SecurityTokenHandlers Where TypeOf handler Is Microsoft.IdentityModel.Tokens.EncryptedSecurityTokenHandler).First(), Microsoft.IdentityModel.Tokens.EncryptedSecurityTokenHandler)
configuration.ServiceTokenResolver = InlineAssignHelper(encryptedSecurityTokenHandler.Configuration.ServiceTokenResolver, System.IdentityModel.Selectors.SecurityTokenResolver.CreateDefaultSecurityTokenResolver(certificates.AsReadOnly(), False))
End Sub

We need to tell WIF the realm(s) we are running under right now, called Audience Uri.
We need to tell WIF what signing certificate's to allow tokens from, called Issuer Name Registry.
CustomTrustedIssuerNameRegistry is a class that will get “fed” the signing certificates when WIF is validating the tokens, and should return a name (any name) if the certificate was allowed. Code for that is further down


Perfect, so now we are ready to create a sign request ( what happens when a user clicks the “login” button or what ever)

Public Function CreateSignInRequestMessage(Issuer As String, Realm As String, Reply As String) As SignInRequestMessage
Dim fam = GetAuthenticationModule()
fam.Issuer = Issuer
fam.Realm = Realm
Dim signInRequest = New SignInRequestMessage(New Uri(fam.Issuer), fam.Realm) With { _
.AuthenticationType = fam.AuthenticationType, _
.Freshness = fam.Freshness, .Reply = Reply
}
Return signInRequest
End Function

So in the code for your “login button” you do something down the line of this


Dim STSLoginPage as string = "https://adfs.wingu.dk/adfs/ls/"
' This webpage, must be in the AllowedAudienceUris
Dim TargetRealm as string = "https://domain.com/MyAwsomeWebapp"
Dim returnURL as string = "https://domain.com/MyAwsomeWebapp/login.aspx"
' or if using MVC
Dim returnURL as string = "https://domain.com/MyAwsomeWebapp/login/signin/"

Dim signInRequest = WIFHelper.CreateSignInRequestMessage(STSLoginPage, TargetRealm, returnURL)
Dim redirURL As String = signInRequest.WriteQueryString()
Response.Redirect(redirURL)

That will kick the user over to the identity provider, and if all goes well, he will then return with a POST to the return URL, where we can now pickup he’s SAML token.
So on the login page (or MVC controller) its now time to read the token, we add a function to our module, than handles that part


Private Function GetSignInResponseMessage() As SignInResponseMessage
Dim ctx = System.Web.HttpContext.Current
Dim req = ctx.Request
Dim message As SignInResponseMessage = WSFederationMessage.CreateFromFormPost(req) 'as SignInResponseMessage
Return message
End Function

Public Function GetWIFPrincipal(ByRef Issuer As String) As Microsoft.IdentityModel.Claims.ClaimsPrincipal 'System.Security.Principal.IPrincipal
Dim fam = GetAuthenticationModule()
Dim message As SignInResponseMessage = GetSignInResponseMessage()
'Dim token As System.IdentityModel.Tokens.SamlSecurityToken = fam.GetSecurityToken(message)
Dim token = fam.GetSecurityToken(message)
If token IsNot Nothing Then
Dim claims As Microsoft.IdentityModel.Claims.ClaimsIdentityCollection = fam.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(token)
Dim principal As System.Security.Principal.IPrincipal = New Microsoft.IdentityModel.Claims.ClaimsPrincipal(claims)
If TypeOf token Is System.IdentityModel.Tokens.SamlSecurityToken Then
Dim t As System.IdentityModel.Tokens.SamlSecurityToken = token
Issuer = t.Assertion.Issuer
ElseIf TypeOf token Is Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken Then
Dim t As Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken = token
Issuer = t.Assertion.Issuer.Value
Else
Throw New Exception("Failed resolving SecurityToken to a known type '" & token.GetType.Name & "'")
End If
Return principal
End If
Return Nothing
End Function

And in the login page/controller you, can now either set the current principal, or parse the claims and sign in the user with formsbased authentication or what ever makes you tick.

Dim Issuer As String = Nothing
Dim Principal As Microsoft.IdentityModel.Claims.ClaimsPrincipal = GetWIFPrincipal(Issuer)
If Principal Is Nothing Then Throw New Exception("Failed parsing sign message to new Principal")
Dim Identity As Microsoft.IdentityModel.Claims.ClaimsIdentity = Principal.Identity
If Identity Is Nothing Then Throw New Exception("Failed parsing sign message to new Principal")
Issuer = Issuer.ToLower

Lastly, to make everything work correctly, we need to make our “login” page support at least 3 of the WS-Federation commands ( I guess that makes “login” page a wrong name then ? ) . So to wrap it all up, you will get something like this

Dim action as string = Request.QueryString(WSFederationConstants.Parameters.Action)
Select Case action
Case WSFederationConstants.Actions.SignIn
' Send user to the identity provider
Dim STSLoginPage As String = "https://adfs.wingu.dk/adfs/ls/"
' This webpage, must be in the AllowedAudienceUris
Dim TargetRealm As String = "https://domain.com/MyAwsomeWebapp"
Dim returnURL As String = "https://domain.com/MyAwsomeWebapp/login.aspx"
' or if using MVC
returnURL = "https://domain.com/MyAwsomeWebapp/login/signin/"
Case WSFederationConstants.Actions.SignOut
Dim requestMessage As SignOutRequestMessage = Nothing
Try
' This will fail, if a "sharepoint" login message
requestMessage = WSFederationMessage.CreateFromUri(Request.Url)
Catch ex As Exception
' ignore
End Try
' Return user to front page
model.RedirectURL = Request.Url.Scheme & "://" & Request.Url.Host & Request.ApplicationPath
If Not requestMessage Is Nothing Then
If Not String.IsNullOrEmpty(requestMessage.Reply) Then
' unless they logged out from another site, then send them back there
model.RedirectURL = requestMessage.Reply
End If
End If
FormsAuthentication.SignOut()
Session.Abandon()

' clear authentication cookie
Dim cookie1 As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, "")
cookie1.Expires = DateTime.Now.AddYears(-1)
Response.Cookies.Add(cookie1)

' clear session cookie
Dim cookie2 As HttpCookie = New HttpCookie("ASP.NET_SessionId", "")
cookie2.Expires = DateTime.Now.AddYears(-1)
Response.Cookies.Add(cookie2)
Case WSFederationConstants.Actions.SignOutCleanup
' Do the same as above, but send an "ok" image back
End Select
And lastly, we need to create class that validates singing certificates. 
Imports Microsoft.IdentityModel.Tokens
Imports System.IdentityModel.Tokens

Public Class CustomTrustedIssuerNameRegistry
Inherits IssuerNameRegistry
'Inherits Microsoft.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry

Public Sub New()
End Sub
'Public Sub New(customConfiguration As System.Xml.XmlNodeList)
' MyBase.New(customConfiguration)
'End Sub

Public Overrides Function GetWindowsIssuerName() As String
Return MyBase.GetWindowsIssuerName()
End Function

Public Overloads Overrides Function GetIssuerName(securityToken As IdentityModel.Tokens.SecurityToken) As String
Dim x509Token As X509SecurityToken = TryCast(securityToken, X509SecurityToken)
If x509Token IsNot Nothing Then

For Each Thumbprint in My.Settings.AllowedSigningThumbprints
If [String].Equals(x509Token.Certificate.Thumbprint, Thumbprint) Then
Return x509Token.Certificate.SubjectName.Name
End If
Next
End If
Throw New SecurityTokenException("Untrusted issuer.")
End Function

End Class

lørdag den 23. februar 2013

SharePoint/CRM/Exchange and other Claims based websites with Social Sign in

The last week I have been working on a project, regarding combining Claims based authentication and login using Social Providers. In the cloud control panel that I normal work on, I have implemented support for signing in using Office 365, Azure AD, pass-through using Azure ACS, and the mandatory Open ID, Google ID, Windows Live ID, LinkedIn, Facebook, and Twitter. But for reasons I don’t want go into, a need came up, to create a simple STS (Secure Token Service), than would “tie” together one or more identities from social network, and offer those to websites and applications supporting WIF/Claims based authentication.

Why a new STS
If you implemented Social Network, either directly, or indirectly though ACS you probably noticed that if a user sign in using Google ID they will not be the same user, if they later decide to sign in using Facebook. That is relatively easy to “handle” if you wrote the application your self, and Microsoft did a decent job, tying it all up, using the membership provider together with DotNetOpenAuth in MVC 4, but if you don’t want to mess with wrapping up your own customer member ship provider, or if your facilitating WIF in Exchange/CRM/SharePoint/Navision or what ever, wouldn’t it just be awesome if you could just get it all “out of the box” some where. And what if that Service would also allow you to setup your own Identity Providers, so you could implement sign in using Office 365/Azure AD, your own ADFS server, or any other Secure Token Service you might have. You can now

The basic setup
We are still figuring out license models and such, but for now were thinking either a hosted solution, and one where you get the website to run for your self, lets image a hosted setup, and after that you get billed a small amount for each 100k users or something like that. So let’s imaging you want to implement this with Microsoft CRM 2011.

  • First signup for an account, you then get access to a Manage menu. But before you go there, head to CRM and start the “Configure Claims-Based Authentication” wizard
    image
    Type in the URL of the Secure Token Service
    image
    Select a certificate to use, when signing the Claims inside the tokens (this certificate needs to exists on all your CRM servers if you got more than one. It can be a self signed, from your internal CA, or one you bought from a third party
    image
    Go though the rest. Go though the “Configure Internet-Facing Deployment” if you haven't don’t so already, and at the end note the URL to the CRM servers metadata.xml file
  • Go to the STS, click Relays, past in the URL from the “Create new relying part” field, and press Create. By default all Social connectors will be allowed, but if you only want for instance Live ID, select that under Identity Providers, and hit Save.

And that is that. SharePoint how ever doesn’t have these cool metadata.xml files, so configuring that, will take a tiny bit more work, but not to worry, that is why we got PowerShell.

  • Open a PowerShell prompt locally on any of the servers in your farm. And run the following PowerShell Script . ( there is a link on the Relaying Party page too ) Make sure you modify the variables at the top to fit your installation
  • Head to the STS, click management, type a meaningful name into “Create new relying part” field, and press Create
    If you went with the defaults in the script, SharePoint should be sending a reply URL, so we can leave PassiveRequestorURI blank.
    SharePoint (default) doesn’t want the claims to be encrypted so we don’t need to add a certificate.
    Under “Audience Uris” add each of the URN’s that was mapped for each of the websites, show in the end of the script.

And you are all done.

Adding Azure AD, office 365, Azure ACS or an ADFS server
That’s all nice, but what about all your local users, or all your Office 365 users ?
Not a problem, head to the “Providers” page, and type in the URL to the metadata file.

If you are using Office 365 or Azure AD the URL will look something like this
https://accounts.accesscontrol.windows.net/<tenant>.onmicrosoft.com/FederationMetadata/2007-06/FederationMetadata.xml

If your using Microsoft ACS, your URL will look something like this
https://<yourname>.accesscontrol.windows.net/FederationMetadata/2007-06/FederationMetadata.xml
(note, someone at Microsoft fucked this up, so it doesn’t sent a Signing Certificate, but it does doing Office 365 … it’s the same certificate thou, so is easy to grab )

If your using ADFS, the URL will look something like
https://adfs.wingu.dk/FederationMetadata/2007-06/federationmetadata.xml

If your using ACS or ADFS, you don’t need to do anything else than going to the ADFS Server/Azure ACS/Azure AD website and add https://STS/FederationMetadata.xml and it will all configure it self. If how ever your using Office 365, you need to add a ServicePrincipal representing the STS. At the top of the Provider screen is a link to a powershell scrip that will set this up. Once the script is run, past in the “spn:<guid>” from the output of the script into the Target Realm field of the new Provider.

Lastly, go back to your Relying Party, and you can now also select your new Office 365 or what ever Provider you added, and let your users sign in using that

onsdag den 6. februar 2013

Requesting email when using Windows LiveID OAuth2

didn’t take long to figure out, but just in case. If you are using DotNetOpenAuth and are using the ApplicationBlock.WindowsLiveGraph to get the identity of the user, you will not get the email address of the user. You can how ever request it, by sending wl.emails in the Scope:

Dim WindowsLiveIDTokenManager As New SQLTokenManager(WindowsLiveIDConsumerKey, WindowsLiveIDConsumerSecret)
Dim WindowsLiveClient As New DotNetOpenAuth.ApplicationBlock.WindowsLiveClient() With { _
    .ClientIdentifier = WindowsLiveIDConsumerKey, _
    .ClientSecret = WindowsLiveIDConsumerSecret _
}
Dim authUrl = New Uri(Request.Url.Scheme + "://" + Request.Url.Authority + "/sts2/login.aspx")
WindowsLiveClient.RequestUserAuthorization(scope:=New String() {ApplicationBlock.WindowsLiveClient.Scopes.Basic, "wl.emails"}, returnTo:=authUrl)

Next, when validating the access token, don’t use the built in JSON Deserialize function, but use your own

 

If authorization IsNot Nothing Then
    Dim request = System.Net.WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken))
    Using response = request.GetResponse()
        Dim JSON As String = ""
        Using responseStream = response.GetResponseStream()
            Dim reader As New IO.StreamReader(responseStream, Encoding.UTF8)
            JSON = reader.ReadToEnd()
        End Using

        Dim jss As New Script.Serialization.JavaScriptSerializer
        Dim LiveIDUser As LiveIDGraph = jss.Deserialize(JSON, GetType(LiveIDGraph))    End Using
End If

 

And this is how your LiveIDGraph would look like

Imports System.Runtime.Serialization

<DataContract(Namespace:="")>
Public Class LiveIDGraph

    <DataMember> Public id As String
    <DataMember> Public name As String
    <DataMember> Public first_name As String
    <DataMember> Public last_name As String
    <DataMember> Public link As String
    <DataMember> Public gender As String
    <DataMember> Public emails As LiveIDEmails
    <DataMember> Public locale As String
    <DataMember> Public updated_time As DateTime

End Class

<DataContract(Namespace:="")>
Public Class LiveIDEmails
    <DataMember> Public preferred As String
    <DataMember> Public account As String
    <DataMember> Public personal As String
    <DataMember> Public business As String
End Class

tirsdag den 5. februar 2013

Fully automated deployment of SharePoint farms in Microsoft Azure

There a plenty of blogs out there about scripting SharePoint, so I wont fill up more space about all the troubles and joys regarding that. I will how ever point you in the direction of AutoSpInstaller who have an awesome script for slip streaming SharePoint installations and better yet. Automating the deployment of SharePoint 2010 and 2013.

I’ve seen a few blog post about installing SharePoint in Microsoft Azure, and I wanted to add my two cent about that. I just finished up doing a Proof of Concept showing a FULLY automated installation of multiple both single and multiple server, SharePoint farm, inside Microsoft Azure. This is how I did it.

I’m developing a Provisioning Engine that supports running in many sites and distribute servers and services across these sites seamlessly. I order to start facilitating Azure we need a subscription and some Persistent VMs deployed inside that subscription. I originally wanted to do everything “offsite” from each subscription, so a new customer could start from scratch, but after a while it became clear I needed some more granulated control doing deployment and needed to deploy my provisioning engine inside the subscription. Microsoft does not have an API for creating subscriptions (that I know off) so we manually sign up for a new Azure Subscription. Next we sign up for a Trial Account in our Provisioning Site. Create a certificate and upload it to Azure and Add Subscription ID and certificate to my Provisioning API in order to make the provisioning engine able to facilitate Azure for that subscription.

We do that by adding a Provisioning Site,

image

Next, we need to make sure all servers can see each other. We can install everything on one server. We can add all servers to the same Azure Hosted Service. We can “link” different roles to a Azure Hosted Service (I have not tested this) or we can create a Virtual Network. The latter is most appealing, so we add a Workspace

image

( at the time of writing, I have not automated the creating of the Virtual Network inside Azure, so we need to add it manually inside Azure and fill out the values in the Workspace plan )

image

Once this is done, manually Add a server to Azure, and deploy our provisioning engine. (this could later be a custom image, or pushed from another site, but for proof of concept, doing this manually  is ok). We link the server to the provisioning site, so the new server have access to all services, and we are now ready to automated everything else.

Next we add an Microsoft SQL server. This can also be done while adding the SharePoint Farm
image

Let customize the SharePoint installation so we control Server names etc. Create a Hosted Service for our new SharePoint Farm

image

image

Next add 1 or more servers depending on how big you want the farm to be

image

Make sure to update relation to point to your new Azure Hosted Service if you got more than one. Lastly we need to add a SharePoint farm on top of the Hosted Service.
image
Fill out desired SMTP/Email settings if needed, and hit deploy. This will automatically add a new Hosted Service and add an SQL Server inside that Service. It will add a Plan for each of the (up to) 22 (default is 16) databases  needed to run the farm, once all have been setup it will deploy SharePoint to each of the servers you added in the above steps, it will create a new Farm, a default SharePoint site and My Site. Configure most of the normal features of a SharePoint farm ( but any features supported by AutoSpInstaller is supported here too)

So what happens behind the scene? Well, AutoSpInstaller supports deploying SharePoint remotely on one or more servers, but it uses PS Exec from PS Tools to do it. ( if you look in the PowerShell scripts it looks like the author also tried making it work using WSMan ( invoke-computer / new-pssession )) but a new blank server doesn’t allow connect with either, so we need a way to get in contact with the server in the first place. If you deploy the standard Windows 2003 image, it allows you to talk with it, using WMI but not WSMan, so you could fire off a WMI command to run the command to configure WSMan ( winrm quickconfig ) but if you deploy a Windows 2012 server, your just out of luck, neither WMI or WSMan will work. You can how ever, tell Windows Azure to automatically join new servers to a domain, and when we are talking about SharePoint you need the servers to be domain joined. Once a Windows server 2012 is part of a domain, you can connect using WSMan and execute PowerShell on the machine (but not WMI, hence PS Exec will not work )

Sure, you could just fire up all servers to be part of a domain, create a group policy to configure the firewall (and maybe there is a Policy for doing something like a winrm quickconfig  too?) but I wanted something generic. Granted, I never figured out a way to “cheat” a fresh Windows 2012 that is not a domain member, I guess I will need to create a custom Image for those later, but for now, having them domain joined was good enough.

On all servers I deploy, I automatically I push out a small windows service. It handles certificates, joining/disjoining domains, installing software, remote management and is also used on Remote Desktop and Citrix XenApp servers to manage user sessions. Its perfect for handling the SharePoint installation and with above I can now push out this service though WMI and/or WSMan and kick of the installation. So the service handles installing an SQL server. well tested and Known technology and easy to automate, next we can now kick off the SharePoint installation.

AutoSpInstaller uses Start-Transcript doing installation, and I haven't figured out how to “support” that in a custom hosted PowerShell host, so first I had to strip that out. Next it does an insane amount of “am waiting lets do a write a “.” dot each second” thing, and is annoying as hell in the console logs, so had to strip those out too. Lastly you need patience … A LOT of it … So now when looking at the Provisioning Request Log is more clean.

imageimage

For some reason the first server you install, that will also handle setting up the farm, and configuring services, will take from 2½ to 4 hours depending on the amount of services you choose. The following servers can take up to 30 minutes to install binaries, and 20 to 40 minutes joining the farm and configuring services. Not sure why really (both CPU/memory and Disk queue length is way below any warning signs on all servers doing the installation)

Once AutoSpInstaller is done, its easy and well documented how to connect to one of the servers and configuring new SharePoint sites/Site Collections and adding/removing users and groups, as part of my provisioning engine.

When using AutoSpInstaller it worth taking 2 minute extra reading the comments in the AutoSPInstallerInput.xml file. Stuff like how database prefix's, limits on characters' in password, or knowing that what worked on your “single” server install will not work in farms ( using the default http://localhost as WebApp name’s or not limiting the QueryServer to a single server will take a lot longer to troubleshoot that just reading the damn documentation Winking smile )

tirsdag den 13. november 2012

Azure PowerShell – Now with Provider Support

I got a little feedback on my PowerShell module WA, and have updated it to reflect some of those things. First of all, subscription handling was weird, so created the prober commands for that ( New-Subscription, Set-Subscription, Remove-Subscription, Get-Subscription, Select-Subscription ) . I also made some optimizing on Table/Row CmdLets, so should handle tables with many rows better. But the most important thing is I implemented a PowerShell Provider ( still working a a few tweaks here and there, but ill keep updating the binaries when needed )

First of all. I started creating the Provider in hopes of making copying files between your local file system and Azure more smooth and intuitive. After I had almost finished most of the work and was ready to start working on that part, I found out that Microsoft does not support cross provider copying. That sucks, but I had already started the work and it still works “cross” container/Storage account wise, and with my new parameters it also works with local file system (with a twist).

When you load the PowerShell module, you will now have access to a azure: drive. The root will contain a list of your subscriptions (and you can create/update/remove with new-item/set-item/remove-item) each representing a folder. If you go down on one of those you will get a list of Storage Accounts associated with that subscription. Again you can Create/Remove storage accounts to that subscription with New-Item/Remove-Item. You can also copy all content from one Storage Account to another with Copy-Item (Move-Item to work soon. Snapshots are not part of the copy, but can be handled individually )

image

All levels work with <tab> tabulator auto completion, to make it fast and smooth navigating around. If you jump down to a storage account and do a dir or Get-ChildItem you will get a list of BlobContainers and Table’s (queues will be added later). You can create new containers and tables with New-Item (default is containers)

image

But enough of that. Remember my long script to copy a storage account in part one ? This is how you can do that now

Copy-Item azure:\Pay-As-You-Go\wingu2 azure:\skadefro\copytest

Works with containers and single blobs too. So what about local files ?
New-Item is for uploading files. Get-Item / Get-ChildItem (or just dir) is for downloading file. Eksamples

# Upload a single file
New-Item -filename C:\temp\1.jpeg azure:\skadefro\copytest\ad01\1.jpeg
# Since we know the file name, you can also just specefy container
New-Item -filename C:\temp\1.jpeg azure:\skadefro\copytest\ad01
# Hell, if you allready are in the folder just use .
cd azure:\skadefro\copytest\ad01
New-Item -filename C:\temp\1.jpeg .

# want to upload a whole folder ?
New-Item -filename C:\temp azure:\skadefro\copytest\ad01
# or
cd azure:\skadefro\copytest\ad01
New-Item -filename C:\temp .
# What about all subfolders in that folder ?
# sure, this will also create the "folder" in azure
cd azure:\skadefro\copytest\ad01
New-Item -Recursive -filename C:\temp .

# want to upload a single file to a folder ?
# Since powershell keep messing with the folder paths, we need to use
# forwariding slash for folders.
New-Item -filename C:\temp\1.jpeg azure:\skadefro\copytest\ad01\test/1.jpeg
# or

# same goes the other way
# download a file
Get-Item -filename c:\temp\1.jpeg azure:\skadefro\copytest\ad01\1.jpeg
# or, since we allready know the file name,
Get-Item -filename c:\temp\ azure:\skadefro\copytest\ad01\1.jpeg

# Download all the files from the container
# this will create the folder structure localy also, if names contains /
Get-Item -filename c:\temp azure:\skadefro\copytest\ad01
# or the short version
cd azure:\skadefro\copytest\ad01
Get-Item -filename c:\temp .

# I know, Get-ChildItem is suppose to do that, but that works too
Get-ChildItem -filename c:\temp azure:\skadefro\copytest\ad01
# or
cd azure:\skadefro\copytest\ad01
Get-ChildItem -filename c:\temp .

# or the cool and lazy way,
dir azure:\skadefro\copytest\ad01 -filename c:\temp

So download a copy, test it out and feel free to give me some feedback

torsdag den 8. november 2012

Azure PowerShell–The missing links

I attended Campus Days again this year, and doing one of the sessions one of the presenters told everyone you need to buy 3rd party products to take snapshots or copy Storage Blobs from one container/account to another. That doesn’t seem fair. I needed this functionality and have created a PowerShell module that can do all that, and a lot more, so I decided to share that, with the world.

I think its important to understand the reason I wrote this before I get flamed with comments and emails. When I began playing around with azure, doing a proof of concept setup together with a guy from Microsoft Denmark, I started creating a PowerShell module to manage it, but quickly came across a module that someone else had written than already did most of what I needed, so abandoned the project again. Several months later, when I was asked to start doing some more work with Azure, especially Persistent VM’s I found that Microsoft had adopted the PowerShell module that I had once used, and in that process removed several key features that I needed (but was once there) I also noticed the module was painfully slow to work with when handling Persistent VM’s, so I started writing my own. Half way though that process I got bored with it, and started mixing Microsoft's PowerShell with my own, just focusing on the things they miss. So you will find a lot of useful stuff, and some redundant stuff. In a real scenario you would probably end up using both (for instance, I've only written half of the code to create new VM’s, and that sure is is an important command, right ? ;-) )

Download the module and extract it somewhere, like c:\wa  Open PowerShell and load the module with

# If you just downloaded it, unblock files
Unblock-File C:\wa\Release\*
import-module C:\WA\Release\wa.psd1

First of all, I hate the way Microsoft handles working with different Subscriptions. (granted some of mine ended up working the same way in the end, but still ). So you load the module and connect to one of your subscriptions with

# Find your Management Certificate, or create one and upload it to azure
dir cert:\CurrentUser\my

# Tell WA module about the subscription and cert and give it a name
Select-Subscription -Name Pay-As-You-Go -SubscriptionId 1f6b36b5-d2ab-49e6-8674-2155a3ea4a55 -CertificateThumbprint AAF4E3017B3DE26E93601E1573FDAF44A3AA15E8

The module loads certificates from localmachine and localuser store, but most will have it in the user\my store. Name can be what ever makes sense to you, I normally use the name Azure also used within the management portal. This gets saved in HKLU\software\wa Registry and from now on, every time you start a new PowerShell prompt you can just use

Select-Subscription -Name Pay-As-You-Go 
# or list all, known subscription with
Get-Subscription
# This will also query azure about statistics data, so you can see if your about to hit your Core, HostedService or Storage Account limits.

If you only want to manage an storage account, you can ignore the above and connect directly to it, using

Select-StorageAccount -AccountName skadefro -AccountKey blahBlagBlah1234==

But if you loaded an subscription, you can let the module handle all that for you and just use the Storage account’s Service Name.

Select-StorageAccount -ServiceName Skadefro

Ok, So what can you do, that Microsoft’s version is missing. Well, managing Storage/Blob/Queue’s was the first show stopper for me, so now you can Create/modify/delete tables, select, insert, modify,delete rows from tables. You can add/update/remove blob containers, update ACL on containers and blobs. Add/Upload/download/snapshot/signature/lease/unlock/remove/copy blobs, both as Page and Block blobs. ( uploading is insanely fast with Page blob, and if you really want to tweak your VM’s, making sure page size fits the size you format your disks with makes a huge difference. )


The reason I’m sharing all this, is several people asked about snapshot’s and copying content from one storage account to another ( hell, even my favorite azure application Azure Explore, doesn’t support copying blobs from one container to another ) ill give a few examples of that.


First, snapshots. very simple

$storageacountname = 'wingu2'
$containername = 'public'
$filename = 'test.txt'
# select an StorageAccount if you got more than one.
# if you only have 1, that will always be selected
Select-StorageAccount -ServiceName wingu2
# Lets upload a text file
# we should place that in a container
$container = Get-Container $containername
if(!$container) { $container = New-Container $containername }
# Lets make it public, so we can show cross subscription/account
# copying later
if( (Get-ContainerACL $containername) -ne 'container'){ Set-ContainerACL $containername container }

# Create a test file, and upload it
if ( (Test-Path $filename) -eq $true) { Remove-Item $filename -confirm:$false }
$file = New-Item -ItemType file $filename
add-content $file '1. Hello world'
New-Blob $containername $filename
$blob = Get-Blob $containername $filename

#Now, lets take a snapshot
$snapshot = $blob | New-Snapshot

#Lets update the file
add-content $file '2. Hello world'
New-Blob $containername $filename

# This will return 1 result
Get-Blob $containername $filename

# This will return 2 result
Get-Blob $containername $filename -Snapshots

# Remove the snapshot, supply snapshot time or pipe the Object
#$snapshot | Remove-Blob

# Removing the file will also fail, since we have a snapshot
Get-Blob $containername $filename | Remove-Blob

# But we can force, deleting all snapshot with
Get-Blob $containername $filename | Remove-Blob -deletesnapshots

Next up, is copy blobs across containers or even storage accounts. If you want to move everything from one account to another, here's a crud but efficient way

Select-Subscription Pay-As-You-Go
Select-StorageAccount -ServiceName wingu2
$containers = @{}
foreach($container in Get-Container){
$containers += @{$container.Name=Get-Blob $container.Name}
# Could even update it to public and close it again after with
# Set-ContainerACL $container.Name container
}

Select-Subscription skadefro
Select-StorageAccount -ServiceName copytest
foreach($container in $containers.GetEnumerator()){
$c = get-container $container.Name
if(!$c){ $c = New-Container $container.Name }

foreach($blob in $container.Value){
Write-Host ("Copying '" + $blob.Name + "' to container '" + $c.Name + "'")
Copy-Blob -Uri $blob.Uri -Destinationuri ($c.Uri.ToString() + '/' + $blob.Name)
}
}


When I showed this to a friend, he quickly asked, what if I don’t want to make it public ? Well, we can use shared signature’s for that, so here’s another way, without requiring the containers to be public.

Select-Subscription Pay-As-You-Go
Select-StorageAccount -ServiceName wingu2
$containers = @{}
foreach($container in Get-Container){
$blobs = @{}
foreach($blob in (Get-Blob $container.Name)){
# By default, this cmdlet creates a 55 minute readonly adhoc signature
$url = $blob | Get-BlobSignature
$blobs += @{$blob.Name=$url}
}
$containers += @{$container.Name=$blobs}
}

Select-Subscription skadefro
Select-StorageAccount -ServiceName copytest
foreach($container in $containers.GetEnumerator()){
$c = get-container $container.Name
if(!$c){ $c = New-Container $container.Name }

foreach($blob in $container.Value.GetEnumerator()){
Write-Host ("Copying '" + $blob.Name + "' to container '" + $c.Name + "'")
Copy-Blob -Uri $blob.Value -Destinationuri ($c.Uri.ToString() + '/' + $blob.Name)
}
}

Another feature that is missing from Microsoft's azure module is the ability to work with tables and queues. So now you can use your favorite PowerShell prompt and work with them there (if that rocks your boat)

Select-StorageAccount -ServiceName wingu2
$tablename = 'testtable'
$table = Get-Table $tablename
if(!$table){
New-Table $tablename
} else {
Remove-Table $tablename
New-Table $tablename
}

# add using hashtable
New-Row $tablename -Columns @{ ID=1; Name='John Doe' }

# add using PSObject
$row = New-Object PSObject -Property @{ ID=2; Name='Jane Doe'; upn='jd@identity.local' }
New-Row $tablename $row

# add overriding RowKey
New-Row $tablename -Columns @{ ID=3; Name='Little Doe'; City='Aarhus' }

Get-Row $tablename

# We can search by Row Key and/or Partition key. Or just use PowerShell
$row = Get-Row $tablename | ?{$_.ID -eq 3}
# Add Age to the object
$row | Add-Member -Name 'Age' -Value 33 -MemberType Noteproperty
# Update row
$row | Set-Row $tablename

# Create new, based on another
$row.ID = 4
$row.Name = 'Bill Doe'
$row.upn = 'bill@identity.local'
$row | New-Row $tablename

Get-Row $tablename

Lastly, I short list of all the commands. Source code will be uploaded once I cleaned it up a bit, and added some help texts and such. Drop me an email if your interested before I'm done (its not highest on my priority list at the moment). Should probably also add some logic to handle async blob copy’s etc. you know.

Copy-WAStorageBlob
Get-WADeployment
Get-WADisk
Get-WAHostedService
Get-WALocation
Get-WAOperationStatus
Get-WAOS
Get-WAOSFamily
Get-WAOSImage
Get-WAServiceCertificate
Get-WAStorageAccount
Get-WAStorageAccountKeys
Get-WAStorageBlob
Get-WAStorageBlobLease
Get-WAStorageBlobSignature
Get-WAStorageContainer
Get-WAStorageContainerACL
Get-WAStorageContainerSignature
Get-WAStorageRow
Get-WAStorageTable
Get-WASubscription
Get-WASubscriptionCertificate
Get-WAVM
Get-WAAffinityGroup
New-WADeployment
New-WADisk
New-WAHostedService
New-WAOSImage
New-WAServiceCertificate
New-WAStorageAccount
New-WAStorageAccountKeys
New-WAStorageBlob
New-WAStorageBlobLease
New-WAStorageBlobSnapshot
New-WAStorageContainer
New-WAStorageRow
New-WAStorageTable
New-WASubscriptionCertificate
New-WAAffinityGroup
Remove-WADeployment
Remove-WADisk
Remove-WAHostedService
Remove-WAOSImage
Remove-WAServiceCertificate
Remove-WAStorageAccount
Remove-WAStorageBlob
Remove-WAStorageBlobLease
Remove-WAStorageContainer
Remove-WAStorageRow
Remove-WAStorageTable
Remove-WASubscriptionCertificate
Remove-WAAffinityGroup
Select-WAStorageAccount
Select-WASubscription
Set-WADeployment
Set-WADeploymentStatus
Set-WADisk
Set-WAHostedService
Set-WAOSImage
Set-WAStorageAccount
Set-WAStorageBlob
Set-WAStorageContainerACL
Set-WAStorageRow

# aliases registed though module manifest file in wa.ps1
New-Alias -name Select-Subscription -value Select-WASubscription
New-Alias -name Get-Subscription -value Get-WASubscription
New-Alias -name Get-OperationStatus -value Get-WAOperationStatus
#New-Alias -name Get-Location -value Get-WALocation

New-Alias -name Get-Deployment -value Get-WADeployment
New-Alias -name New-Deployment -value New-WADeployment
New-Alias -name Set-Deployment -value Set-WADeployment
New-Alias -name Set-DeploymentStatus -value Set-WADeploymentStatus
New-Alias -name Remove-Deployment -value Remove-WADeployment

New-Alias -name Get-AffinityGroup -value Get-WAAffinityGroup
New-Alias -name New-AffinityGroup -value New-WAAffinityGroup
New-Alias -name Set-AffinityGroup -value Set-WAAffinityGroup
New-Alias -name Remove-AffinityGroup -value Remove-WAAffinityGroup

New-Alias -name Get-Disk -value Get-WADisk
New-Alias -name New-Disk -value New-WADisk
New-Alias -name Remove-Disk -value Remove-WADisk
New-Alias -name Set-Disk -value Set-WADisk

New-Alias -name Get-OSImage -value Get-WAOSImage
New-Alias -name New-OSImage -value New-WAOSImage
New-Alias -name Set-OSImage -value Set-WAOSImage
New-Alias -name Remove-OSImage -value Remove-WAOSImage

New-Alias -name Get-VM -value Get-WAVM


New-Alias -name Get-ServiceCertificate -value Get-WAServiceCertificate
New-Alias -name New-ServiceCertificate -value New-WAServiceCertificate
New-Alias -name Set-ServiceCertificate -value Set-WAServiceCertificate
New-Alias -name Remove-ServiceCertificate -value Remove-WAServiceCertificate

New-Alias -name Get-Certificate -value Get-WASubscriptionCertificate
New-Alias -name New-Certificate -value New-WASubscriptionCertificate
New-Alias -name Remove-Certificate -value Remove-WASubscriptionCertificate

New-Alias -name Get-HostedService -value Get-WAHostedService
New-Alias -name New-HostedService -value New-WAHostedService
New-Alias -name Remove-HostedService -value Remove-WAHostedService
New-Alias -name Set-HostedService -value Set-WAHostedService

New-Alias -name Get-StorageAccount -value Get-WAStorageAccount
New-Alias -name Get-StorageAccountKeys -value Get-WAStorageAccountKeys
New-Alias -name New-StorageAccount -value New-WAStorageAccount
New-Alias -name New-StorageAccountKeys -value New-WAStorageAccountKeys
New-Alias -name Remove-StorageAccount -value Remove-WAStorageAccount
New-Alias -name Select-StorageAccount -value Select-WAStorageAccount
New-Alias -name Set-StorageAccount -value Set-WAStorageAccount

New-Alias -name Get-Blob -value Get-WAStorageBlob
New-Alias -name Get-BlobLease -value Get-WAStorageBlobLease
New-Alias -name Get-BlobSignature -value Get-WAStorageBlobSignature
New-Alias -name New-Blob -value New-WAStorageBlob
New-Alias -name New-BlobLease -value New-WAStorageBlobLease
New-Alias -name New-Snapshot -value New-WAStorageBlobSnapshot
New-Alias -name Copy-Blob -value Copy-WAStorageBlob
New-Alias -name Remove-Blob -value Remove-WAStorageBlob
New-Alias -name Remove-BlobLease -value Remove-WAStorageBlobLease
New-Alias -name Set-Blob -value Set-WAStorageBlob

New-Alias -name Get-Container -value Get-WAStorageContainer
New-Alias -name Get-ContainerACL -value Get-WAStorageContainerACL
New-Alias -name Get-ContainerSignature -value Get-WAStorageContainerSignature
New-Alias -name New-Container -value New-WAStorageContainer
New-Alias -name Remove-Container -value Remove-WAStorageContainer
New-Alias -name Set-Container -value Set-WAStorageContainer
New-Alias -name Set-ContainerACL -value Set-WAStorageContainerACL

New-Alias -name Get-Row -value Get-WAStorageRow
New-Alias -name New-Row -value New-WAStorageRow
New-Alias –name Set-Row –value Set-WAStorageRow


New-Alias
-name Remove-Row -value Remove-WAStorageRow

New-Alias -name Get-Table -value Get-WAStorageTable
New-Alias -name New-Table -value New-WAStorageTable
New-Alias -name Remove-Table -value Remove-WAStorageTable

torsdag den 13. september 2012

Azure PersistentVM loosing network connectivity

I have several time experience that my VM’s suddenly loose all connectivity in azure. in the forums several people have complained about this. Your machine will show as running in the portal, but you cannot connect to it remotely. Some say that waiting a few hours makes it come back, but not for me. If you have several machines connected to a virtual network, you can ping and connect to the machine, but you cannot browse/resolve DNS, or connect to anything externally, even using IP addresses from the machine.

If you try and export the VM, delete it, and import the VM, it will fixes the problem.

$servicename = 'superservice'
$vmname = 'superserver01'

Export
-AzureVM -ServiceName $servicename -Name $vmname -Path "c:\VMConfig\$vmname.xml"
Remove
-AzureVM -ServiceName $servicename -Name $vmname
Remove
-AzureService -ServiceName $servicename
$vm = Import-AzureVM -Path "c:\VMConfig\$vmname.xml"
New
-AzureVM -VM $vm -ServiceName $servicename -Location 'North Europe'


How ever if you want to keep the Virtual IP, you don’t want to delete the Hosted Service.




New-AzureVM -VM $vm -ServiceName $servicename


This will fail if the machine was part of a Virtual Network. ( the machine will have a Subnet defined in the configuration, but the azure REST API wont know what Network that subnet belongs too (even if you only have one) so if you get


New-AzureVM : HTTP Status Code: BadRequest - HTTP Error Message: The virtual network name cannot be null or empty.


do it like this


$servicename = 'superservice'
$vmname = 'superserver01'
$vmname = 'supercoolnetwork'

Export
-AzureVM -ServiceName $servicename -Name $vmname -Path "c:\VMConfig\$vmname.xml"
Remove
-AzureVM -ServiceName $servicename -Name $vmname
$vm = Import-AzureVM -Path "c:\VMConfig\$vmname.xml"
New
-AzureVM -VM $vm -ServiceName $servicename -VNetName $networkName