Using IronPython with MOSS 2007

Posted April 13th, 2010 in General, Microsoft, Python by ryan

I’ve been working on a project that interacts with Microsoft Office SharePoint Server 2007 (MOSS 2007) for the last few months and one of the tools I’ve been using daily to support my work is IronPython. IronPython has made it easy for me to come up to speed quickly on the MOSS 2007 API but what has made my life even easier is the IronPython Console.

*Note: If you have a browser that supports Silverlight, you can try Python in your browser now.

IronPython ships with a console virtually identical to the stand Python console. The IronPython console provides me with a constant live connection directly to the API. It’s very different and somewhat empowering to transition from the standard workflow in Visual Studio of write code/build/run to something more like a conversation with the code. I think the term conversation is a very good analogy because it’s not just looking at classes and methods, it’s also data and interaction. It’s experiencing everything all at once!

Let’s take a look at what I’m talking about. To run these samples, I had IronPython 2.6.1 installed on a server running Windows Server 2003 and MOSS 2007.

When you first start up the console, you need to reference the Microsoft.SharePoint .dll. You SharePoint types probably know to find this in either the 12 Hive or the GAC.

>>> import clr
>>> clr.AddReference("Microsoft.SharePoint")

We need to import the SPSite class before we use it too.

>>> from Microsoft.SharePoint import SPSite

Now we can create a connection to a site and open its default SPWeb object.

>>> site = SPSite(baseurl)
>>> web = site.OpenWeb()
>>> web

We can also navigate around the subwebs of a given web by using the Webs property. You can run into permissions issues though. Here we try to access the first subweb in the Webs collection.

>>> web.Webs[0]
Traceback (most recent call last):
File "", line 1, in
SystemError: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENI
ED))

To get around this error, we can just use the SystemAccount token attached to each site. I really don’t know the reason behind the design of this API, but you can use one site reference to give you a connection with elevated privileges on another site.

>>> temp = SPSite(baseurl)
>>> site = SPSite(baseurl, temp.SystemAccount.UserToken)
>>> web = base_site.OpenWeb()

Now you can start exploring around and seeing what exits. When you want to see
what members a given object has, you just use the dir() method. Let’s take a look at
the first object in the Lists collection.

>>> dir(base_web.Lists[0])
['AddWorkflowAssociation', 'AlertTemplate', 'AllRolesForCurrentUser', 'AllowCont
entTypes', 'AllowDeletion', 'AllowEveryoneViewItems', 'AllowMultiResponses', 'Al
lowRssFeeds', 'AnonymousPermMask', 'AnonymousPermMask64', 'Audit', 'Author', 'Ba
seTemplate', 'BaseType', 'BreakRoleInheritance', 'CanReceiveEmail', 'CheckPermis
sions', 'CheckedOutFiles', 'ContentTypes', 'ContentTypesEnabled', 'Created', 'Cu
rrentChangeToken', 'DefaultApprovalWorkflowId', 'DefaultContentApprovalWorkflowI
d', 'DefaultItemOpen', 'DefaultView', 'DefaultViewUrl', 'Delete', 'Description',
'Direction', 'DocumentTemplateUrl', 'DoesUserHavePermissions', 'DraftVersionVis
ibility', 'EffectiveBasePermissions', 'EffectiveFolderPermissions', 'EmailAlias'
, 'EmailInsertsFolder', 'EnableAssignToEmail', 'EnableAttachments', 'EnableDeplo
yWithDependentList', 'EnableDeployingList', 'EnableFolderCreation', 'EnableMinor
Versions', 'EnableModeration', 'EnableSchemaCaching', 'EnableSyndication', 'Enab
leVersioning', 'EnsurePropsFresh', 'EnsureRssSettings', 'Equals', 'EventReceiver
s', 'EventSinkAssembly', 'EventSinkClass', 'EventSinkData', 'ExcludeFromTemplate
', 'Fields', 'FirstUniqueAncestor', 'Folders', 'ForceCheckout', 'Forms', 'GetCha
nges', 'GetContentTypeIdByUrl', 'GetDefaultViewForContentType', 'GetDirectChildC
ontentType', 'GetDistinctFieldValues', 'GetHashCode', 'GetItemById', 'GetItemByU
niqueId', 'GetItems', 'GetItemsInFolder', 'GetPropertiesXmlForUncustomizedViews'
, 'GetType', 'GetUncustomizedViewByBaseViewId', 'GetView', 'HasUniqueRoleAssignm
ents', 'Hidden', 'ID', 'ImageUrl', 'IrmEnabled', 'IrmExpire', 'IrmReject', 'IsCa
talog', 'IsContentTypeAllowed', 'ItemCount', 'Items', 'LastItemDeletedDate', 'La
stItemModifiedDate', 'Lists', 'MajorVersionLimit', 'MajorWithMinorVersionsLimit'
, 'MemberwiseClone', 'MobileDefaultViewUrl', 'MultipleDataList', 'NoCrawl', 'OnQ
uickLaunch', 'Ordered', 'ParentWeb', 'ParentWebUrl', 'Permissions', 'PropertiesX
ml', 'ReadSecurity', 'Recycle', 'ReferenceEquals', 'RemoveWorkflowAssociation',
'RenderAsHtml', 'RequestAccessEnabled', 'ResetRoleInheritance', 'RestrictedTempl
ateList', 'ReusableAcl', 'RoleAssignments', 'RootFolder', 'SaveAsTemplate', 'Sch
emaXml', 'SendToLocationName', 'SendToLocationUrl', 'ServerRelativeDocumentTempl
ateUrl', 'ServerTemplateCanCreateFolders', 'ServerTemplateCanReceiveEmail', 'Set
AttributesForPropertiesXML', 'ShowUser', 'TemplateFeatureId', 'Title', 'ToString
', 'Update', 'UpdateWorkflowAssociation', 'Version', 'Views', 'WorkflowAssociati
ons', 'WriteRssFeed', 'WriteSecurity', '__class__', '__delattr__', '__doc__', '_
_format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclas
shook__', 'm_ListAttributesDict', 'm_Lists', 'm_Permissions', 'm_arrListProps',
'm_iRow']

