Making of Sitecore Community Project Templates

Writing this blog post is like sharing an experience about Making a Hollywood movie or talking about behind the scenes for a Hollywood movie, working with Sitecore is a different experience and that is what I am sharing here and as the title says “Making of Sitecore Community Project Templates” is what this post is all about.

This all started with one bright idea from Varun Shringarpure and he was the lone warrior while he initiated his idea into a working copy. I saw him working on this great idea and suggested to help, Varun had some different idea and wanted to work alone. A couple of weeks later Varun wanted me to be part of it and he shared his experience and findings with me. Finally working together for another couple of weeks we were able to release it for Sitecore Community.

Varun started creating the various projects and their structure he followed the approach suggested at Side Waffel. There were lot of configuration needed to be done for us to get the templates generated based on Side Waffel. Later on digging into further it was discovered that there is much easier way to create the visual studio templates and we completely dropped the idea of using Side Waffel.

The approach we followed was to export each visual studio project as a template, zip the exported template and add them to the VSIX project solution. A manual task but much simpler and easier task as compared to Side Waffel configuration. Also it was difficult to troubleshoot the configurations that we created for Side Waffel.

Varun announced the release of Sitecore Community Project Templates, more on the documentation and source can be found by following the link.

If you are interested in knowing more about how it is all setup and few tips if you want to come up with your own visual studio templates keeping reading further as this will help to get you kick-started.

How is it all setup?

Currently we have setup three solutions,

1)      Sitecore.Community.Templates.VSIX

Solution for creating the VSIX file that references templates from other projects.

2)      SitecoreMVCStarterKit

Solution containing a bunch of projects required to setup a Sitecore MVC solution.

3)      SitecoreWebformsStarterKit

Solution containing a bunch of projects required to setup a Sitecore Webforms solution.

Projects

Projects

Creating Visual Studio Project Templates

Firstly we created projects structure for all projects Sitecore.MVC.Extension, Sitecore.MVC.IOC, Sitecore.MVC.Models, Sitecore.MVC.Services, Sitecore.MVC.TDS.Core, Sitecore.MVC.TDS.Master, Sitecore.MVC.Web and Sitecore.MVC.Web.UnitTest. For the projects we Added and removed files, installed nugets and such kind of stuff.

Solution Structure

Solution Structure

Once we had our projects setup correctly we did Export Template for each of the projects in the solution which in the background created a .zip file for being used as a visual studio project template.

 

Export Template

Export Template

Export Template Wizard

Export Template Wizard

Creating VSIX Project

Next step was to create a VSIX project that would help us to deliver the Sitecore Community Project Templates.

 

Creating VSIX Project

Creating VSIX Project

This is how we setup the VSIX project,

 

VSIX project setup

VSIX project setup

You might think why did we created the structure ProjectTemplates/CSharp/Sitecore Community and then added all our project template zips. There’s a reason to do so as we wanted the templates to appear under Templates-> Visual C# and just above Sitecore Rocks.

New Project Dialog

New Project Dialog

Why it’s named Sitecore Community Project Templates?

We discussed few different names like Sitecore Templates (we dropped this name as would like Sitecore owns it), Sitecore R&D Templates, Sitecore Project Templates then came the final name Sitecore Community Project Templates as it was dedicated to the so awesome and vibrant Sitecore Community and anyone can contribute to it.

Releasing Sitecore Community Project Templates

Few things that Varun worked upon for releasing it to the Visual Studio Gallery were creating Readme.txt and it’s content, License.txt, Icons, pushing to github, Adding to Sitecore Marketplace and finally sending it to Visual Studio Gallery.

Tips

1)      Amending project zip files with $safeprojectname$ helped us to achieve the custom project name that one can specify during new project creation.

$projectname$

$projectname$

Watch out this link for more token replacements at Template Parameters

2)      For your project template to appear at a required location in the New Project Dialogue, the VSIX project should reflect the same folder structure and the zip of the project template should then be added to the required folder.

3)      In order to support your VSIX for different versions of Visual Studio, open .vsixmanifest file -> Install Targets and Edit or Add New entry for the Visual Studio Version.

More details for inclusion and exclusion of visual studio versions can be found at VSIX Manifest Designer

Install Targets

Install Targets

