by

How To Get the Managed Accounts Password in SharePoint 2010

This script I’ve got some time ago from a Microsoft Field Engineer. It is ok to share (you can find this same utility here and a more elaborated version here). Make sure to run this script in the SharePoint Management Shell, using an account with Farm Admin privileges.
function Bindings()
{
    return [System.Reflection.BindingFlags]::CreateInstance -bor
    [System.Reflection.BindingFlags]::GetField -bor
    [System.Reflection.BindingFlags]::Instance -bor
    [System.Reflection.BindingFlags]::NonPublic
}

function GetFieldValue([object]$o, [string]$fieldName)
{
    $bindings = Bindings
    return $o.GetType().GetField($fieldName, $bindings).GetValue($o);
}

function ConvertTo-UnsecureString([System.Security.SecureString]$string) 
{ 
    $intptr = [System.IntPtr]::Zero
    $unmanagedString = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($string)
    $unsecureString = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($unmanagedString)
    [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($unmanagedString)
    return $unsecureString
}

Get-SPManagedAccount | select UserName, @{Name="Password"; Expression={ConvertTo-UnsecureString (GetFieldValue $_ "m_Password").SecureStringValue}}


You should see a result like this:


get-sharepoint-2010-service-accounts-password-powershell


Things to Watch Out



Some tricky things might happen when you execute this script. So, If you run this script and…



  • All passwords displayed are BLANK: check your current logged  account permissions (remember, farm admin rights)


  • Some of the passwords displayed are BLANK: the accounts are likely out-of-synch with Active Directory ..ouch!


Accounts Out-of-Synch With AD



if you have multiple farms or geographically distributed farms, do not be surprised if after you setup the Auto-Reset Managed Accounts Password you see them out-of-synch with AD. If you experience that, try to run the following command:



Repair-SPManagedAccountDeployment



This will redeploy all the credentials and checks if the current farm passphrase is consistent across all the servers. This command will also tell you if any accounts are broken. In that case you should see a screen similar to the below:


repair-sharepoint-managed-accounts-powershell


in that case you can try to…


Set the Managed Account Password Manually



Run the following command:



Set-SPManagedAccount -UseExistingPassword





This will allow to enter the password for the managed account. This command is the same used to set the password. You will see a screen similar to the below where you will manually enter the set-sharepoint-managed-accounts-password


 


If when trying to execute the command, you receive an error message like the one below,


error-deploying-administration-application-pool-credentials-another-deployment-may-be-active


then make sure the SharePoint Timer Jobs are running in all the servers. I hope all these experiences I’ve had help you and maybe save some of your precious time.


By

by

How to Fix PassBook: Cannot Connect to iTunes Store iOS6

If you just upgraded your iPhone to the new iOS6 you will note one of the new apps called PassBook. Click here to learn more about the PassBook.

iphone-passbook-hot-to-fix- (2)

However, if you try to access it you will see this frustrating message:

iphone-passbook-hot-to-fix- (3)

here’s a little hack to overcome this. Go to your phone settings and change your device date to the future. Choose year 2013, for example.

iphone-passbook-hot-to-fix- (4)

then confirm and do not select the option to automatically update the time.

With the clock set to the future, go to the PassBook app. You should see once more the cannot connect to the Apple store message, but then after that is all good.

iphone-passbook-hot-to-fix- (5)

iphone-passbook-hot-to-fix- (1)

By

by

How to Fix: Verify that the critical User Profile Application and User Profile Proxy Application timer jobs are available and have not been mistakenly deleted

When provisioning a Project 2010 Server or a SharePoint 2010 server, if you are using the Service Pack 1 you will have an unpleasant surprise which is the User Profile Service misbehaving and potentially breaking your system. To fix that, the recommendation is to apply the August 2011 Cumulative Update.
However soon you will notice that every hour or so, your SharePoint Health Analyzer will start bombarding your screen with this error:
 
sharepoint-2010-review-problems-and-solutions
 
That is in fact an issue introduced with the August CU. It is a known issue and MS is working on that. Chances are there is nothing wrong with your UPS. That's very likely a false positive. They are just timer jobs which are being deleted without any intervention, but because a bug was introduced by the cumulative update package.
So to avoid that message keeps showing up and drawing your attention, you have to set SharePoint to automatically try to fix the issue. Follow these steps.
In the Monitoring section, in the Central Admin, click the link Review Rule Definitions
sharepoint-2010-monitoring-health-analyzer
A list of all the current job definitions will be listed by group. Browse the Configuration group and find the rule called "Verify that the critical User Profile Application and User Profile Proxy Application timer jobs are available and have not been mistakenly deleted"
 

health-analyzer-rule-definitions-configuration-sharepoint-2010
Click the rule and edit the item selecting the checkbox Repair Automatically, then save.


edit-health-analizer-rules-definition
Now, every time this message comes up SharePoint will try to fix the issue automatically creating the missing timer jobs

By

by

The New Microsoft Logo Done Using ONLY CSS

That’s pretty hard-core UI , the new Microsoft logo done entirely with CSS. No images, no convoluted HTML…just plain CSS.
logo {
    font: 60px "Segoe UI";
    color: #747273;
    line-height: 1.5em;
    padding-left: 1.7em;
}

logo:before {
    content: '\2006';
    position: absolute;
    height: 0.095em;
    left: 0;
    box-shadow: 0.35em 0.35em 0 0.25em #f8510c, 1.05em 0.35em 0 0.25em #7eba00, 0.35em 0.97em 0 0.25em #00a3f4, 1.05em 0.97em 0 0.25em #ffba00;     
}



If you create an html page with:

<logo>Microsoft</logo>


you will see this.ms


You can play around here for more results: http://jsfiddle.net/ 




superedge-css


Note that the logo increases/shrinks according to the length of the text


google-css


apple-css


( yeah, I know…doesn't look good on Apple Smile )


Go ahead and have fun!

By

by

Project Management: Duration, Scheduling, Resourcing

Before the project starts, a schedule is created. A schedule determines the macro view of the project, which is then broken down into smaller pieces of work. The person responsible to handle this dynamic is called Scheduler.
The scheduler with all these pieces then creates a work breakdown structure, aka. WBS, which is the wallet for the effort estimated for each task. Then we find the people, then allocate them and then we get moving.
This is not news, we've been doing this for centuries. Just look at the engineering projects. We've been building cathedrals, cities, bridges, castles for many years. We do have a huge experience and materials when the subject comes to manage engineering projects.
With so much experience and materials to build upon, we still find ourselves having an incredible hard time trying to answer one question : how many tasks should we have in a schedule and how long each task should be?

The Art of Estimation
Often we see project schedules that are just plain convoluted and project managers frustrated to isolate the issue with the tasks in the project schedule because they far too macro. Some projects lasts decades, like the construction of the LHCI; some projects are just a few days. But regardless of the length, how to handle a schedule with hundreds, thousands of items?
Different industries, require different project management strategies, that's one of the primary challenges of the project: Delivering on time, on budget. Let's have a look at an IT project. Here a few samples on how to approach the scheduling and task decision process:
IT projects: IT is a very new category of projects; unlike engineering projects the experience is being built fairly recently, which might explain why so many IT projects fail in comparison with older industries.
  • Phases: IT projects normally follow a very successful model, which is a design phase, a development/build phase, a quality assurance/testing phase, a documentation phase, and a deployment/release
  • Duration: The projects are measured in weeks or months; which makes the task to allocate work a bit easier: days or weeks.
  • Resourcing: Resource allocation comes down to a person/unit. If you drink the Agile-koolaid you should try to think about the resources and tasks using  short sprints. Maximum 2 weeks sprints.
Engineering/Construction Projects: This is what the humankind knows how to do it best. Big scale projects.
  • Phases: Just like regular planned projects but having an engineering phase at the beginning. This is a very peculiar group, because despite our vast historic experience, this moment always covers one or many aspects that has never been done/thought/designed before.
  • Duration:  Engineering projects are visualized in months, years...lasting at minimum weeks and at maximum months.
  • Resourcing: Expect to see thousands of tasks in this type of project. So the Scheduler here will have to manage the units person/skill level, rather than person/day. These allocations can become quite complex and often there is a needed to create smaller projects and group them into a program to ease the management and delivery aspect.
Which these concepts in mind we will discuss now how long should be a project.
Divide to Conquer
Let’s imagine an engineering plant location move project. The company bought new offices in another location and needs to phase-out the old offices while transitioning to the new one. First we need to identify the macro-objective, then after that experience show us that the breakdown in smaller pieces are a good approach. Not only because they are more visible to manage and to handle but also because their deliverables can potentially be closed down independent of each other.
pm
you determine the star and finish of the project. then you breakdown in smaller tasks (A, B, C, D, for example), then you try to group these tasks in logical phases (1, 2 and 3, in our case) and for each phase you try to break them in smaller micro tasks. How many micro tasks is up to the manager or responsible for the delivery but in my experience I try to avoid creating less than 5 tasks and more than 15. This is not a rule of guide, it is just the number I personally feel confortable and that has brought me most successes.
Additionally, every time a decision needs to be applied to a task try to get into the habit of asking yourself: can this task be broken down into smaller tasks? Is this going to impact the scope? the main reason for that is because generally some tasks look very simple in the schedule but effectively can become quite complex during the execution…for many reasons. You can’t foresee which ones will be but you can forecast their likelihood of happen.
And yet…
bear in mind that despite all our previous successes and our amazing management skills… some projects will fail, and sometimes nothing can stop that happening. For these cases the same old adage still applies: visibility, visibility, visibility. Make a deliverable visible as much as you can, use whatever powers you have to propagate this visibility. You cannot stop a project from failing, but you can fail gracefully (to use a term from IT management). As long as everyone is aware of how the project is going and we are doing the best we can of the situation everyone is accountable.
The plan is not important, but planning is important.

By

by

What is BYOD and Why Some Companies are Against It ?

BYOD (bring your own device) is one of the big topics being discussed now in the organizations. The main questions arise from:
  • is our organization mature/prepared enough to allow external devices coming into our ecosystem?
  • is our workforce trained and educated enough to understand their possibilities, actions and consequences?
  • is our overall culture and strategy aligned with the new world of BYOD?
These are extremely thoughtful questions and if governance around this topic is not done with due diligence, these policies can swiftly backfire.
What's the point in blocking Facebook, twitter etc. when clearly your employees likely have a smartphone in their pocket and will use these services anyway?
Having said that, I believe we need to understand the motivations and the cost x benefits that BYOD would bring to an organization.
For example, it is common practice that content created on company's computers are intellectual property not of the employee but the company itself; however what are the implications if the employee creates his material in a personally own laptop? who has the IP of the production? you see...that's already raising big questions and yet this is not even the tip of the iceberg. The lines between IP and behaviour are getting blurred by the minute.
and here's the raw truth. 67% of the people are already using it and the majority of people is in favour of bringing their own devices to work anyway.
byod

How did the BYOD thing started?

We live in a social world, and the technology reflected this in many ways, mimicking across the virtual world. Now we have Facebook, tweeter etc. So when people went to work, they felt the need to adjust their new virtual persona across the boundaries as well. People don't want to wait until 6PM to live their online personas, they want full experience, control. So, BYOD started from the employee/worker's perspective.
The next step was then to use the devices they felt more confortable with. Your company might have a preferred mobile device such as BlackBerry for business, HP for laptops, encrypted USB drives for data transfer. And more often than not, these are pushed via company policies. However, some workers did not like BlackBerry, they want to use iPhones, they prefer using a Samsung Series 9 instead of HP, and they prefer to keep their stuff in pocket hard disks. People were then using the company's recommended devices and side-by-side using their own preferred ones. Almost like a parallel reality.
And for a whole new generation which was born with a myriad of technological options, being able to choose their own hardware and software platforms makes them more satisfied. More satisfied workers likely makes more productive people. More productive people increases the chances of a project success. Project success makes companies happy. Win-Win for companies and workers.
Sounds like simple joining the dots. It isn't.
Research has shown more majority of organizations are against BYOD  , and in fact some organizations actually ban workers bringing their own devices to work. But don't blame the corporations for it, some of them have very good points to back their policies.
 
Look at this research and you can see that almost 60% of U.S. IT professionals view mobile devices owned by employees as posing the greatest risk their organization face . If you work in the healthcare or finance, this is even more real.
Mainly this happens because some industries are highly regulated by very strong code of practices when it comes to sensitive and privacy data such as company and customers. These industry regulators stand a very strong stance and it an organization is found breaching some of their obligations they can easily face fines and some cases even jail.
See now? the iceberg tip starts to show up and the conversation is not focused anymore just on gadgets but how a business is run and their obligations with the market, government and citizens.
Overall, all this is great. It opens up the canvas for discussion around the pros and cons of adopting BYOD.
Just accepting BYOD as the coolest thing ever at the workplace is not the smartest route. As in any project, all the risks and benefits need to be weighted.

By

by

How to Get AD Forest in PowerShell

Here’s another small PowerShell script useful for your administration. It returns the AD object for a specified forest; the forest in the current context is returned  if nothing is passed as parameter. This is also compatible with Office 365.
function Get-Active-Directory-Forest-Object ([string]$ForestName, [System.Management.Automation.PsCredential]$Credential)
{    
    #if forest is not specified, get current context forest
    If (!$ForestName)     
    {        $ForestName = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Name.ToString()    
    }        

    If ($Credential)     
    {        
        $credentialUser = $Credential.UserName.ToString()
        $credentialPassword = $Credential.GetNetworkCredential().Password.ToString()
        $adCtx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("forest", $ForestName, $credentialUser, $credentialPassword )
    }    
    Else     
    {        
        $adCtx = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext("forest", $ForestName)    
    }        

    $output = ([System.DirectoryServices.ActiveDirectory.Forest]::GetForest($adCtx))    

    Return $output
}



By

by

How to Change Currency from Windows Store in Surface, Windows RT

if you just received your Microsoft Surface RT, when going to the Windows 8 app store you should see the prices in your local currency. In my case I saw the prices in British Pounds…living in Australia it does not make much sense…so if you come across this, here’s how to fix:

 

at the Start Menu, type ‘location’. and select the option ‘Settings’ and ’Change location’

 

in the next screen, choose your correct location. In my case, my Surface was configured to ‘United Kingdom’, so I just changed to ‘Australia’

click OK and voila! all set. If you go to the Windows Store again you should see the prices adjusted to your correct currency.

By

by

How to Populate a ObjectDataSource from a Dataset

To use datasets for data manipulation and grid displaying is great in a SharePoint environment.  
The .NET framework offers many displaying controls for that task amongst them is the SPGridView. Grid views are excellent for presenting data because people like to see things organized in grids. it is almost natural to our eyes and project stakeholders love grids because they are like the heart and soul of a project management report.
If you are using SharePoint it is pretty straightforward to instantiate a SPGridView control and then use the datasource property to point to a dataset.
So let's say, you want to display all the team sites or site under a specific URL. you can populate a dataset with the rows and bind to the grid.

sharepoint-objectdatasource-spgridview-dataset-1
The only issue here is the network traffic. Every time you perform a postback you will force the dataset to be loaded and then the grid will just change the page displayed, but under the hood the whole dataset was there populated. If you have hundreds of sites and these are being accessed by multiple users it can potentially be using unnecessary bandwidth. ( note: There are strategies to place around this mechanism like using cache objects and persisting information in the viewstate, but we wont be discussing them here )
sharepoint-objectdatasource-spgridview-dataset-3 
 
Would not be great if we could have a out-of-the-box structure good enough to allow fetching the necessary records for a specific page?
For that we can use the ObjectDataSource control.

sharepoint-objectdatasource-spgridview-dataset-2
You can read a lot about the usages of the ObjectDataSource all over the net, but if you are like me a big fan of datasets and you have been dealign with datasets objects in many legacy applications, you want to just want to have an easy way to migrate your datasets to ObjectDataSources.
Unfortunately, the ObjectDataSource control does not have a property like objectDataSource.DataSource neither it has a LoadFromXml or Load(Dataset)...
So how do you do?
Here's how I find it: using reflection.

ObjectDataSources do not have a property to perform something like MyObjectDataSource.DataSource=MyDataSet, but it does have a constructor that allows you to parse classes and extract data methods.
So let's say you have a scenario like this in a webpart
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use
        /// composition-based implementation to create any child controls
        /// they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            Grid = new SPGridView
                           {
                               AutoGenerateColumns = false,
                               AllowSorting = true,
                               AllowPaging = true,
                               AllowFiltering = true,
                               PageSize = 10
                           };
 
            Grid.DataSource = MyDataSet.MyTable;
            Grid.DataBind();
        }

To convert this to an ObjectDataSource you then do this...
        /// <summary>
        /// Gets the data table for object source.
        /// </summary>
        /// <returns></returns>
        public DataSet GetDataTableForObjectSource()
        {
            // do whatever you want to do here and
            // return the table with the data
            return MyDataSet.MyTable;
        }
 
 
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use
        /// composition-based implementation to create any child controls
        /// they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
 
            // in this constructor specify the type name, the class name and
            // the public method inside this class where the object datasource will retrieve the data
            // make it a signed assembly for security reasons.
            var edgeDataSource =
                new ObjectDataSource(
                    "MyNamespace.MyClass, MyNamespace.MyClasss, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ce8ab85a8f42a5e8",
                    "GetDataTableForObjectSource") {ID = "EdgeDataSource"};
 
            Grid = new SPGridView
                           {
                               AutoGenerateColumns = false,
                               AllowSorting = true,
                               AllowPaging = true,
                               AllowFiltering = true,
                               PageSize = 10
                           };
 
            // do not use DataSource property. MUST USE DataSourceID with the control name
            Grid.DataSourceID = "EdgeDataSource";
 
            // do this before the databind
            Controls.Add(edgeDataSource);
            Controls.Add(Grid);
 
            // bind the objects and execute the call
            //specified in the ObjectDataSource constructor
            Grid.DataBind();
        }
 
