Friday, November 27, 2015

Error occurred in deployment step 'Uninstall app for SharePoint': Communication with the SharePoint server is canceled.

Hi,

Did you have tried with SharePoint online Developer Site with deploying a fresh App? Do you tried with VS 2013 Premium, VS 2012 Premium? and when you ask for logging credentials for SharePoint Online site, did you get above error?

Error occurred in deployment step 'Uninstall app for SharePoint': Communication with the SharePoint server is canceled.

If so keep reading the post since I have found this solution sometimes back. After several years months it popped up with my new laptop. So thought to share with you to save some time.

this is the last error you will see after several js errors.

Solution:

1.Check your windows updates, all of the important updates should be installed.
2.Go to windows features and disable and enable IE 11
3.Repair your .Net framework 4.5.2 to get back to original state.
4.Clear down the SharePoint online cache by log out and close the all browsers.

Then try to go online with the solution. You should be successfully log in to the SharePoint online and run your application.


Tuesday, August 11, 2015

System.IO.FileLoadException: System.IO.FileLoadException: Could not load file or assembly 'Microsoft.QualityTools.Testing.Fakes, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040).

Hi,

This issue was faced while we were building our unit tests. We had Microsoft.QualityTools.Testing.Fakes - Version=12.0.0.0 installed and reference was updated to not to use specific version. We rebuild our test suit, but failed.

We are keep getting this error and luckily we got below reference:

http://stackoverflow.com/questions/27741115/need-a-work-around-microsoft-qualitytools-testing-fakes

which is the exact same issue.

We followed below steps from the thread and succeeded.

1.Go to project directory and find "FakesAssemblies"
2.Delete all the contents
3.Make sure the specific version for the Microsoft.QualityTools.Testing.Fakes assembly is set to 'false'
4.Rebuild the solution and run/debug test

Good Luck! thought someone will be get help.

Tuesday, July 14, 2015

MVC KendoGrid Data retrieval sample implemented

Recently I got task to implement KendoGrid for one of my implementation and thought to share the experiences gained while researching about Kendo (DevCraft).

Task : Create Notes (plain text) with some other parameters (which were already populated while main view is loading). So I have to integrate my Notes section in a partial view and avoid postback the page and refresh KendoGrid, with the new notes added by the user.

My approach:

I have created a div with id = "grid". So my ultimate target is to update KendiGrid to this div.

<div id="grid"></div>

then I have gone through several samples mentioned in KendoGrid documentation and learnt special points regarding the changes I need to apply and match with the configurations.