4)      MyTemplate.vstemplate

5)      Unzip exported template and rename project with $safeprojectname$

Nice Reads

–          How to Create a Visual Studio 2012 Project Template: Introduction

–          Visual Studio Templates

–          Creating Project and Item Templates

–          Custom Visual Studio Project Templates

What a nice journey to cherish for, Thanks Varun for this endeavor and Pranav Geria for helping out with the Sitecore Icons.

Sitecore Support Package Generator

I recently updated my machine to Windows 10 and didn’t face any problems running all of my installed programs. Exceptions are always expected in a developer’s life so my Sitecore Support Package Generator was not running and every time I try to execute it, it had some issues and died showing me the below screen,

Sitecore Support Package Generator

SSPG

Checking the Event viewer and the SSPG logs files it revealed that it has some access problems with Optimization.Suggestion.Count.config file and was throwing below error.

ERROR SSPG.MainWindow - Couldn't clear IsolatedStorage on startup.
System.UnauthorizedAccessException: Access to the path 'Optimization.SuggestedTests.Count.config' is denied.
   at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive)
   at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive)
   at SSPG.Core.FileSystem.RoamingFileSystemProvider.Clear()
   at SSPG.MainWindow.MainWindow_Loaded(Object sender, RoutedEventArgs e)

You can find the SSPG.log file at C:\Users\MyUser\AppData\Roaming\Sitecore\SSPG\Files\Logs.

I then started two help channels and tweeted Alen Pelin who is the contributor to this tool, he asked me to check if I have .NET framework 3.5 installed which I was having. Our small twitter conversation.

The other channels was with the Mighty Ones, guessing who I am referring to? Yes they are Sitecore Support Team. Lilia Silvestrova asked me to delete the files present under C:\Users\<User name>\AppData\Roaming\Sitecore\SSPG\Files\ and yes that is the trick.

So if you are facing such issue I would suggest to check SSPG.Log file and if this blog post resolves your issue you should be thankful to the Mighty Ones.

Sitecore Faceting – Removing Global And Displaying Customs Facets: Part-4

We might want to have more control over the facets that are being displayed on the Search UI. When custom facets are defined they are mingled with the global ones and it is difficult to differentiate between them on the Search UI. The global facets are interpreted as sitecore default facets, but they are global ones meaning they appear on all bucket items. If you are following my Sitecore Faceting series then yes this is the fourth one talking about removing the global facets and displaying the ones that you choose.

Below image shows the custom facets mingled with global facets,

Sitecore Custom Facets Mingled

Sitecore Custom Facets Mingled

Let’s consider a hypothetical case where we need to display custom facets(News Release Date Range and News Category) related to our News bucket and which the content authors can take advantage of instead of using the global ones (Template, Language, Author, Date Range) which might not make sense to them.

The logic that we applied was to display only those facets which are selected on the “__facets” field available in the Indexing section.

Custom_Facets_-_Selected

Custom Facets Selected

 

We will take the same path as mentioned in my third post Sitecore Faceting – Ordering Sitecore Global / Default Facets: Part-3, let’s define a processor that will be patched after “Sitecore.Buckets.Pipelines.Search.GetFacets.RunFacets” processor. This processor can be found at \App_Config\Include\Sitecore.Bucket.config.

  
     
      

Now let’s writeup a class that will inherit from Sitecore.Buckets.Pipelines.Search.GetFacets.GetFacetsProcessor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sitecore.Buckets.Pipelines.Search.GetFacets;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.Data.Items;
using Sitecore.Data.Fields;

namespace sc80up2.SitecoreEntities.Facet
{
    public class FacetSortOrder : GetFacetsProcessor
    {
        #region ...Public Methods
        