Cute trick!
So there you go. To migrate, load, or populate ObjectDataSources using DataSets, all you have to do is to wrap the data returned in a public class and pass the method information to the ObjectDataSource constructor. I hope this helps you guys out there using ObjectDataSources.
Now go coding. Happy paging, happy filtering, happy caching!

By

by

Duet Enterprise: Derived Key Token Cannot Derive Secret

In the process of connecting SAP and SharePoint, one of the steps is to ask the SAP Administrator to provide to provide a whole bunch of BDC models. These models will then be incorporated into the SharePoint BCS and then make the SAP tables available in the SharePoint site.
duet-enterprise-sharepoint-sap
Sounds simple, except for the fact that, more often that not even if you follow the steps to the letter, one might come across the following error message:
security configuration error: derived key token cannot derive key from the secret
This is caused mainly by SAP configuration (or lack of it), but do not put the blame on them...getting Duet to work sometimes it is a daunting task.
How to track that down?
Listen to the network: well, one of the things you can do it to see what's going on is using the good old network sniffing tools. I suggest to you the Network Monitor, but feel free to use what ever you want. By listening to the traffic flowing from SharePoint to SAP you will have a clue it the connection is established.
duet-enterprise-sharepoint-sap - 2
If you hear nothing, this lead to the conclusion that BCS might not be connecting at all. Check the SAP endpoints, find out how the HTTPS port is configured. Do not assume SAP is using the default HTTPS port number. The best way to find this out: open the endpoint URL with your favourite browser.
If you can browse, the issue is likely security. Check the security configuration of the Duet accounts involved. Check the SSO accounts.
If you can not browse, check if there are any firewall blocks between the SharePoint farm and the SAP gateway servers.
  duet-enterprise-sharepoint-sap - 3