Now this may or may not be readable to you. Alot of times when there’s a ton of text to deal with in the console, I’ll iterate through the methods and print them each on their own line.

>>> for method in dir(base_web.Lists[0]):
...     print method
...
AddWorkflowAssociation
AlertTemplate
AllRolesForCurrentUser
AllowContentTypes
AllowDeletion
AllowEveryoneViewItems
.... [Omitted to save space]
__class__
__delattr__
__doc__
__format__
__getattribute__
__hash__
__init__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__
m_ListAttributesDict
m_Lists
m_Permissions
m_arrListProps
m_iRow

You can inspect classes too. You don’t need an instance. If you inspect the class you’ll just need to import the type first.

>>> for method in dir(SPListCollection):
...     print method
...
Traceback (most recent call last):
NameError: name 'SPListCollection' is not defined
>>> from Microsoft.SharePoint import SPListCollection
>>> for method in dir(SPListCollection):
...        print method
...
Add
CopyTo
... [Omitted to save space]
__add__
__class__
__delattr__
__doc__
__format__
__getattribute__
__getitem__
__hash__
__init__
__iter__
__len__
__new__
__reduce__
__reduce_ex__
__repr__
__setattr__
__sizeof__
__str__
__subclasshook__

If you’re coming from a C# or VB background, you’re probably familiar with the “Using” block. Python has something similar to that with the “with” statement. The with statement is used with ContextManagers. Many of the .Net framework classes support the ContextManager methods so you can use the with statement. You can see the __enter__ and __exit__ methods below that help make this possible.