        public override void Process(GetFacetsArgs args)
        {
            if (args.Result != null)
            {
                //Get bucket item
                Item bucketItem = Sitecore.Data.Database.GetDatabase("master").GetItem(args.LocationFilter);
                if (bucketItem == null) return;

                //Facet field
                MultilistField fieldfacet = bucketItem.Fields["__facets"];
                if (fieldfacet == null) return;

                List<string> lstCustomFacets= new List<string>();
                //Get selected facet on a bucket
                foreach (var selectedfacet in fieldfacet.GetItems())
                {
                    if (selectedfacet.TemplateID.ToString() == TemplateIDs.FacetTemplateID)
                    {
                        //get facet field id, can be stored by comma seperated
                        if (selectedfacet.Fields["parameters"] != null && !string.IsNullOrEmpty(selectedfacet.Fields["parameters"].Value))
                        {
                            foreach (string str in selectedfacet.Fields["parameters"].Value.Split(','))
                            {
                                lstCustomFacets.Add(str);
                            }
                        }
                    }
                }

                IEnumerable<IEnumerable<SitecoreUIFacet>> facetListLists = (IEnumerable<IEnumerable<SitecoreUIFacet>>)args.Result;
                List<IEnumerable<SitecoreUIFacet>> newFacetListLists = new List<IEnumerable<SitecoreUIFacet>>();

                foreach (IEnumerable<SitecoreUIFacet> facetList in facetListLists)
                {
                    foreach (SitecoreUIFacet facet in facetList.ToList())
                    {
                        foreach (string str in lstCustomFacets)
                        {
                            if (facet.ID.ToLower() == str.ToLower())
                            {
                                newFacetListLists.Add(facetList);
                            }
                        }
                    }
                }
                args.Result = newFacetListLists.Distinct().OrderBy(fl => (fl.Count() > 0) ? fl.FirstOrDefault().Type : "");
            }
        }
        #endregion

    }

    public static class TemplateIDs
    {
        public const string FacetTemplateID = "{5C125B6D-C481-4C24-B5B9-9A23FE396BF0}";
    }
}

Code Explanation

Selected facets are first stored in a list (lstCustomFacets), these facets are read from the “__faceting” field. Iterate through all the facets that are passed to the processor via args and trying to match the selected one stored in the lstCustomFacets and return them from the method.
That was simple isn’t it? So the crux of this post is you can have your own processor for faceting.

Below image shows the final outcome where only selected (can be custom or global ones) being displayed on Search UI.

 

Outcome Sitecore Custom Facets

Outcome – Sitecore Custom Facets

Keep faceting and Sitecoring and yes do not forget to share your Sitecore Knowledge and learnings with the Sitecore Community.

Sitecore Faceting – Ordering Sitecore Global / Default Facets: Part-3

The third in a row about sitecore faceting and yet not the last one, I am planning to write two more posts on faceting after this. If you want to refer to the previous two posts below are the links,

1) Sitecore Faceting Novice Learnings: Part-1
2) Sitecore Faceting-List and Link Type Fields:Part-2

In this post I will share how can we Sort the Global (Default) facets available on the Search UI. Sitecore has most of such things either content managed (via Core Database) or via settings, sadly for ordering of global facets you will have to write your own processor. But it’s a simple piece of code so let’s check how to achieve it.

Below is the list and image of the default facets namely,

– Template
– Language
– Author
– Date Range

Sitecore Global Facets

which are available on any sitecore bucket item.

Sitecore uses a processor, “Sitecore.Buckets.Pipelines.Search.GetFacets.RunFacets” to get and display the facets. This processor can be found at \App_Config\Include\Sitecore.Bucket.config.

  
     
      

Now let’s writeup a class for a processor that will inherit from Sitecore.Buckets.Pipelines.Search.GetFacets.GetFacetsProcessor

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sitecore.Buckets.Pipelines.Search.GetFacets;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.Data.Items;
using Sitecore.Data.Fields;

namespace sc80up2.SitecoreEntities.Facet
{
    public class FacetSortOrder : GetFacetsProcessor
    {
        #region ...Public Methods
        public override void Process(GetFacetsArgs args)
        {
            if (args.Result != null)
            {
                IEnumerable < IEnumerable < SitecoreUIFacet >  > facetListLists = (IEnumerable < IEnumerable < SitecoreUIFacet >  > )args.Result;
                IEnumerable < IEnumerable < SitecoreUIFacet >  >  newFacetListLists = facetListLists.OrderBy(fl => (fl.Count()  >  0) ? fl.FirstOrDefault().DisplayName : "");                
                args.Result = newFacetListLists;
            }
        }
        #endregion
}
}

To summarize the logic of above code, we check if there is a item attached to a facet (fl.Count() > 0) and then sort it based on “DisplayName” .

