Google vs. Microsoft

November 30, 2010 3 comments

I recently started a comparison chart between Google and Microsoft. It mainly concerns their cloud offering but I’ve included some old school applications as well. I’ll be updating the post as I learn more about each’s services and add my own thoughts as well. If I’m missing something or if anyone had some thoughts please let me know!

Google Microsoft
Free Web Applications Search
Gmail
Picasa
Maps
Sites
Google Docs
Google Calendar
Google Talk
N/A
Google Video / YouTube
Buzz
Google Voice
Bing
Hotmail
Live Photo Gallery
Bing Maps
N/A
Docs.com
Live Calendar
Live Messenger
SkyDrive / Live Mesh
N/A
N/A
N/A
Business Web Applications Google Apps for Domains

  • Free for first 50 users
  • DocVerse + Office
  • Google Docs
  • Sites / Calendar
  • Gmail
  • Google Voice (TBD)
Office 365 (Closed Beta)

  • $$$$$
  • On Premise Office 2010
  • Office Web Apps
  • SharePoint Online
  • Exchange Online
  • Linc Server Online
Platform as a Service Google App Engine

  • N/A
  • Languages: Java and Python
  • Relation Database: Hosted SQL with GAE for Business
  • Datastore: BigTable
  • Authentication: Integrates with Google Accounts
  • Services: Memcache, Mail, Scheduled Tasks
  • Frameworks: Spring and Django (with mods)
  • N/A
Azure

  • VM from On-Premise (TBD)
  • Languages: C#, VB.NET, IronRuby, IronPython, PHP
  • Relational Database: SQL Azure
  • Datastore: Tables, Blobs, and Queues
  • Authentication: SAML but must be handled by developer
  • Services:  Web Role, Worker Role, AppFabric  Service Bus
  • Frameworks: ASP.NET MVC, PHP Zend
  • Ability to remote login to running instance
Mobile OS Android Windows Phone 7
Client OS Chrome OS (TBD) Windows 7
Server OS N/A Windows 2008 R2 Server
Browser Chrome IE 9 Beta
On-Premise Software N/A SharePoint Server
Exchange Server
Linc Server
Hyper-V
Active Directory
SQL Server
BizTalk Server
On-Premise Search Google search appliance FAST Search for SharePoint
  • Update 001 – 12/1/2010: Added Google Search Appliance and FAST Search
  • Update 002 – 12/3/2010: Added updates to GAE that Google recently release
Categories: Cloud

Claims Based Authentication with SharePoint 2007

June 24, 2010 1 comment

I was recently tasked with enabling our SharePoint farm with Claims Based Authentication. It was a fun challenge as I never worked with the technology before.  There is a lot to Claims and I don’t want to go into too much depth on the benefit as there are plenty of good blogs already out there.  If you are completely new to Claims then this article should be a good starting point.

Microsoft has released both a Step-by-Step Guide to get SharePoint 2007 working with Claims as well as a MSDN article.  Personally, I found both of these lacking in detail for my situation and the goal of this post is to fills in the gaps left by these two other articles.  A lot of the Microsoft documentation focused on either Windows 2008 or in single server farm, which didn’t fit my environment.  Hopefully this posting will help others who would like to try Claims out.

Prerequisites

There are several prerequisites that are required before we get started. They are.

  1. ADFS v2 running on Windows 2008 R2. I didn’t set this up but my co-worker followed the Step-By-Step Guide linked above
  2. SharePoint 2007 SP2 or SharePoint Services 3.0 SP2 or later
  3. Windows 2003 R2 SP2
  4. .NET Framework 3.5 SP1
  5. An extended Web Application that is either in the Internet or Extranet Zone
  6. A SSL certificate for the extended Web Application installed on all WFE servers and in IIS.
  7. winhttpcertcfg.exe – http://www.microsoft.com/downloads/details.aspx?familyid=c42e27ac-3409-40e9-8667-c748e422833f&displaylang=en
  8. The STS Signing Certificate for the resource domain. You need to get this from your ADFS/Domain Admin.  Install this into the Local Machine’s Trusted People store on all Web Front End servers.
  9. The URL of the STS server, typically the ADFSv2 system. Obtain exact location from your friendly ADFS/Domain Administrator

One of the most frustrated things with Claims is that the Windows Identity Foundation client that is a required component is not built for a scaled out SharePoint farm.  To fix this, Microsoft provides source code for the RSACookieTransformLibrary.  The issue is that their link in their MSDN article doesn’t work. I had to track down our TAM to get me the code.  I am not sure if I can redistribute it or not (I need to ask our TAM) so in the mean time, you can always post a comment on this blog and I’ll try to get it to you. 