if there are no devices or security rules blocking the network connection then we must go to the mythic land of the SAML.
You see…for Duet Enterprise to work , the endpoint requires that the SAML issuer configured in the SAP side must be correct. If it is not, this will result in a token issued incorrectly, which will then reflect in the BDC schemas exported from SAP, and since the schemas are going to be generated with different keys, the BCS models and calls to endpoint won't work. The fix is in the middleware, the SCL.
duet-enterprise-sharepoint-sap - 4
This used (maybe still is...) a very tricky thing because the only way to fix this is dealing with XML manually (I know...sorry for you in advance). On a positive note, I understand that in Duet Enterprise FP1 there is an automated tool, but I haven’t be able to work with FP1 yet.
If you don't have access to this XML tool to “spot the not-right”, I suggest you to try these steps:
duet-enterprise-sharepoint-sap - 5
  1. If you see the KeyType element, try to change to PublicKey. (check the WSDL endpoint exposed by the SAP)
  2. Remove all BCS definitions from SharePoint
  3. In SAP, regenerate all BDC definitions.
  4. Reimport them all into SharePoint
Every Duet Enterprise project I've seen was a success so far, however nobody said it is always easy.

By

by

Test Drive: Xbox SmartGlass on Windows 8

If you have installed the new Windows 8, you will notice there is an application called Xbox SmartGlass. SmartGlass at first seems just like a regular app that talks about movies etc., however it integrates completely with your Xbox experience. Here’s how to setup your SmartGlass.
11
In your Windows 8 Start menu, tap the Xbox SmartGlass application.
Untitled
Your Windows 8 device will try to connect to the Xbox console. Make sure you are connected to the internet and your Xbox Live account is on.
2 3
In a few seconds the two devices will start trying to “talk” to each other. Once the connection is established, your windows 8 notebook or tablet will be effectively part of your Xbox ecosystem. Like a remote control.
From your tablet, now you can access to the Xbox 360 Dashboard. If you have a 360 dashboard in your console you will notice that it is not quite exactly the same look of your Xbox, but it definitely has all the functions, just that they are adapted to the tabled.
4 5
Your tablet or notebook becomes truly a Xbox controller. Swipe your fingers across the screen and you see that your Xbox will respond to it. In a more detailed view, you can see how the surface of your tablet is configured as a SmartGlass controller. We even have access to the typical controller buttons.
7 9
Now one of the coolest things. If you have Xbox applications like Vevo, Foxtel on Xbox etc. You can control and watch movies from it. In this case I am playing the movie Gattaca.
but wait, there is more! Microsoft went one step ahead. Look that in your SmartGlass is able to retrieve and display detailed information regarding the movie. The device I am using is not a Windows 8 “official” tablet. but the expectation is that we will be able to find more information about the movie, characters, actors as we watch and even streaming the movie to the tablet…making the whole media experience superb! You can potentially leave your room and continue watching the movie in the tablet.
Another great feature is that SmartGlass is a “dockable” application, so you can continue using your Windows 8 environment for work, editing Office documents, browsing the internet and at the same time keep watching the movie in the left side of the screen.
10
All in all, Windows 8 is amazing so far and Xbox will definitely become more than just a gaming console. I can’t wait to get my hands in the first Microsoft Surface and try all these things. Have a look at the video demoing the Xbox SmartGlass