Add the FacetSortOrder processor after Sitecore’s RunFacets processor. So if you hit /sitecore/admin/showconfig.aspx it should reflect as follow,

Bucket-ShowConfig

Below is an xml that you can place in a Facet.config file for xml patching, make sure you put the Facet.config file in a folder under App_config/Include folder otherwise your processor will not get appended as Sitecore.Bucket.config falls after it chronologically.



  
    
      
        
      
    

  

Below image confirms the changed ordering of Sitecore’s Facets.

Global-Facets-Sorted

In my next post for faceting I will be writing about removing the global facets from the Search UI and displaying only the customs one as selected by a user.

Keep Sharing, Keep Caring!

Sitecore Faceting-List and Link Type Fields:Part-2

A second post in the series on Sitecore Faceting, the first post, Sitecore Faceting Novice Learnings was about getting stated with Sitecore Faceting, if you have missed it check it here. This post is about a Sitecore Setting that comes in handy when faceting for List or Link Type fields needs to be implemented.

Are you faceting List (MultiList, TreeList and others) and Link (General Link, DropLink and others) Type Fields and wanted to display the search results on a bucket, faceted by any of these fields? These fields internally stores ID of the referenced item, so if you facet on them you will see IDs being displayed on the search UI.

Below is the list of fields that stores ID of the referenced item in index,
– Checklist
– GroupedDropLink
– MultiList
– TreeList
– TreeListEx
– DropLink
– DropTree
– GeneralLink

Note: DropList and GroupedDropList stores the name of the referenced item in an index so we do not need to worry about them while faceting.

Below screenshot displays how by default the Search UI displays IDs while faceting List and Link Type fields.

IDsDisplaying

Sneaking over the indexes via Luke will also show that the indexes stores the ID of the item and hence it displays the same on the Search UI.

 

Luke-Checklist

 

Luke-MultiList

Content authors will surely come complaining to a developer that they will be happy if they see the actual name (friendly name) of the item being faceted instead of ID.

Sitecore has a lot of settings which allows you to tweak things and configure sitecore your way. I would like to share about a gem (so called setting) for Faceting in this post.

Problem Statement

How to display Friendly Name in Search UI for List & Link fields being used for Faceting?

The Approach

In order to solve above problem I started with googling and the hits that made me interested were,

Sitecore 7 Content Search – Custom Facets on List Fields by Glen McInnis, after going through this article it was not going to help me as it was SOLR and I needed something for Lucene.

FACETS EXPLAINED by Sitecore 7 Development Team, this too didn’t worked for me as these were the steps I already did and the Search UI was displaying IDs for me on the bucket folder for the facets.

SITECORE 7: MAKING GOOGLE PART 2 by Sitecore 7 Development Team, this post seemed promising to me and made me think I would have to define a virtual field and do customization. But this was a lot to do.

It constantly made me think that there should be a simpler way to achieve this hence I discussed with few brilliant brains around me (Kiran Patil and Bhavesh Maniya) who I thought might have worked on faceting. This too didn’t helped me as these guys didn’t worked on faceting for List or Link Type fields.

Brilliant brains have brilliant ideas, Kiran suggested me to look at the sitecore support portal and check if there is a ticket for it. This was a bull’s-eye for me and I found my solution. Marcia Dietrich one of our colleague already had the same problem and was answered to her query by Sitecore Support Team.

The Simplest Solution

So here come the curtain raiser, below setting is used for displaying item name for a list field being faceted on the Search UI.

The comments above this setting does mentions that if you have huge data this might degrade performance so use it wisely.

Setting the value of “BucketConfiguration.ResolveFacetValueToFriendlyName” to “true” in \App_Config\Include\Sitecore.Buckets.config would change the IDs to friendly name and you would have now become a magician for your content authors





FacetName

I am just warming up myself to write the third one in this series of sitecore faceting. If you find it interesting or want to share more about faceting please do comment on this post.

Sitecore Faceting Novice Learnings: Part-1

Sitecore 7 and above versions are really powerful in search capabilities, there are lot of things that can be accomplished. Lucene, Solr, ComputedFields, VirtualFields, Buckets and Faceting has made search very easy in Sitecore.

I have intentionally highlighted “Faceting” above as this is what I am going to blog about in this post. This post is about how you can get started with Faceting in Sitecore.