After you get the code you have to change only one line, enable Assembly Signing (so it can be placed into the GAC), and Compile.  You will need the WIF Client and the WIF SDK in order to compile. My exact steps were:

  1. Download and install WIF Client (for Windows 2003 x86 only) on system
  2. Download and install WIF SDK on system
  3. Download RsaCookieTransformLibrary Zip File
  4. Extract Zip File
  5. Open in Visual Studio
  6. Select the Common name for the Claim’s enable WebApplication SSL certificate , created earlier
  7. Open the file RSAEncryptedSessionSecurityTokenHandler.cs
  8. Replace ‘YourUniqueCertificateSubjectName to with Common Name copied from Step 6
    1. Be aware. At first, I only thought this would be something like “CN=claims.example.com”. But it turns out for my certificate, the subject name was something like "CN=claims.example.com, OU=Example, O=Example, L=Chicago, S=IL, C=US"
    2. I had to write a small console application to walk through what the Subject was
  9. Go to the Property Page of the Project
  10. Select the Signing Tab > Check the Sign the Assembly box
  11. Click New for strong name > Key Name: RsAEncryptedSessionSecurityTokenHandler > Deselect Protect my key file . . .
  12. Compile the code
  13. Save the dll for later use

There is one more piece of code that you must write before you can start configuring Claims. By default, ADFSv2 signs all of their messages with a SHA-256 bit key.  Windows 2003 by default doesn’t support that but you can enable it.  To do so, you have to create a console based application that calls one function. Why Microsoft didn’t include this by default is beyond me.

The console code is something like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Security.Cryptography;

namespace RegisterSHA256_Hashing
{
    class RegisterSHA256
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Going to regiter SHA-256 on this computer . . .");
            Oid2.RegisterSha2OidInformationForRsa();
            Console.WriteLine("Done . . .");
        }
    }
}

Create a new console application, code the code, compile and xcopy it to all of your Web Front End Servers.

PHEW! Finally, we are not ready to install and configure Claims-Based authentication. Each of the steps below need to be run on each SharePoint web front end server so do one then rinse and repeat.

Install Windows Identity Foundation Client

  1. Get the appropriate WIF client for your platform from http://www.microsoft.com/downloads/details.aspx?FamilyID=be4db6a0-b76d-446d-810c-ea3c25b3969a&displaylang=en#filelist
  2. Run the downloaded exe
  3. Next > Accept EULA > Finish

Install Federation Extensions for SharePoint 3.0

  1. Download Microsoft-Federation-Extensions-For-SharePoint3.0.msi from http://www.microsoft.com/downloads/details.aspx?FamilyID=8e7b6d99-991e-44fc-a74e-9adb152ddc37
  2. Run the downloaded MSI
  3. Agree to EULA > Install

Register SHA256

  1. Copy the RegisterSH256_Hashing command line application to the server created earlier
  2. Double click on the icon

RSA Cookie Transform Library

  1. Copy the RSACookieTransformLibrary.dll to the GAC
  2. Note the Public Key Token

Federation Utility for SharePoint 3.0

  1. Run the Federation Utility from the Start Menu
  2. Select Browse > Select the web.config file for the Central Administration ( C:\inetpub\wwwroot\wss\VirtualDirectories\%SiteId\web.conifg )
  3. If this server is not hosting the Central Administration Web Site, select the web.config for the extended Web Application’s default zone
  4. Next
  5. Application Configuration Location > Browse > Select the web.config for the extended application create way up in the Prerequisites
  6. Application URL : Enter the Url of the Extended Web Application
  7. SharePoint Security Zone : Internet or Extranet depending on how the Web Application was configured
  8. Select Cookie Expiration
  9. Enter your STS location in the form of something similar to https://sts.example.com/FederationMetadata/2007-06/FederationMetadata.xml
  10. Click Test Location to confirm.
  11. Select ‘Schedule a task to perform daily …’ then Next. This will contact the STS server for any updates to its configuration
  12. Enable certificate chain if this is for production, otherwise leave this as the default > Next
  13. Select ‘No Encryption’ if using SSL > Next > Next > Finish
  14. Enter a password of the user account to run your scheduled task. This is just a standard Windows Task so it can be updated later