Cheers,

By

by

How To Count How Many Pages in SharePoint Site Using PowerShell

Some tasks you don't need to go ask the developers to create a feature for you. Don’t worry about them.
Again, here’s another script for the casual SharePoint Administrator, Developer or Project Manager that does not require much work or knowledge of SharePoint. How many pages a site has? Let’s go to the bits. You can use this little script below:

function count-items-by-site-by-list-type($URL, $BASETEMPLATE) 
{     
    $site = Get-SPSite $URL     
    $totalItems = 0     
    foreach($web in $site.AllWebs)     
    {         
        $lists = $web.Lists         
        for ($i=0; $i -le $lists.Count – 1; $i++)          
        {             
            $list = $lists[$i]             
            if ($list.BaseTemplate -eq $BASETEMPLATE)             
            {                 
                $totalItems = $totalItems + $list.Items.Count             
            }         
        }             
    }     
    $site.Dispose()     
    write-host $totalItems 
}




This script counts all the items for a given list type. So for example, if you want to count how many pages there are in the following http://www.myProjectSite.com you should do this:


count-items-by-site-by-list-type http://mySite/ "WebPageLibrary"


You can get any result; project items, total of tasks, total of persons, total of documents…anything. The possible values for the $BASETEMPLATE parameter can be found in this link.