>>> dir(SPSite)
['AddWorkItem', 'AllWebs', ...[Omitted for space], '__class__', '__delattr__', '__doc__', '__enter__
', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__new_
_', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__s
tr__', '__subclasshook__']

Now we can refactor our earlier sample to use the with statement. This is something I use more in scripts that reference MOSS 2007, but I thought you may find some uses.

>>> web = None
>>> with SPSite(baseurl) as temp:
... 	with SPSite(baseurl, temp.SystemAccount.UserToken) as site:
...			web = site.OpenWeb()
...

It’s all pretty basic and the console lends itself well to those who like to explore. I really like this method versus digging around the object browser or Reflector all of the time. I like the instant feedback when exploring and the ability to see data and not just structure. I’ve also successfully used IronPython to create custom event handlers and for some administrative tasks for a 2003 to 2007 upgrade. I highly recommend you try it if you find yourself having to do any development using the SharePoint API.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Debugging IronPython In Visual Studio

Posted December 30th, 2008 in .Net, General, Microsoft, Python by ryan

I’ve been getting to know IronPython a little lately and one of the first things I wanted to know was how to debug IronPython in an IDE.  Since I use Visual Studio 2008 at work, I thought it would be a good start.  I searched Google and found a text representation of the steps involved over at Harry Pierson’s blog.

I found it pretty simple to do and somewhat useful for longer scripts.  It will be nice in the future to have first class support for IronPython in Visual Studio 2010.

You should have IronPython 2.0 Final and Visual Studio 2008 Professional or Better* installed to complete this demo.

Create a python file to debug:

1
2
3
4
5
6
7
8
#debug.py
class Foo:
def __init__(self, name=None):
    self.name = name
 
if __name__ == "__main__":
    f = Foo("LVS")
    print f.name

From Visual Studio, open the IronPython executable (ipy.exe). If it doesn’t do so for you, add the ipy.exe as an existing project.

From the Solution Explorer, right-click on Properties and set the Command Arguments property.  Use “-D” to tell ipy.exe to create debugging output, “-i” to start an interactive session at the end of debugging and add the full path to the script you made before.

Properties Dialog

Properties Dialog

Click Ok.

Open the script you created earlier in Visual Studio and place breakpoints as desired.

Adding a Breakpoint

Adding a Breakpoint

Run the script in debug mode (F5).

If you added the “-i” argument in step 3, after the last breakpoint is released it will launch an interactive session for you.  You will be able to inspect your script at this point, much like the immediate window in Visual Studio.

Interactive Console

Interactive Console

* I tried this in the Visual Studio 2008 Team Developer Edition and the Visual Studio Express Edition.  The Express Editions do not work as they don’t allow you to open the ipy.exe as a solution item. Sorry “hobbyists”, we’ll see if the Express sku’s of Visual Studio 2010 will target IronPython / IronRuby.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Designing An Intranet With Sharepoint [External Reference]

Posted September 19th, 2008 in .Net, Microsoft, Web Design by ryan

A collegue (really a mentor) of mine knows Sharepoint like nobody’s business and she posted an interesting article this week about when moving to Sharepoint, there is a shift in the mindset how you look at and classify information.  It’s a quick point with a list of good references and I think it’s a good primer before jumping into Sharepoint.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Trying out Sinatra on Windows

Posted November 9th, 2007 in General, Linux, Microsoft, Open Source, ruby, Web Design by ryan

I saw a lot of buzz about the new Sinatra web framework and decided I’d give it a try. I have a client now that has a simple site they need up now and then I can migrate them to Rails over time. When I saw how easy Sinatra looked, I thought I could give it a chance to see what it could do.

I installed Sinatra via RubyGems:
gem install sinatra -y

After that I created a simple file following the example:

require 'rubygems'
require 'sinatra'


get '/' do
"Now we're cooking with gas"
end

But much to my dismay, nothing happened when running this on my windows box. I instantly searched Google for “Sinatra on windows” and found the Google Group for Sinatra and a post explaining that Sinatra doesn’t run on Windows yet. As I read into the thread, I found someone had some suggestions for making it work.

John Bledsoe had the following suggestions:

My humble suggestion would be to remove the FileUtils#touch from
Sinatra::Server#tail and update Environment#prepare_loggers to
something like:

def prepare_loggers(logger = nil)
if logger.nil?
FileUtils.touch(Options.log_file)
logger = Logger.new(open(Options.log_file, 'w')
end
end

Making these changes allowed Sinatra to run, but it wouldn’t server the page. Instead it returned an error:

Fri Nov 09 16:26:26 -0800 2007: ERROR: undefined method `info’ for nil:NilClass

I made a post to the group and was promptly replied to! The general advice given is that it is a rapidly emerging framework undergoing a lot of changes and to check back soon.

More on testing Sinatra in Linux coming soon….

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

EWeek attacks MSFT Open Source Initiatives

Posted August 27th, 2007 in Microsoft, Open Source by ryan

I just read an article at EWeek, and I can’t emphatically disagree more with the writer’s statements.

While it is true that there aren’t many products coming out of Redmond as true open source these days, the writer bases his assumptions on the top five projects at CodePlex. CodePlex is not the only place to find open source projects!

The writer goes on to bash a few projects as too ambitious or already done some time ago in another technology.

Number four is BlogEngine.NET. Guess what? It’s a simple blog back-end written in .Net. Wow. Let me see, if I do a search on SourceForge, a real open-source site, on blog and engine, I find 5,633 results. Oh yeah, I see a big demand out there for another blogging platform.

Then he makes this statement:

But, let’s assume that Microsoft really wanted to be open-source friendly. How about instead of flapping your lips, you release some code under your b.s. community licenses that’s actually not built from Microsoft proprietary parts, trashy example code, or is just a pointless “me too” project.

So I must not get his point. The language and platform must also be open for the project to be considered open source? And if I want something to run on a Windows Server so it will be easier to support next to the other apps I have running on Windows, with a support team that knows Windows (and not enough Linux to support production environments), and I use a version of a product that was built in C# and ASP.Net that includes the source code and a license that says I may modify and distribute such source code – that’s not open source enough?

I realize the writer has a background working in Linux and Unix environments for some big organizations, but I’m surprised he could have overlooked SubSonic, SubText, DasBlog, NAnt, NCover, NHibernate, Gentle.Net, CoolStorage.Net, ProMesh.Net, MonoRail, NChart, PostSharp, AspectSharp, .Text, NGallery, .NETZ, mojoPortal, Rainbow, log4Net, NLog, Logger.Net, SharpPDF, PDFSharp, Report.Net, SharpSSH, Lucene.Net, DotLucene, CommerStarterKit / dashCommerce, ETC, ETC ETC. I could literally list out a huge amount of projects with active or recent development and a decent following.

I think plenty of people are doing open source development using Microsoft’s platform and tools. Not all large proprietary software companies release [some/any] code under an open source license – Microsoft’s not the only one.

I’m very open to the promise of open source and developing in non-microsoft technologies and yet I don’t expect Microsoft to give me code. I don’t expect Microsoft to give me anything. If I want something for free, I go here.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Useful Error Messages

Posted July 11th, 2007 in Microsoft by ryan

Here is some output today from the command line on Windows XP. I’m not going to add a lot of commentary here, but I thought this was a little ironic / funny.
U:\>net -help
The syntax of this command is:

NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP |
HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION |
SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ]

U:\>net send -help
Sending files is no longer supported.

More help is available by typing NET HELPMSG 3777.

U:\>net helpmsg 3777

Sending files is no longer supported.


Thank you. I love redundant messages.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Stats Check

Posted June 30th, 2007 in General, Microsoft by ryan

I don’t have a lot of really technical content on this blog as of yet and have a whopping 2 subscribers according to feed burner. In the blogsphere, I am nobody. Now I do watch my stats and I have found it interesting that someone from Microsoft has been reading this blog. I’m a decent software developer, but I’m not at the level of a Microsoft developer (yet). I suspect it has to do with the fact that I have ranted slightly at Microsoft’s actions lately. I’m not getting a hit here or there. I’m talking about 11:30 P.M. on a Friday night and going through every page and every category. It doesn’t look like a bot, those usually show up in my stats in a sequential manner.

So I’m curious as to why someone at Microsoft would be checking out my blog. Since I’m obviously not some genius developer with tons of information to share, my only guess is that either someone on the night shift up there likes surfing through random and boring sludge like my blog. Another scenario could be someone working overtime for the legal department is trying to find anything picturing Microsoft in a bad light and they hit either my post about disliking Vista, or my post disagreeing with Microsoft’s tactics in dealing with a developer that increases the value in their product(s).

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Jim Losi Nominated for MVP

Posted April 12th, 2007 in .Net, Blogs I Read, Microsoft by ryan

Jim Losi, Visual Developer – Visual C# MVP Candidate 2007

For both new and experienced developers, Jim Losi has been a tremendous resource for guidance and assistance within the .Net community. Jim has assisted me personally via forum post, a code sample, a note of confidence, debugging a project, or contributing a library when needed. I have witnessed Jim help countless others on the LearnVisualStudio.Net forums as well in the same manner. Jim lives on the other side of the country from me and as such I am surprised to be able to get a hold of him in the late hours of the night and the early hours of the morning.

Jim remains steadfast in his dedication to ensure that those who ask him questions understand the answers and he encourages those individuals to continue the cycle and help each other. Jim consistently assists others in a professional and friendly manner and demonstrates a level of commitment to others rarely seen within the .Net community.

Jim has worked very hard to help many of us out in the community and has never asked for anything in return. He is a colleague, a mentor, and an example for the community at large. Jim Losi is the ideal candidate for Visual Developer – Visual C# MVP.

Jim Losi has been a great influence to me in the last year and a half and ‘m really hoping Microsoft recognizes him this year for all of his hard work. If you have a testimonial for Jim as well, please forward it to me and I’ll make sure it makes its way to Microsoft by way of Bob Tabor / LearnVisualStudio.Net.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Enter Vista

Posted February 10th, 2007 in Microsoft by ryan

I was able to fix one of the machines!  It was a simple problem.  Apparently PCI-E video cards require XP SP2 or better.  I did not have a slipstreamed XP disk and instead of making one, I just decided to install that copy of Vista I received from PowerTogether.com.

There are a few things I like thus far and several I do not.  But it’s not fair to judge after 48 hours.  I’ll give it some time and get back to you.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

PowerTogether.Com Vista Offer Validation

Posted January 24th, 2007 in .Net, Microsoft by ryan

A couple of months back, Microsoft offered free copies of Vista Business or Office 2007 for watching 3 webcasts or hosted labs through PowerTogether.com. I did my part and signed up, watched the 3 webcasts and received an email saying it would be on the way within 6 weeks of RTM.

That day came today! I received a license and media for Vista Business:

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]
FireStats icon Powered by FireStats