Task Description

Create a facet for News Category that will be displayed and used to filter results on a bucket folder which contains News Articles.

Here I am demonstrating News Articles which are very common to sites other examples where faceting can be implemented are Products, Employees, Customers, Case Studies and many more.

Creating a Facet

In order to get started with faceting the very first step is to define a facet, you can define a facet at “/sitecore/system/Settings/Buckets/Facets

1)      Select Facets-> Right Click and Insert Facet

Create Facet

2)      Provide Name for the facets in our case it would be “News Category”.

Facet Name

3)      Once the facet is created, there are few important fields that needs to be understood,

Field Usage
Field Name This field should have the name of the field in lower case and should match the field name in your sitecore_master_index. Ideally it would be the field name on your News Article template.

Note: If your field name have spaces replace the space with “_” so for e.g News Article template has “News Category” field, then the field name to be specified in facet should be “news_category”

Global Check this field if you want this facet to appear on all your buckets.Note: If your facet is not global and it should appear on a specific bucket only? Refer to section “Non-Global Facets” of this post to achieve this.

Facet-Fields

 

4) Now go to your bucket folder and search, custom configured facet will appear.

Facet-Results

News Category is a single line text field and “Dealernews” value can be seen faceted in above screen.

News-Item

Non-Global Facet

In most of the cases we will be creating non-global facets as they should be displayed only on specific Buckets and not all over the other sitecore buckets.

1)      To do so first off all uncheck the “Global Facet” field on your custom facet.

2)      Select the bucket on which you want the facet to be applied, in Content Tab -> Go to Indexing Section and look for “Facets” field. Select required facet.

Non-Global-Facet

Below is a code snippet in case if you want to add facets to an item programmatically.

public void AddNewsFacets(ID itemID)
        {
            const string newsCategoryFacet = "{C4788FE1-EF4A-4814-961C-1CF85B9144CA}";
            var item = Sitecore.Context.Database.GetItem(itemID);

            Logger.LogMessage(string.Format("Adding Facets {0}", itemID), this);
            using (new EditContext(item))
            {
                MultilistField fieldfacet = item.Fields["__facets"];
                if (fieldfacet==null)
                {
                    return;
                }
                //clear the values first if any saved in the field
                item.Fields["__Facets"].Value ="";

               //now add the required facets
                fieldfacet.Add(newsCategoryFacet);                
            }
            Logger.LogMessage("Adding TOT Facets Complete", this);
        }

Be tuned on more for Sitecore Faceting! Till then Keep Sitecoring and Sharing

Create Azure VM from PowerShell with IIS Web Server auto installed

I saw someone asking on a forum about how to create Azure VM with Windows feature pre-installed, i thought it would be nice weekend exercise to see if i can get a Azure virtual machine created from PowerShell with IIS Web Server auto installed.

Now, by no means, i am saying that the PowerShell script given below is the best way to do it, there could be better, easier and correct way of doing it, but hey … this got my job done, so it should help you as well.

So in below PowerShell script the only thing that you have to change is, replace wherever you see XXXXXX with your cloud service name (the name that appears in Azure cloud service section), i know i can add a variable and make it easier for you, perhaps in next version of script.

so let’s see the script.


#Let's select the VMImage first that we want to use to build Server
$getvmimage = "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-201412.01-en.us-127GB.vhd"

# keep some variable handy which we will reuse many times
$user = "webadmin"
$pass = "P@ssw0rd"
$name = "Web60" #####This will be the name of your VM, you can changet if you wish to########

# Create new AzureVMconfig for Web60 and provide it as input to Azureprovisioningconfig and eventually to New-AzureVM
$newvm = New-AzureVMConfig -Name $name -InstanceSize Medium -ImageName $getvmimage | Add-AzureProvisioningConfig -Windows -AdminUsername $user -Password $pass
New-AzureVM -ServiceName XXXXXXXXXXX -VMs $newvm -WaitForBoot -Verbose

#Some Port & Session Variables
$port = Get-AzureEndpoint -Name PowerShell -VM (Get-AzureVM -ServiceName XXXXXXXXXXX -Name $name) | Select -ExpandProperty Port

Write-Host "$port"   ####No real importance, writing it on console only for testing##############