Last Steps

  1. Allow your application pool account for the web application access to the certificate key store. You do this by using winhttpcertcfg as such – cmd.exe /c Winhttpcertcfg -g -A Example\$appPoolAccount -c LOCAL_MACHINE\My -s $subject_of_certificate
  2. Add  the following  to the <Microsoft.IdentityModel><service> section of Web.config file of the extended web application
  3. <securityTokenHandlers>
    <remove type="Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <add type="RsaCookieTransform.RsaEncryptedSessionSecurityTokenHandler, RsaCookieTransformLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=&lt;tobefilledin>" />
    </securityTokenHandlers>
    • Replace <tobefilledin> with Public Key Token copied that you copied when you installed the dll to the GAC

    After all that, you can now follow the Step-by-Step guide. The guide will walk you through how to add users from the accounts domain to your SharePoint site. Typically this is done by using an email address.  Once you get everything setup, its pretty sweet. Its just a long and winding road to get that.

     

    Common Errors

    One last thing before I wrap up.  There were a few errors that I encountered when installing this that I wanted to post with my solutions to assist others as they work their way through this.

    1. Error ID2002. Stsadm failed – I received this when I ran the Federation Utility on my second WFE.  This is because the Provisioning timer job wasn’t deleted after the utility ran on the first WFE.  The solution was to use the Central Administration to delete the ‘Provisioning Web Application timer job’ before running the utility on the second WFE
    2. Unexpected Error has occurred – [CryptographicException: The system cannot find the file specified.]. I received this error before I ran the winhttpcertcfg utility.  This is due to the AppPool service account not being able to load its profile. It needs its profile loaded so it can read the certificate store so that it can encrypt/decrypt/hash messages back and forth to ADFS
    3. Failed to Execute URL System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.BeginExecuteUrl(String url, String method, String childHeaders, Boolean sendHeaders – This was a nasty error that took me a while to figure out the cause. There isn’t a lot of information on the Internet concerning this error and what little is out there, mainly concerns either IIS7 or a custom ASP.NET application. Turns out this error doesn’t have anything to do with your SharePoint setup. At least in my cause it was because ADFS was mapping claims from the account domain to unused roles in our resource domain. After we went back to the Step-By-Step guide and followed their ADFS setups it fixed our last issue.
    Categories: iis, SharePoint, windows

    MSDeploy with IIS6

    March 21, 2010 1 comment

    One of the most common tasks an IIS admin can do (besides installing IIS and who really is still doing that if you’re doing virtualization) is to deploy code given to us by the developers.  In the olden days, this wasn’t too hard. You where given a batch file or maybe an MSI and you ran it on the one server that supported the applications.  But now, most applications have 2,3 or more servers that need to be worked on.  I’m a lazy admin. I hate doing things more than once so I was always looking for a way to sync multiple IIS servers. For a long time if you were using MS technologies, you had to either use nant or roll your own solution.  Some continued to use AppCenter 2000 but that’s a decade old!  Enter msdeploy.

    I know that there are a lot of other blog posts out there on the Internet concerning Microsoft’s new deployment tool called Msdeploy, but most concern how it can be used with IIS7 applications. This isn’t surprising since it was really made for IIS7 and only really intended to interact with IIS6 so that you can migrate from IIS6 to IIS7. Well, it does a great job of synchronizing IIS6 applications as well!

    All that you need to do is install MSdeploy on each server, enable the remote service – net start msdepsv – and simple command line like this:

    • msdeploy -verb:sync -source:metakey=lm/w3svc/1 -dest:metakey=lm/w3svc/1,computername=Server1

    This will sync the files, AppPools, and IIS settings for your application. You can see all dependencies that will be sync via:

    • msdeploy.exe -verb:getDependencies,alltrigger -source:metakey=lm/w3svc/1

    This is awesome stuff but there is one thing that was always missing from the list of dependencies for my applications.  And that was my GACed DLLs.  There isn’t a way for msdeploy to know if a assembly in the GAC is used by your application or not automatically.  The good thing is that Microsoft does give you the ability to sync GACed DLLs by running the following two commands:

    • msdeploy -verb:dump -source:gacAssembly="MyTestAssembly"
    • msdeploy -verb:sync -source:gacassembly="MyTestAssembly" -dest:metakey=lm/w3svc/1,computername=Server1

    Again great stuff but it kind of sucks that you have to run two or more commands to sync your application if you have GACed DLLs. Never fear because Microsoft has thought of this as well.  What you need to do is to create a XML file that describes your application. In it, you can include everything that you want to sync – files, IIS6 metadata settings, GACed assemblies, etc . . . Then you just have to tell MSdeply to use that file as input and you’re done!

    For example, MyApplication has been created on the Web Site #885762418 pointing to D:\Inetpub\myapplicationroot for its file location. It also has two dlls that it needs located in the GAC.  Then the XML would look like this:

    <MyApplication>
      <metakey path="lm/w3svc/885762418" />
      <dirPath path="D:\Inetpub\myapplicationroot" />
      <gacAssembly path=’System.Web, Version=2.0.0.0, Culture=neutral, processorArchitecture=x86, PublicKeyToken=b03f5f7f11d50a3a’ />
      <gacAssembly path=’JPMCCommonServices, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL, PublicKeyToken=405319ba8665dd1a’ />
    </MyApplication>

    And the command to deploy this application would be

    • msdeploy.exe -verb:sync -source:manifest=custom.xml -dest:manifest=custom.xml,computername=Server1

    I know that some people have strong opinions about XML but in this case it is very easy to use and makes our job as IT admins much simpler so we can focus on the other things that make our jobs challenging and fun.

    Categories: iis, msdeploy, windows

    Compare Two Directories with Powershell

    February 17, 2010 Leave a comment

    Have you ever been tasked to compare two or more directories on different systems to ensure that they are the same?  This seems to come up all too often in my job – I’m afraid to find out why . . .  Most people will compare directories by looking at files and their modified date or byte sizes.  And this works very well. I also know that there are a lot of tools/applications that already do this, but they either cost money or not approved by my company. So the path of least resistance is to write my own and using a SHA-1 hash as the basis of comparison.

    A little review. A hash is a cryptographically unique value of a document. In other words, every document, text, or otherwise produces a unique hash that can be computed again and again. This fact is can be utilized in comparing two different files for uniqueness.  Hashes are used every day.  For example, our passwords for applications we use online are not stored in the clear but rather hashed (or at least they should be).

    So our first step in this quick and dirty script is to write a function to get a hash on any given file.  I found a lot of this code via Google and converting some C# code over to Powershell. The function basically opens the file, computes the hash of given type (in this case SHA-1), and then strips out any -

    function get-hash {
    param (
    [string] $file = $(throw 'a filename is required'),
    [string] $algorithm = "sha256"
    )

    $fileStream = [system.io.file]::openread((resolve-path $file))
    $hasher = [System.Security.Cryptography.HashAlgorithm]::create($algorithm)
    $hash = $hasher.ComputeHash($fileStream)
    $fileStream.Close()

    return ( ([system.bitconverter]::tostring($hash)).Replace("-") )

    }

    Now that we know how to get a hash on one file, we’ll have to get the hashes of all files in a directory and sub-directories.  We’ll store it in an object array which can be used by compare-object later on.  Notice the call to get-hash with an algorithm of sha1. PsIsContainer –eq $false means to skip over directory names.

    function get-DirHash(){
    begin {
    $ErrorActionPreference = "silentlycontinue"
    }
    process {
    dir -Recurse $_ | where { $_.PsIsContainer -eq $false } | select Name,DirectoryName,@{Name="SHA1 Hash"; Expression={get-hash $_.FullName -algorithm "sha1"}}
    }
    end {
    }
    }

    Now the easy part.  We store the object array in two different arrays for the two different directories and then call compare-object to do the comparison.  The flag –SyncWindow can also be used.


    Compare-Object $($src | get-DirHash) $($dst | get-DirHash) -property @("Name","SHA1 Hash") -includeEqual

    This gives a complete script of:
    param (
    [string] $src,
    [string] $dst
    )

    function get-DirHash(){
    begin {
    $ErrorActionPreference = “silentlycontinue”
    }
    process {
    dir -Recurse $_ | where { $_.PsIsContainer -eq $false } | select Name,DirectoryName,@{Name=”SHA1 Hash”; Expression={get-hash $_.FullName -algorithm “sha1″ }}
    }
    end {
    }
    }

    function get-hash {
    param(
    [string] $file = $(throw ‘a filename is required’),
    [string] $algorithm = ‘sha256′
    )

    $fileStream = [system.io.file]::openread((resolve-path $file))
    $hasher = [System.Security.Cryptography.HashAlgorithm]::create($algorithm)
    $hash = $hasher.ComputeHash($fileStream)
    $fileStream.Close()

    return ( ([system.bitconverter]::tostring($hash)).Replace(“-”) )

    }

    Compare-Object $($src | get-DirHash) $($dst | get-DirHash) -property @(“Name”,”SHA1 Hash”) -includeEqual

    The output looks something like the following:


    C:\Data\E148884\Code\PowerShell\powershell.exe .\compare_directories.ps1 c:\temp\REF c:\temp\DST

    Name SHA1 Hash SideIndicator
    ---- --------- -------------
    deploy-sharepoint.bat 85B5967389E5FA4BDA698AA2FA9889685B7B1CA0 ==
    gacutil.exe ACBB2E6BEC6DBA8BA3E7E743A5CDC22D57CC6AD4 ==
    deploy-metastorm.bat F83BFB947F8970B76115E4E0B4E5CB20DE54719 =<
    deploy-metastorm.bat 3BB7DB50F3FEA06976C7076DD0D30585B0F702DB ;

    And there you go. Another quick script that is very useful to administrators.

    Categories: Uncategorized

    SharePoint Trending with Google APIs

    November 8, 2009 9 comments

    At my day job, I manager a fairly large SharePoint deployment. We currently have about 450GB of content spread across 6-7 content databases. Needlessly to say, because SharePoint stores all of its information inside SQL Server database and Microsoft’s recommendation for no larger than 100GB content databases, trending our growth is very important to our team. For a while, we have been taking snapshots of the content database’s size, storing the information in Excel and generating Pivot table and charts. This worked fine but I wanted better. I’ve always liked the way Google’s Finance pages looked so I was excited to learn that you can use those same APIs in your own site. I think I’ve come up with a pretty neat solution by utilizing the SharePoint object model ,PowerShell, a little jQuery, Google’s APIs and an awesome course from EndUserSharepoint (Url – http://www.endusersharepoint.com, Twitter – @ESUP) . I’m always open for suggestions or improvements so after you read my posting, please let me know what you think.

    Enough chit chat. Let’s get into how this works. To get this working for you, you’ll need three things:

    1. A SharePoint List to store the size of the SharePoint databases
    2. A PowerShell script to populate the list on a nightly basis
    3. A Web Part page with a Content Editor Web part + jQuery and the SharePoint List to generate the graph

    SharePoint List

    This easiest thing to create. Its just a custom SharePoint list with the following columns.

    • Web Application – the name of the SharePoint web application. I typically rename the default Name field.
    • Database Name – the name of the of the Content Database.
    • Database Size – a number field that will store the size of the database. The one thing that I do not like about the number field is that it inserts commas into the number. I debated about making this a string field but I decided to just handle this with a little jQuery
    • Date – this will hold the date the database snapshot was taken. I give it a default value of today’s date and only select date, not date/time.

    A couple other things to note about the list:

    1. You will need to grant your SharePoint farm account contribute access to the list. This is because the PowerShell script will run as the Farm account. In a locked down environment like mine the only account that can access the databases is the Farm account.
    2. To keep the list from growing too large, I setup an IRM policy to delete a list item 90 days after the item is created. This keeps my list nice and trim automatically.

    PowerShell Script

    The PowerShell script utilizes the SharePoint object model so it has to run on one of the SharePoint servers in your farm. I choose my Central Admin server but it can be any server in the farm. The idea of the script to is to loop through every Web Application and gather the size of each Content Database associated with it and then upload the information to the SharePoint list. Its pretty straight forward except for one issue with SharePoint Content Database names when working with PowerShell. This discussion thread goes into good detail on how to get around it – http://groups.google.com/group/microsoft.public.windows.powershell/browse_thread/thread/16c06d92b2385325.

       1: . ..\SharePointFunctions.ps1

       2:

       3: #Powershell had an issue with the SPContentDatabase assembly function Name and DiskSizeRequired. This is a work around

       4: #See http://groups.google.com/group/microsoft.public.windows.powershell/browse_thread/thread/16c06d92b2385325 for more information 

       5: $nameMethod = [Microsoft.Sharepoint.Administration.SPContentDatabase].getMethod("get_Name")

       6: $diskMethod = [Microsoft.Sharepoint.Administration.SPContentDatabase].getMethod("get_DiskSizeRequired")

       7:

       8: set-variable -option constant -name TrendingList -value "Trending-SPDatabase"

       9: set-variable -option constant -name TrendingSite  -value "http://tis-collaboration.jpmchase.net/ti/shareddotnet"

      10: set-variable -option constant -name WebApplication  -value "Web Application"

      11: set-variable -option constant -name DatabaseName -value "Database Name"

      12: set-variable -option constant -name DatabaseSize  -value "Database Size (MB)"

      13:

      14: $MB = 1024*1024

      15:

      16: #Function main - Where all of the fun is

      17: function main() {

      18:

      19:     #Loop through all WebApplications

      20:     get-SPWebApplications -name * | % {

      21:

      22:         #Don't need to display information on the Central Admin site

      23:         if( -not $_.IsAdministrationWebApplication ) {

      24:

      25:             $strWebApp = $_.Name.TrimStart()

      26:

      27:             #Display information about the content database attached to this WebApp

      28:             $ContentDatabaseCollection = $_.ContentDatabases

      29:

      30:             $ContentDatabaseCollection | % {

      31:

      32:                 $newlistitem  = @{}

      33:                 $newlistitem[$WebApplication] = $strWebApp

      34:                 $newlistitem[$DatabaseName] = $nameMethod.Invoke($_, "instance,public", $null, $null, $null)

      35:                 $newlistitem[$DatabaseSize] = [math]::round( ($diskMethod.Invoke($_, "instance,public", $null, $null, $null) / $MB), 0)

      36:

      37:                 add-toSpList -url $TrendingSite -list $TrendingList -entry $newlistitem

      38:

      39:             }

      40:         }

      41:     }

      42:

      43: }

      44: main

    The variables TrendingSite, TrendingList, WebApplication, DatabaseName, DatabaseSize will need to be updated for your environment.

    The function get-SPWebApplication will return a list Web Application objects. You can limit the list to a specific Web Application by replacing “–name *” with “–name $name_of_web_application”

       1: function get-SPWebApplication( [string] $name )

       2: {

       3:     $WebServiceCollection = new-object microsoft.sharepoint.administration.SpWebServiceCollection( get-SPFarm )

       4:     $WebServiceCollection | % { $WebApplications += $_.WebApplications }

       5:

       6:     return ( $webApplications | where { $_.Name.ToLower() -like "*"+$name.ToLower()+"*" } | select -Unique )

       7: }

       8:

       9: function get-SPFarm()

      10: {

      11:     return [microsoft.sharepoint.administration.spfarm]::local

      12: }

    To add the information to the SharePoint List, we have to pass a hash table with name/value pairs to the function add-toSpList. We also have to pass the URL of the Site that hosts the list and the List name.

       1:

       2: function add-toSpList ( [Object] $url, [string] $list, [HashTable] $entry)

       3: {

       4:     if( $url.GetType().Name -eq "String")

       5:     {

       6:         $site = new-object Microsoft.SharePoint.SPSite($url)

       7:         $web = $site.OpenWeb()

       8:     }else

       9:     {

      10:         $web = $url

      11:     }

      12:

      13:     $splist = $web.Lists[$list]

      14:     $newitem = $splist.items.Add()

      15:

      16:     $entry.Keys.GetEnumerator() | % {

      17:         $newitem[$_] = $entry[$_]

      18:     }

      19:

      20:     $newitem.update()

      21:     $web.Dispose()

      22:     $site.Dispose()

      23: }

    Now that we have to entire script, all you have to do is schedule it to run as often as you wish via the Windows Scheduler. Make sure you run the script as the SharePoint Farm Admin.

    SharePoint WebPart Page + jQuery

    Now the fun begins. I owe a ton of thanks to the EndUserSharepoint.com team as I used a lot of their work as a basis for what I’m trying to do. First, what you need to do is add a Web Part page to your site. On this page, add a Content Editor Web Part and the SharePoint List that you created earlier. For the list, I filtered the view to only display one database name. I also only selected he database name, size, and date columns. If I have more than one database (or web application) then I will need to create a page for each. The view should look something like this:

    Next you have to get jQuery working with your site, and this means adding code to the Content Editor Web Part. I would suggest heading over to EndUserSharepoint.com (http://www.endusersharepoint.com/?s=jquery+for+everyone) for more information on jQuery, but basically jQuery is a collection of JavaScript functions and objects that make JavaScript coding a lot easier. You need to load the jQuery engine and thankfully Google hosts it for you. All you need to do is link to their URL in your code. This is what I done for this to work. Google also hosts the visualization APIs that we need to generate the graph. If you want to learn more about the available APIs and samples on how to use them, head over to http://code.google.com/apis/visualization/

    The code for the Content Editor Web Part + jQuery is as follows: (PS: This has to be added via the CEWP’s source button, not the Rich Text Editor.)

       1: <script type="text/javascript" src="https://www.google.com/jsapi"></script>

       2:

       3: <script type="text/javascript">

       4:     google.load('visualization', '1', {packages: ['annotatedtimeline']});

       5:     function drawVisualization() {

       6:       var dataList = $("td.ms-vb2 div");

       7:       var dateList = $("td.ms-vb2 nobr");

       8:       var dateArray = new Array();

       9:

      10:       $.each(dateList, function(i,e)

      11:       {

      12:         var y = $(e).text();

      13:         dateArray[i] = y;

      14:       });

      15:

      16:       var data = new google.visualization.DataTable();

      17:       data.addColumn('date', 'Date');

      18:       data.addColumn('number', 'Size');

      19:       data.addRows(dataList.length);

      20:

      21:       $.each(dataList, function(i,e)

      22:       {

      23:          var x= $(e).text().replace(",","");

      24:          data.setValue(i, 0, new Date(dateArray[i]) );

      25:          data.setValue(i, 1, parseInt(x * 1048576) );

      26:       });

      27:

      28:       var annotatedtimeline = new google.visualization.AnnotatedTimeLine(document.getElementById('trending'));

      29:       annotatedtimeline.draw(data, {'displayAnnotations': true});

      30:     }

      31:

      32:     google.setOnLoadCallback(drawVisualization);

      33:

      34: </script>

      35: <div id="trending" style="width: 100%; height: 400px;"></div>

    Well there you go. Once you have everything in place you should have a page the looks similar to this:

    I hope that everyone has enjoyed this post and I always look forward to any feedback.

    Categories: Uncategorized

    Time zone Clocks with SharePoint using jQuery

    October 16, 2009 1 comment

    I work with a lot people who are spread across the global so we are always trying to find out what is their local time. While Google has a great query that will convert time for you, I wanted to see if I could create a SharePoint page that will list the times in all the zones that we have people on the team. I found a great blog post on ‘Path to Sharepoint’ (http://pathtosharepoint.wordpress.com/2009/01/09/world-clock/) did exactly what I wanted. The one catch was that he used a lot of JavaScript to convert the calculated text column to HTML. I wondered if jQuery could make it easier. This is what I came up with . . .

      1: <script type="text/javascript" src="http://www.google.com/jsapi"></script>
      2: <script type="text/javascript">
      3:     //load jQuery
      4:     google.load("jquery", "1.3.2");
      5: </script>
      6:
      7: <script type="text/javascript">
      8: $(function() {
      9:     $("td.ms-stylebody:contains('DIV')").each(function(){
     10:         $(this).html($(this).text());
     11:     });
     12: });
     13: </script>

    There are a couple requirements for this to work.

    1. The list view was set to boxed.
    2. The calculated column had this equation:
    3. ="<DIV id='calchtml'><embed src='http://www.clocklink.com/clocks/5001-blue.swf?TimeZone="&TimeZone&"'
      width='250' height='70' wmode='transparent' type='application/x-shockwave-flash'></DIV>"

    If you follow the instructions at ‘Path to SharePoint’ and use this jQuery you should get something like this:

    Categories: Uncategorized

    Powershell Script to Create Sharepoint Web Application

    April 10, 2008 Leave a comment

    Microsoft Sharepoint 2007 has a very nice web-based UI to create Web Applications, but there is one catch. The UI creates the backend database on the fly. In a lot of companies, this is the role of a DBA, and only they are allowed to create a new database. In a way this makes sense due to the fact that the DBAs must maintain the intergity of the database server. Microsoft has provided a switch within the stsadm command to create a new Web Application with an existing database, but I thought I could come up with a way to do it using Powersell.

    What I wanted to do was to supply a script with an XML configuration that would create 1-N Web Applications with 1-N Sites. The XML looks like the following:

    <Sharepoint>
    <WebApplication name=”Test Site #1″ hostheader=”http://portal.example.net”>
    <AppPoolName>WebApp-Portal</AppPoolName>
    <AppPoolUser>Domain\myServiceAccount</AppPoolUser>
    <AppPoolPass>test1235</AppPoolPass>
    <Port>80</Port>
    <DatabaseServer>DBS-SERVER-NAME\MOSS</DatabaseServer>
    <DatabaseName>WSS_Content_Potal</DatabaseName>
    <RootDirectory>d:\inetpub\wwwroot\wss\portal</RootDirectory>
    <Sites>
    <Site Path=”/”>
    <Title>Root Site</Title>
    <Description>Root Site</Description>
    <Type>STS#1</Type>
    <AdminAccount>DOMAIN\Administrator</AdminAccount>
    <AdminName>Administrator1</AdminName>
    <AdminEmail>root@jexample.net</AdminEmail>
    </Site>
    </Sites>
    </WebApplication>
    <WebApplication></WebApplication>
    </Sharepoint>

    The first thing that needs to be done is load the Sharepoint .NET assembly and attach to the local farm

    [void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
    $farm = [microsoft.sharepoint.administration.spfarm]::local

    Then load the XML configuration file and loop through all Web Applications.

    function main()
    {

    $moss = “Sharepoint”
    $cfg = [xml](gc $cfgFile)

    if( $? -eq $false ) {
    Write-Host “Could not cleanly parase XML file. Exiting . . .”
    return $false
    }

    Write-Host “Found Sharepoint Farm on Local Host . . “

    Write-Host “Using $cfgFile file . . .”

    $cfg.$moss.WebApplication | % {

    createWebApp( $_ )

    }
    }

    main

    Surprisingly to create new Web Application, all you need to do is create a Powershell object of type SPWebApplicationBuilder, assign the proper variables, create and then provision. The command can take up to 10 minutes to complete so be patient.

    function createWebApp( [object] $cfg )
    {
    $webAppBuilder = $nul
    $webAppBuilder = new-object _
    microsoft.sharepoint.administration.SPWebApplicationBuilder($farm)

    $secureString = ConvertTo-SecureString $cfg.AppPoolPass -asPlainText -force

    $webAppBuilder.Port = $cfg.port
    $webAppBuilder.ApplicationPoolId = $cfg.AppPoolName
    $webAppBuilder.ApplicationPoolUsername = $cfg.AppPoolUser
    $webAppBuilder.ApplicationPoolPassword = $secureString

    $webAppBuilder.HostHeader = $cfg.hostheader
    $webAppBuilder.ServerComment = $cfg.name
    $webAppBuilder.DatabaseServer = $cfg.DatabaseServer
    $webAppBuilder.DatabaseName = $cfg.DatabaseName
    $webAppBuilder.RootDirectory = $cfg.RootDirectory

    if( $cfg.AllowAnonymous.ToString().ToLower() -eq “true” ) {
    $webAppBuilder.AllowAnonymousAccess = $true
    }

    Write-Host “Will now Provision this Web Application.”
    Write-Host “This may take up to 10 minutes. . .”
    $webApp = $webAppBuilder.Create()
    $webApp.Provision()

    Finally, loop through all Sites that are listed in the XML and add them to the Web Application.

    $cfg.Sites.Site | % {
    $title = $_.SiteTitle.ToString()
    $path = $_.Path.ToString()

    rite-Host “Will now Provision Site – $title ($path). “
    Write-Host “This may take up to 10 minutes. . .”

    $webApp.Sites.Add( $_.Path,
    $_.Title,
    $_.Description,
    1033,
    $_.Type,
    $_.AdminAccount,
    $_.AdminName,
    $_.AdminEmail)
    }

    See easy as 1, 2, 3 . . .

    Categories: Uncategorized

    Powershell Scriptblocks

    February 11, 2008 Leave a comment

    One of the interesting features that is, I believe, little know in Powershell is the scriptblock. What is a scriptblock? The way that I define it is a function or block of code that is assigned to a variable. Why do you need to know about this? I’ve found it most useful when using Powershell to create a GUI. You have to assign an action to an element on the GUI (like a Button). But the action can not be a function. It must be a script block. You can define the block as a variable or define it within the {} of the Add_Click method of the System.Windows.Forms.Button object.

    Now I’m probably completely wrong with this, and if I am I would love to learn more about it. So please let me know! I want to cover how to create GUIs in Powershell in couple weeks so I will be building off this blog post.

    So how do you create a Script block. Its easy as assigning a variable to a anything within {}.

    A simple case would be something like

    PS C:\temp> $x = { Write-Host “Hello, World!” }

    PS C:\temp> $x.GetType()

    IsPublic IsSerial Name BaseType
    ——– ——– —- ——–
    True False ScriptBlock System.Object

    If you just call the variable, it will return the block definition

    PS C:\temp> $x
    Write-Host “Hello, World!”

    To invoke the scriptblock, you need to call the Inovke() method of the script

    PS C:\temp> $x.Invoke()
    Hello, World!

    Within the scriptblock, you can do whatever you want to do. It can be multiple lines, you can even call functions from within the block. For example:

    PS C:\temp> function y () {
    >> Write-Host “Within function y”
    >> }
    >>
    PS C:\temp> y
    Within function y
    PS C:\temp> $x = {
    >> Write-Host “Within scriptblock x”
    >> y
    >> }
    >>
    PS C:\temp> $x.Invoke()
    Within scriptblock x
    Within function y

    Here are all of the methods that Scriptblocks provides within Powershell

    PS C:\temp> $x | Get-Member

    TypeName: System.Management.Automation.ScriptBlock

    Name MemberType Definition
    —- ———- ———-
    Equals Method System.Boolean Equals(Object obj)
    GetHashCode Method System.Int32 GetHashCode()
    GetType Method System.Type GetType()
    get_IsFilter Method System.Boolean get_IsFilter()
    Invoke Method System.Collections.ObjectModel.Collection`1[[System.Management.Automation.PSObject, Syst...
    InvokeReturnAsIs Method System.Object InvokeReturnAsIs(Params Object[] args)
    set_IsFilter Method System.Void set_IsFilter(Boolean value)
    ToString Method System.String ToString()
    IsFilter Property System.Boolean IsFilter {get;set;}

    I hope this gives you an introduction into scriptblocks. Next time, hopefully, we can cover the TCL/TK-like feature of Powershell – its GUI.

    Categories: Uncategorized

    Q&D Ping Function for Powershell

    January 16, 2008 Leave a comment

    By default, Powershell does not have any built in functionality to send an ICMP ping to see if a remote computer is alive on and on the network. But never fear because Powershell is based off .NET. This means it is very easy to implement a Ping function that you can add to a Powershell library file (along with other functions that I have blogged about previously). The function is pretty straight forward. All that you really new to do is to create two .NET objects – Ping and PingReply. My ping function only looks to see if a success was returned by ICMP. I am not looking for round trip time or to handle non-successful.

    function Ping (  [string] $strComputer ){  $timeout=120;  trap { continue; }
    
      $ping = new-object System.Net.NetworkInformation.Ping   $reply = new-object System.Net.NetworkInformation.PingReply
    
      $reply = $ping.Send($strComputer, $timeout);  if( $reply.Status -eq "Success"  )   {     return $true;  }  return $false;
    
    }

    Again that’s it. The trap command will just ignore any errors that are throw by the $ping.Send command. If anyone has questions than you can always email me at brian@bjd145.org.

    Categories: Uncategorized

    Powershell and XML Configuration Files

    January 7, 2008 Leave a comment

     

    One of the things that I almost always create when I am developing a script is a configuration file. Utilizing XML for a configuration file format is very easy with Powershell.  The first thing that you need to do is to layout your XML file. I typically don’t create a DTD or verify the XML schema because well, only my scripts will be using the XML configuration file.  Not completely within spec, but I’ve learn to live with it. The XML does need to be well formed with proper closing brackets, root node, etc in order for Powershell to read the XML but that is the only restriction.

    The most common XML file that I create includes a list of servers and some attribute about those servers. A simple  example that of a test application that is made up of three web servers and a database server. The way that I would create the XML would be as follows:

    <test_app_servers>
        <dbs server=”vm-dbs1″ dbsname=”eut”/>
        <web dir=”d$\inetpub\wwwroot”>
            <server>vm-test1</server>
            <server>vm-test2</server>
            <server>vm-test3</server>
        </web></test_app_servers>

    Now the important part, how does Powershell read the XML.  The code is very straight forward. You use the get-content command and cast the file as XML.  The command is:

    $cfgFile = “.\test_app_config.xml”
    $root = “test_app_servers”
    $cfg = [xml] ( gc $cfgFile )

    Now once you have the configuration saved in the variable $cfg then how do you use it?  Powershell stores the information in a tree format so it is easy to get at. Some samples of how to get at the data include:

    $strDbsName = $cfg.$root.dbs.dbsname

    $strDbsServer = $cfg.$root.dbs.server

    $strWebDir = $cfg.$root.web.dir

    $cfg.$root.web.server | % {
            $strWebServer = $_
            “Content of
    \\$strWebServer\$strWebDir
            dir
    \\$strWebServer\$strWebDir

    }

    And that is all you should need to know in order to utilize XML as a configuration file with Powershell

    Categories: powershell, windows
    Follow

    Get every new post delivered to your Inbox.