What if I have pages not only in page libraries but across any library?


Then you can use this modified version. Remember this code will run a bit slower so I’ve put some visual clues as heartbeat indicators.



function count-pages($URL)
{    
    $site = Get-SPSite $URL    
    $totalPages = 0    
    foreach($web in $site.AllWebs)     
    {         
        write-host        
        write-host "Processing:" $web.Url        
        $lists = $web.Lists        
        write-host "(lists found ):" $lists.Count        
        write-host "-------------------"        
        for ($i=0; $i -le $lists.Count – 1; $i++)        
        {             
            try            
            {                
                $list = $lists[$i]                
                for ($j=0; $j -le $list.Items.Count – 1; $j++)                
                {                    
                    $item = $list.items[$j]                    
                    if ( $item.Url.ToLower().EndsWith(".aspx") )                    
                    {                        
                        $totalPages++                        
                        write-host -fore green -back green " " -nonewline                    
                    }                
                }            
            }            
            catch                
            {                
                write-host -fore red -back red " " -nonewline            
            }        
        }    
    }    
    $site.Dispose()    
    write-host    
    write-host "----------------------------------"    
    write-host "total pages found--->" $totalPages
}



Cheers,

By

by

How To: Fix relative broken links in SharePoint (using PowerShell)

Scenario: There is project website in the production environment. How can we replicate that same environment for a test/development environment?
One of the options would be to backup and restore the whole site via SharePoint granular backup. However if you have a domain name specific for test (something like http://myprojectTEST.com) then you have to adjust the links that will likely come broken.
sharepoint-broken-links-migration_thumb[2]
The PowerShell script below address this case. It works similar to a string replace; the difference here is that it works in the navigation links.
function fix-quicklaunch-links([string]$URL, [string]$oldString, [string]$newString) 
{ 
    $errorFileName = "c:\temp\fix-quicklaunch-links-ERROR.txt" 
    $successFileName = "c:\temp\fix-quicklaunch-links-SUCCESS.txt" 

    $site = Get-SPSite $URL 

    $totalWebs = $site.AllWebs.Count – 1
    foreach($web in $site.AllWebs) 
    { 
        Write-Host 
        Write-Host -fore white -back blue "Processing web: " $web.Url 
        $nav = $web.Navigation 
        $quicklaunch = $nav.QuickLaunch 

        $totalQuickLaunch = $nav.QuickLaunch.Count - 1 
        for ($i=0; $i -le $totalQuickLaunch; $i++) 
        { 
            $mainlink = $quicklaunch[$i] 
            $linkurl=$mainlink.Url 

            if ($linkurl.Contains($oldString)) 
            { 
                try 
                { 
                    $mainlink.Url = $linkurl.Replace($oldString, $newString) 
                    $mainlink.Update() 
                    write $linkurl | Out-File -filepath $successFileName -append 
                    write-host -fore green -back green "." -nonewline 
                } 
                catch 
                { 
                    write $linkurl $_.Exception.Message | Out-File -filepath $errorFileName -append 
                    write-host -fore red -back red "." -nonewline 
                } 
            } 
            $totalChildren = $mainlink.Children.Count - 1 

            for ($j=0; $j -le $totalChildren; $j++) 
            { 
                $child = $mainlink.Children[$j] 
                $childurl = $child.Url 

                if ($childurl.Contains($oldString)) 
                { 
                    try 
                    { 
                        $child.Url = $childurl.Replace($oldString, $newString) 
                        $child.Update() 
                        write $childurl | Out-File -filepath $successFileName -append 
                        write-host -fore green -back green "." -nonewline 
                    } 
                    catch 
                    { 
                        write $childurl $_.Exception.Message | Out-File -filepath $errorFileName -append 
                        write-host -fore red -back red "." -nonewline 
                    } 
                } 
            } 
        } 

        $web.Update() 
    } 

    $site.Dispose() 

    $finaldate = Get-Date 
    write-host 
    write-host -fore white -back blue "End of processing ("  $finaldate ")"
}
 





so if you are migrating from http://myprojectsite to http://myprojectsiteTEST you would call the function as:


fix-quicklaunch-links “http://myprojectsite” “http://myprojectsite/” “http://myprojectsiteTEST/”


The script will run across the site you specify in the parameters and it will traverse all the sub sites and navigation links under it. At the end it will generate 2 log files in the c:\temp folder with the errors and successes during the process.


I hope it helps someone with this issue.

Cheers,

By

by

How To Create Cascading Dropdowns SharePoint 2010

Scenario: You want to be able to add items to a list where the values of the “dropdown 1” are dependent on the selected “dropdown 2” value. As in the figure below.
1

Unfortunately that’s not an out of the box feature in SharePoint, however you can achieve that with a mix of jQuery and Content Management.
It is not complicated and if you follow these instructions, you don’t even need jQuery background to achieve it. The first step is to create 2 lists: one for the parent values (in our sample, Countries) and one for the children values (in our sample, cities)
In the countries list, leave the Title column to be the country name.
2
In the cities list, leave the Title column to be the city name; Additionally, create a new column called Country which will map to the same values you will enter in Title column of the country list. From now on, let’s refer to this list as a Relationship List.
3
Now, in the main form create 2 linked columns: One pointing to the Title column in the city list and the other pointing to the Cities column in the Cities list (the relationship list)
In our sample, the column linked to the countries list is called CountryLookup.The column linked to the cities will be called CityLookup. Below you see them and their definitions:
4
5
6
Now comes the part 2, when we will use the jQuery engine to power our solution. You will need to download the jQuery library and the SPServices library.
Place these files in a library which your site has access.
7
Now, in your main list we are going to modify the way the add new items to the list works. If you never done that, not a problem, you will see that’s very easy. In the list ribbon, choose the option to edit the Default New Form.
8
The form below will appear. Click add a web part link and place there a content editor web part.
9
In the content editor, add the code below. Do not add as text, make sure to add as HTML.

<script language="javascript" src="/js/jquery-1.8.0.min.js" type="text/javascript" />
<script language="javascript" src="/js/jquery.SPServices-0.7.1a.min.js" type="text/javascript" />    
<script language="javascript" type="text/javascript">     

    $(document).ready(
    function()   
    {             
        $().SPServices.SPCascadeDropdowns(           
        {             
            relationshipList: "Cities",  
            relationshipListParentColumn: "Country",  
            relationshipListChildColumn: "Title",                 
            parentColumn: "countrylookup",  
            childColumn: "citylookup",  
            debug: true
        });
    });
</script>




Save the form and that’s it. Try to add a new item to the list and you will see that when you select the country dropdown, the cities will be automatically updated to reflect only the cities that match the country.


Cheers,

By