$credential = Get-Credential -Credential $user -Verbose
$sessionoption = New-PSSessionOption -SkipCACheck
$session =  New-PSSession -ComputerName XXXXXXXXX.cloudapp.net -Credential $credential -Port $port -UseSSL -SessionOption $sessionoption -Verbose

$getstatus = Get-AzureVM -ServiceName XXXXXXXXXX -name $name | select InstanceStatus, PowerState -Verbose
if ($getstatus -match "ReadyRole" -and "Started") {Write-Host "Server is Ready, Connecting Now"; Enter-PSSession -Session $session}
else {Write-Host "Unable to Connect, Something Wrong, Try Again"; $getstatus }

#Once PSSession  starts then it should install Webserver Role in remote server
#Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature -IncludeManagementTools -Verbose

Invoke-Command -Session $session  -ScriptBlock {Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature -IncludeManagementTools -Verbose} -Verbose

There are many more stuff that you can do it from this script by making some easy changes, like instead of Web-server you can deploy any other Windows Feature by just making some changes, or you can leave the windows feature about completely and just use the PowerShell remoting to login to remote server and do whatever you want to.

If you come across any bug, or if you know about a better way of doing it, just share in comment.

Till then happy learning.

Hardeep

Sitecore8 Logout Bug

I might be “the fewer ones” who got chance to work on an upgrade project from Sitecore 6.6 to Sitecore8. During our initial installation phase when I was playing around with Sitecore8 discovered a bug with the Logout link available at the top right corner of Sitecore Launch Pad.

Sitecore8 Logout

Do you ever logout from Sitecore? I have seen most of the users directly closing the browser, instead of doing it a correct way and logging out. Logging out correctly doesn’t matters if your license covers huge number of logins, however if you have limited logins licensed and users do not logout, often you might come across a message stating maximum number of allowed users has been reached. If you have come across such a message here is a very nice article explaining the solution.

So, you have just logged in Sitecore8 to get a snitch of it and clicked on “Logout” link it comes up with error as shown below.

Sitecore8-Logout-error

Sitecore8-Logout-error

This happens only for the first time when you click on Logout link. Using browser back button and clicking again on Logout will not reproduce this issue. It’s just for the first time in a new browser session.

Sitecore Support has provided a solution for it and that is what I am sharing it here,

1. Backup /Website/Views/Shared/ExperienceExplorerView.cshtml

2. Download ExperienceExplorerView.zip, extract and replace ExperienceExplorerView.cshtml at /Website/Views/Shared folder.

That’s all I have to share in this post, keep Sitecoring and sharing.

Create New Storage Account with PowerShell

Creating New Storage Account in Azure.
It’s pretty easy when you want to create an Azure storage account using management portal, however let’s see how to create one using PowerShell, gradually you’ll see all this smaller tutorials adding up to one complete how to tutorial for Azure VM creation.

1. Let’s first see if you have any storage account available in Azure subscription

You can query your subscription with “Get-AzureSubscription” and under “CurrentStorageAccountName” property you will see the name of storage account, if the property is blank than that means either no storage account is created or the storage account is not yet set in subscription.

08-Get-AzureSubscription

As you can see we do not have any account available as of now under “CurrentStorageAccountName”.

2. So let’s now create a storage account in Azure using PowerShell cmdlets and later on we will set the account in subscription

#New-AzureStorageAccount –Location “East US 2” –StorageAccountName “hi1” –Label “HI1”

11-New-AzureStorageAccount

We have successfully created the storage account, you should be able to verify it in your management portal as well, for me it took about a min for information to appear on management portal.

3. Now let’s verify in your PowerShell and see if PowerShell can detect the new storage account automatically.

#Get-AzureSubscription

08-Get-AzureSubscription

AS you can see “CurrentStorageAccountName” property doesn’t have any value set, so let’s update the properties of a Microsoft Azure Storage account in current subscription.

4. Let’s set the newly created storage account in Azure Subscription.

The “Set-Azuresubscription” cmdlet establishes and changes the properties of an Azure Subscription. You can use this cmdlet to create a new subscription or change the properties of an existing subscription.

Required parameter are: -CurrentStorageAccountName
: -SubscriptionName

# Set-AzureSubscription -SubscriptionName -CurrentStroageAccountName “write the name of your account here.”