(KendoGrid samples : http://docs.telerik.com/kendo-ui/api/javascript/ui/grid and http://demos.telerik.com/kendo-ui/grid/index)

So I have started like below:

$("#grid").kendoGrid({
})

We should configure a datasource for the grid. So I have able to create datasource like below

$("#grid").kendoGrid({
             dataSource: {
                    type: "json",
                    transport: {
                        read: { url: '@Url.Action("YOURACTION", "YOURCONTROLLER")', dataType: "json", type: "GET", cache: false },
                        parameterMap: function (data, operation) {
                            if (operation == "read") {                              
                                data["YOURPARAMETERTOPASSTOACTION"] = PARAM1;
                            }
                            return data;
                        }
                    }

})

(I just reading the data and pumping into the grid. I also pushing one parameter to the Action and I'm using json calls)

I need to show an error message when KendoGrid facing a issue on loading data. So it's like below after update.

$("#grid").kendoGrid({
             dataSource: {
                    type: "json",
                    transport: {
                        read: { url: '@Url.Action("YOURACTION", "YOURCONTROLLER")', dataType: "json", type: "GET", cache: false },
                        parameterMap: function (data, operation) {
                            if (operation == "read") {                              
                                data["YOURPARAMETERTOPASSTOACTION"] = PARAM1;
                            }
                            return data;
                        }
                    },
                    error: function (e) {
                        ShowGeneralErrorMsg('ERROR TO SHOW');
                    }
               }

})

Also I need to define the schema to show.

$("#grid").kendoGrid({
             dataSource: {
                    type: "json",
                    transport: {
                        read: { url: '@Url.Action("YOURACTION", "YOURCONTROLLER")', dataType: "json", type: "GET", cache: false },
                        parameterMap: function (data, operation) {
                            if (operation == "read") {                              
                                data["YOURPARAMETERTOPASSTOACTION"] = PARAM1;
                            }
                            return data;
                        }
                    },
                    error: function (e) {
                        ShowGeneralErrorMsg('ERROR TO SHOW');
                    },
                     schema: {
                        model: {
                            id: "FIELD1",
                            fields: {
                                OTHERFIELD1: { type: "string" },
                                OTHERFIELD2: { type: "string" },
                                OTHERFIELD3: { type: "date" }
                            }
                        }
                    },
                     batch:false
               }
})

After defining the schema, I have updated the columns configurations with custom template definitions for several columns. Disable sorting.

$("#grid").kendoGrid({
                dataSource: {
                    type: "json",
                    transport: {
                        read: { url: '@Url.Action("YOURACTION", "YOURCONTROLLER")', dataType: "json", type: "GET", cache: false },
                        parameterMap: function (data, operation) {
                            if (operation == "read") {                              
                                data["YOURPARAMETERTOPASSTOACTION"] = PARAM1;
                            }
                            return data;
                        }
                    },                  
                    error: function (e) {
                        ShowGeneralErrorMsg('ERROR TO SHOW');
                    },

                    schema: {
                        model: {
                            id: "FIELD1",
                            fields: {
                                OTHERFIELD1: { type: "string" },
                                OTHERFIELD2: { type: "string" },
                                OTHERFIELD3: { type: "date" }
                            }
                        }
                    },
                    batch: false
                },
                navigatable: true,
                dataBound: function () {

                },
                sortable: false,
                toolbar: kendo.template('<div class="dropdown milestone-add-btn">' +
                            '<a href="javascript:void(0);" onclick="javascript:ShowAddForm();" class="action-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true"><i class="icon icon-add icon-accent"></i><span>add</span></a>' +
                                        '</div>')

                       ,
                columns: [{
                    field: "OTHERFIELD1",
                    headerTemplate: '<div><label class="grid_header_label">OTHERFIELD1</label></div>',
                    template: '<a class="text_ellipsis" style="float:left; width:400px;" href="javascript:void(0);" title="#=OTHERFIELD1#">#=OTHERFIELD1#</a>'

                },
                {
                    field: "OTHERFIELD2",
                    headerTemplate: '<label class="grid_header_label">OTHERFIELD2</label>',
                    template: "#= kendo.toString(kendo.parseDate(OTHERFIELD2, 'yyyy-MM-dd'), 'MM/dd/yyyy') #"
                },
                {
                    field: "User",
                    headerTemplate: '<div><label class="grid_header_label">OTHERFIELD3</label></div>',
                    editor: OTHERFIELD3Editor,
                    template: "#=OTHERFIELD3#"
                },
                {
                    command: [
                    {
                        name: "destroy",
                        text: "&nbsp;",
                        iconClass: "icon icon-accent icon-remove icon-align icon-2x",

                    }
                    ]
                }],
                editable: false
            });

            $("#grid").find(".k-grid-toolbar").insertAfter($("#grid .k-grid-content"));

Monday, June 15, 2015

The "SqlBuildTask" task failed unexpectedly. System.IO.FileNotFoundException

Hey Guys,

While you were building a solution with a DB project inside MVC app, you may see a build error like below.

Error 10 04018: The "SqlBuildTask" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.TransactSql, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.SqlServer.TransactSql, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
   at Microsoft.Data.Tools.Schema.Sql.Build.SemanticVerification.Verify(SqlSchemaModel model, ErrorManager errorManager, String databaseName, String referencesFilePath)
   at Microsoft.Data.Tools.Schema.Sql.Build.SqlTaskHost.RunExtendedValidation(String databaseName, String referencesFile)
   at Microsoft.Data.Tools.Schema.Tasks.Sql.SqlBuildTask.ExecuteValidateModelStep()
   at Microsoft.Data.Tools.Schema.Tasks.Sql.SqlBuildTask.ExecuteStep(Func`1 step)
   at Microsoft.Data.Tools.Schema.Tasks.Sql.SqlBuildTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__20.MoveNext()

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

Solution:

Go to the project properties of the error throwing project and uncheck


That's it, your solution should build as normal.

Tuesday, June 9, 2015

'System.Web.WebPages.Html.HtmlHelper' does not contain a definition for 'DropDownListFor' and no extension method 'DropDownListFor' accepting a first argument of type 'System.Web.WebPages.Html.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)

If you are working on Visual Studio 2013 Premium and started to work on MVC 4 or 5 project. You will be probably experiencing this error while building your solution. MVC Razor mark ups were not recognized and intellisence were not working. I think I have figure out the fix.

I tried below options from several posts (mentioned in the end of this post)

Attempt 1:

1.Check /Views/ web.config
2.Check the Razor reference syntax is like below

<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>
 
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Optimization" />
        <add namespace="Orca.Web" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

(I'm working on MVC 5)

Attempt 2:

Clean the solution and close VS 2013 premium. Deployed Update 4 for Visual Studio 2013 Premium. Start the VS and clean the solution and rebuild. Yup That's it! Worked successfully.


Tuesday, March 31, 2015

SharePoint 2013 Apps - what is 'Use Strict'

What is 'Use Strict'?

As it mentioned, may be the beginners in SharePoint 2013 app developers, notice the specific line in Scripts/App.js file. It's the first line appeared in that file and it App.js file was automatically included while you created a new App development project through Visual Studio. Please find below information I have grabbed through several posts.

"Use Strict" is guiding the code blocks to be run under Strict mode. As you already know, we got number of ECMAScript versions like 3.1, 4 and 5. Strict Mode is a new feature comes with ECMAScript 5 allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions. Basically developers can use of this mode effectively, also have to be extra careful on using it. Some developers mentioned that it's better to configure JSHint/JSLint before you use "Use Strict".

What are the pros/cons on Strict Mode?

It catches some common coding bloopers, throwing exceptions.
It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
It disables features that are confusing or poorly thought out.

However in mozilla they have listed down several number of features that "Strict mode" will facilitate

Please follow below url:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

If you love to know more about ECMAScript 5, please go through below url:

http://ejohn.org/blog/ecmascript-5-objects-and-properties/




Monday, February 23, 2015

Powershell suit for all functionalities - SharePoint 2010/2013

Hey Folks,

I was thought to share one of my idea to share most of the common powershell commands we were using daily in our day to day jobs, in SharePoint. I'm sure this should be helpful to you in your needs. Code is not debugged fully. So go for it.


Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0

Write-host -ForegroundColor Yellow 'Powershell suit for SharePoint 2010/2013 Manipulation!'

Write-host '---------------------------------------------------------'
Write-host ''
Write-host 'This suit will facilitate most of the common tasks that will perform by SharePoint developer.'


Write-host 'Please enter your option to proceed......'
Write-host ''
Write-host -ForegroundColor Green '########## Bulk Operations'
Write-host ''
Write-host 'Create bulk number of items to custom list - Enter 1'
Write-host 'Delete bulk number of items from custom list - Enter 2'
Write-host 'Get Item Count of a list - Enter 3'
Write-host ''
Write-host -ForegroundColor Green '########## General Site level operations'
Write-host ''
Write-host 'Get Content Types and their GUIDs - Enter 4'
Write-host 'Get custom web templates deployed - Enter 5'
Write-host 'Get site/web level features - Enter 6'
Write-host 'Activate/Deactivate specific feature on specific Scope - Enter 7'
Write-host 'Get the WSPs deployed in solution store - Enter WSPS'
Write-host 'Add, Deploy WSP and Activate features in a site collection - Enter DEP'
Write-Host 'Upgrade WSP - Enter UPG'
Write-host 'Retract particular wsp and remove - Enter REM'
Write-host ''
Write-host -ForegroundColor Green '########## Powershell general informations'
Write-host ''
Write-host 'Get the powershell version of the environment - VER'
Write-host ''

$answer = Read-Host 'Please enter your option '
Write-host ''


switch($answer)
{
 # Creating bulk number of items
 1 {
  Write-host -ForegroundColor Green 'Your answer is : 1'
  Write-host ''
  $siteUrl = Read-Host 'Please enter site url '
  $listName = Read-Host 'Please enter List Name to get Item Count '
  Write-host ''
  $webUrl = $siteUrl
  $listName = $listName
  $numberItemsToCreate = 20000
  $itemNamePrefix = "Title "
   
  # Open web and library
  $web = Get-SPWeb $webUrl
  $list = $web.Lists[$listName]
   
  # Create desired number of items in subfolder
  for($i=1; $i -le $numberItemsToCreate; $i++)
  {
   $newItemSuffix = $i.ToString("000000")
   $newItem = $list.AddItem()
   # List item fields need to be populate here.
   $newItem["Title"] = "$itemNamePrefix$newItemSuffix"
   $newItem.Update()
   write-host "Item created: $itemNamePrefix$newItemSuffix"
  }

  #Dispose web
  $web.Dispose()
 }
 # Deleting bulk number of items
 2 {
  Write-host -ForegroundColor Green 'Your answer is : 2'
  Write-host ''
  Write-host -ForegroundColor Green 'Batch process will delete items in batches of 2000 >>>'
  Write-host ''
  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null
  $siteUrl = Read-Host 'Please enter site url '
  $listName = Read-Host 'Please enter List Name to get Item Count '
    $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
    Write-Host "SiteURL", $siteUrl

    $sw = New-Object System.Diagnostics.StopWatch
    $sw.Start()

    $web = $site.OpenWeb()   
    $myList = $web.Lists[$listName]
    Write-Host "Items Number before delete: ", $myList.Items.Count

  $guid = $myList.ID
  $strGuid = $guid.ToString()

    $strPost = "<?xml version=""1.0"" encoding=""UTF-8""?><ows:Batch OnError='Return'>"
    foreach($item in $myList.Items)
    {
    $strPost += "<Method><SetList Scope=""Request"">"+ $strGuid +"</SetList>"
    $strPost += "<SetVar Name=""ID"">"+ $item.ID +"</SetVar><SetVar Name=""Cmd"">Delete</SetVar>"
    $strPost += "</Method>"
    }
    $strPost += "</ows:Batch>"

  # Write-Host "Batch: " $strPost
    $strProcessBatch = $web.ProcessBatchData($strPost)
    
    Write-Host "Result: " $strProcessBatch 

    $sw.Stop()
    Write-Host "Items total after delete: ", $myList.Items.Count
    #write-host "$y Items add in " $sw.Elapsed.ToString()
    
    $web.Dispose()
    $site.Dispose()
 }
 # Count the items in a custom list
 3 {
  Write-host -ForegroundColor Green 'Your answer is : 3'
  Write-host ''
  $siteUrl = Read-Host 'Please enter site url '
  $listName = Read-Host 'Please enter List Name to get Item Count '
  
  $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
    

  $sw = New-Object System.Diagnostics.StopWatch
  $sw.Start()

  $web = $site.OpenWeb()   
  $myList = $web.Lists[$listName]
  Write-Host "Number of Items in the list: ", $myList.Items.Count
 }
 # Get Content Types and their GUIDs
 4 {
  Write-host -ForegroundColor Green 'Your answer is : 3'
  Write-host ''
  $siteUrl = Read-Host 'Please enter site url '
   
  $site = new-object Microsoft.SharePoint.SPSite($siteUrl)
  $cts = $site.rootweb.ContentTypes
 

  '"CT Name"' + `
  ',"CT ID"' `
  #',"CT Description"' + `
  #',"CT Group"' +
  #',"Field Title"' + `
  #',"Field Internal Name"' + `
  #',"Field ID"' + `
  #',"Field Group"' + `
  #',"Field Max Length"' + `
  #',"Field Description"' 

  ForEach ($id in $cts)
  {
   '"' + $id.Name + `
   '","' + $id.Id + `
   '"' 
    
    #ForEach ($field in $id.Fields)
    #{
   #'"' + $id.Name + `
   #'","' + $id.Id + `
   #'","' + $id.Description + `
   #'","' + $id.Group + `
   #'","' + $field.Title + `
   #'","' + $field.InternalName + `
   #'","' + $field.Id + `
   #'","' + $field.Group + `
   #'","' + $field.MaxLength + `
   #'","' + $field.Description + `
   #'"' 
    #}
  }

  $site.Dispose()
 }
 # Get custom web templates deployed
 5 {

  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  $web = Get-SPweb $siteUrl 
  Write-host "Web Template:" $web.WebTemplate " | Web Template ID:" $web.WebTemplateId 
  $web.Dispose()

  # To get a list of all web templates, use the following PowerShell code

  function Get-SPWebTemplateWithId 
  { 
    $templates = Get-SPWebTemplate | Sort-Object "Name" 
    $templates | ForEach-Object { 
   $templateValues = @{ 
    "Title" = $_.Title 
    "Name" = $_.Name 
    "ID" = $_.ID 
    "Custom" = $_.Custom 
    "LocaleId" = $_.LocaleId 
     }

  New-Object PSObject -Property $templateValues | Select @("Name","Title","LocaleId","Custom","ID") 
     } 
  }

  Get-SPWebTemplateWithId | Format-Table


 }
 # Get site level features
 6 {

  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
 
  #Get-SPFeature | Sort -Property DisplayName
 
  #Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id
 
  Get-SPFeature | Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,Id
 
  #Get-SPFeature -Site $siteUrl | Sort DisplayName | FT DisplayName,Id
 
  #Get-SPSite $siteUrl | Get-SPWeb -Limit ALL | %{ Get-SPFeature -Web $_ } | Sort DisplayName -Unique | FT DisplayName,Id

 }
 # Activate/Deactivate feature on a specific site collection
 7 {
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  $FeaturefolderName = Read-Host "Enter Feature folder name ";
  $SiteScope = Read-Host "Enter site scope ";
  
 
  function Check-SPFeatureActivated
  {
  #Write-Host "inside function";
   param([string]$FeaturefolderName=$(throw "-FolderName parameter is required!"),
     [Microsoft.SharePoint.SPFeatureScope]$Scope=$(throw "-Scope parameter is required!"),
     [string]$Url)  
   if($Scope -ne "Farm" -and [string]::IsNullOrEmpty($Url))
   {
    throw "-Url parameter is required for scopes WebApplication,Site and Web"
   }
   $feature=$null
     
    switch($Scope)
    {
     #"Farm" { $feature=Get-SPFeature $FeaturefolderName -Farm }
     #"WebApplication" { $feature=Get-SPFeature $FeaturefolderName -WebApplication $Url }
     #"Site" { $feature=Get-SPFeature $FeaturefolderName -Site $Url }
     #"Web" { $feature=Get-SPFeature $FeaturefolderName -Web $Url }
    
     Site {
       try
       {
        $feature=Get-SPFeature $FeaturefolderName -Site $Url
       }
       catch [System.Management.Automation.ActionPreferenceStopException]
       {
        if( !($_.Exception -is [System.Data.DuplicateNameException]) )
        {
         #Its not a "feature is already activated at scope" exception
         #throw 
         Write-Host -ForegroundColor Yellow "Feature already activated!"
         $feature = False;
        }
       
       }    
     }
     Web {
    
       try
       {
        $feature=Get-SPFeature $FeaturefolderName -Web $Url
       }
       catch [System.Management.Automation.ActionPreferenceStopException]
       {
        if( !($_.Exception -is [System.Data.DuplicateNameException]) )
        {
         #Its not a "feature is already activated at scope" exception
         #throw 
         Write-Host -ForegroundColor Yellow "Feature already activated!"
         $feature = False;
        }
       
       }
      
    
     }
    
    }
   #}
  
  
   #return if feature found or not (activated at scope) in the pipeline
   $feature -ne $null
  }

  $IsAlreadyDeployed = Check-SPFeatureActivated -FeaturefolderName $FeaturefolderName -Scope $SiteScope -Url $siteUrl
 
  if($IsAlreadyDeployed)
  {
   Write-Host -foregroundcolor Red "Feature already activated!"
   Write-Host " "
   Write-Host -foregroundcolor yellow "Deactivating the feature!"
   Write-Host " "
   Disable-SPFeature $FeaturefolderName -Url $siteUrl
   Write-Host " "
   #Write-Host "Enabling the feature!"
   #Write-Host " "
   #Enable-SPFeature $FeaturefolderName -Url $siteUrl
   
  }
  else
  {
      Write-Host -foregroundcolor Green "Enabling the feature in site level!"
   Write-Host " "
  
   Enable-SPFeature $FeaturefolderName -Url $siteUrl
  
  }
 
  #Enable-SPFeature $FeaturefolderName -Url $siteUrl
 
  

 }
 # Get the powershell version
 VER {
  Write-host 'Your powershell Version is :'
  Write-host ''
  $PSVersionTable.PSVersion
 }
 # Get the WSP deployed
 WSPS {
  [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
  $farm=[Microsoft.SharePoint.Administration.SPFarm]::Local
  Write-Host -foregroundcolor Yellow "WSP's deployed to the solution store!"
  Write-Host " "
  Write-Host "==============================================================="
  Write-Host " "
  foreach ($solution in $farm.Solutions) 
    {
     if ($solution.Deployed){
        Write-Host $solution.DisplayName " | " $solution.Status   #need to check the statuses provide by this $solution variable            
     }          
    }
  Write-Host " "
 }
 # Add, Deploy WSP and Activate features in a site collection
 DEP {
  # read wsp package location
  $fileUrl = Read-Host "Enter Location to the WSP ";
  #$fileUrl = "< location>"
 
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  #$siteUrl = "<url>";
 
  # Get WSP name
  $fileName = Read-Host "Enter WSP Name ";
  #$fileName = "TestWspDeployment.wsp";
 
  $file = $fileUrl + $fileName;
  # Add WSP to solution store
 
 
  Add-SPSolution -LiteralPath $file;
  $sln = get-spsolution -identity $fileName;
   Install-SPSolution -Identity $fileName -WebApplication $siteUrl -GACDeployment -Force;
   while($sln.JobExists) { 
   Write-Host -NoNewLine .
   start-sleep -s 2 
   };
   Write-Host " "
   Write-Host " "
   Write-Host -ForegroundColor Yellow "Solution $fileName Deployed successfully!"
 }
 # Upgrade selected WSP
 UPG {

  # read wsp package location
  #$fileUrl = Read-Host "Enter Location to the WSP ";
  #$path = "<location>"
 
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  #$siteUrl = "<url>";
 
  # Get WSP name
  $file = Read-Host "Enter WSP Name ";
  #$file = "TestWspDeployment.wsp";
 
  #$file = $fileUrl + $fileName;
  # Add WSP to solution store
 

  # Get the path to WSP
  $path = Read-Host "Enter Location to the WSP ";
  # Get the WSP Name
  #$file = Read-Host "Enter WSP Name ";
  # Get site collection
  #$siteUrl = Read-Host "Enter Site Collection URL ";

  Write-Host "Upgrading solution:" $file -ForegroundColor Green
  Update-SPSolution -Identity $file -LiteralPath $path$file -GACDeployment
  $solution = Get-SPSolution $file
  Write-Host "Waiting for solution upgrade to complete" -ForegroundColor Green

  while ($solution.JobExists -eq $true) {
   Write-Host "." -NoNewline
   sleep 1
   $solution = Get-SPSolution $file
  }
  ""
  Write-Host "Solution upgrade completed " $file -ForegroundColor Green

  Write-Host "Restarting IIS Services."

  IISRESET /NOFORCE


 }
 # Retract and Remove WSP after deactivating features
 REM {
  # Get site collection
  $siteUrl = Read-Host "Enter Site Collection URL ";
  #$siteUrl = "<url>";
 
  # Get the WSP Name
  $file = Read-Host "Enter WSP Name ";
  #$file = "TestWspDeployment.wsp";
 
 
  # Check if solution exists.
  $Solution = Get-SPSolution | ? {($_.Name -eq $file) -and ($_.Deployed -eq $true)}  -ErrorAction SilentlyContinue
  if ($Solution -ne $null)   
  {

   Write-Host "Retracting solution: $file" 
   if($Solution.ContainsWebApplicationResource)   
   {   
    Uninstall-SPSolution $file -AllWebApplications -Confirm:$false   
   }   
   else   
   {   
    Uninstall-SPSolution $file -Confirm:$false   
   }
   # There is a error in this line Restart-SPAdminV4
   #Restart-SPAdminV4
   while ($Solution.JobExists)
   {
    Write-Host -NoNewLine .
    Start-Sleep 2
   }
   Write-Host ""
   Write-Host "$file retracted successfully."  -foregroundcolor Green
   Write-Host ""
   if ($(Get-SPSolution | ? {$_.Name -eq $file}).Deployed -eq $false)
   {
   Write-Host ""
    Write-Host "Removing solution: $file" 
    Write-Host ""
    Remove-SPSolution $file -Confirm:$false
    Write-Host "$file removed successfully from solution store!"  -foregroundcolor Green
    Write-Host ""
   }
  } 
  else
  {
 
  $Solution2 = Get-SPSolution | ? {($_.Name -eq $file) -and ($_.Deployed -ne $true)}  -ErrorAction SilentlyContinue
   if($Solution2 -ne $null)
   {
   Write-Host "Solution not deployed!"
   $GetAnswer = Read-Host "Remove solution from solution store (Y/N) "
    if($GetAnswer = "Y")
    {
     Write-Host ""
     Write-Host "Removing solution: $file" 
     Write-Host ""
     Remove-SPSolution $file -Confirm:$false
     Write-Host "$file removed successfully."  -foregroundcolor Green
     Write-Host ""
    }
   }
  }
 

 }

 Default {}

}

function Restart-SPAdminV4
{
    Stop-Service SPAdminV4
    Start-SPAdminJob 
    Start-Service SPAdminV4
}