Now if you do not come across any error, let’s verify and check the properties of “CurrentStorageAccount” whether it’s update or not with new value.

15-Blur-AzureSub

Keeping learning, Keep Sharing

Thanks

Hardeep

Connecting Powershell To Azure Account

Hi,

Apart from managing your Azure setup from management portal you can do it through your PowerShell console as well, additionally it helps in automating your task too, so let’s see how to connect your PowerShell to Azure account.

1. How to list cmdlet modules in PowerShell
Windows PowerShell module exist in two states, either they are loaded or are available within your setup but aren’t loaded yet, first we will see how to list down modules which are loaded in your PowerShell, then we will see how to list down all the cmdlet available in your system but not loaded yet.

2. How to list loaded module in PowerShell
You can use the “Get-Module” cmdlet without any parameters to list down loaded module in Powershell

01-Get-Module-All

3. How to list all modules in PowerShell
To obtain list of all modules available in system but might not be loaded in Windows PowerShell console, you can use the same cmdlet “Get-Module” but with additional parameters

02-Get-Module-List-Available

4. If you do not see Azure cmdlets in your system, than you’ll have to install them, let’s see how to do that.

5. The easiest way is to do it from Microsoft Web Platform installer, the web platform installer will not only install the cmdlet, but it will also resolve all the dependencies and install them as well, so that makes it very easier for you.

So open your preferred browser and go to Microsoft Azure Downloads

Once you are in download section of command line tools you can click on install and that should download the web platform installer, rest of the installation of cmdlet then should be done from web platform installer.

03-Webinstaller-from-microsoft

6. Once you have downloaded the web installer and started the deployment the first screen would look like something as below, from there on rest of is just clicking Next button.

04-Web-installer

 

7. Once you have installed the module you can search in PowerShell for Azure module.

05-Get-command-Azure

8. Let’s connect your powershell to Azure
There are couple of ways you can add the Azure account to Windows PowerShell. You can use the “Add-AzureAccount” cmdlet, which uses Azure Active Directory authentication access tokens, or you can do it through “Import-AzurePublishSettingsFile”, which uses a management certificate, which you have to download first.

8.1
The “Add-AzureAccount” cmdlet makes your Azure Account and its subscriptions available in Windows PowerShell. It’s like logging in to your Azure account in Windows PowerShell.
When you run Add-AzureAccount, it displays an interactive windows that prompts you to sign into your Azure account. This sign-in is valid until the access token expires. When it expires, cmdlet that require access to your account prompt you to run Add-AzureAccount again.
I guess the access token TTL is one hour, but that’s just my guess.

06-Add-Azureaccount

As you can see above, you can simply write “Add-AzureAccount” cmdlet in PowerShell console without any option and it will prompt you for your username and then password.

8.2 Verify your Azure Account
Once you have successfully logged in, it would be good to verify your account and ensure you have logged in to correct account, you might have multiple accounts.

To verify your account, you can run following command.

“Get-AzureSubscription”

08-Get-AzureSubscription

8.3 Connect your Powershell to Azure using “Get-AzurePublishingsettingsFile” and “Import-AzurePublishSettingsFile”

With “Get-AzurePublishingSettingsFile” you have to download the publishing profile from Azure management portal and store it as some secure path.

Once you have downloaded the profile you have to than import in PowerShell with “Import-AzurePublishSettingsFile”, the import command would like something as below.

PS C:\Windows\system32> Import-AzurePublishSettingsFile “Path to your file you downloaded from portal”

Note: Ensure to mention your path in double quotes

8.4 Once you have managed to connect PS to Azure, then let’s verify it for last time.

08-Get-AzureSubscription

9. For some reason if you want to remove this subscription from your PowerShell then you can use the following cmdlet to remove.

#Remove-AzureSubscription

The Remove-AzureSubscription cmdlet deletes an Azure subscription from your subscription data file so Windows PowerShell can’t find it. This cmdlet does not delete the subscription from Microsoft Azure, or change the actual subscription in any way.

Required parameter is -SubscriptionName

so the final cmdlet would be

#Remove-AzureSubscription -SubscriptionName “whatever is your subscription name”

If you have any query/question write to hardeepbhamra@gmail.com

Thanks

Hardeep