Jun262009

Modifying the Commerce Server 2009 Contemporary site’s site definition (Part 1)

Published by david at 10:54 AM under SharePoint 2007 | Commerce Server

While building a new site with Commerce Server 2009 SharePoint services, we wanted to redesign the site and modify a lot of pages. The problem is that for us to do that 3 solutions were possible per Microsoft’s documentation:

  1. Use the extensibility kit to edit the pages and master pages
  2. Change the necessary pages directly in the Layouts folder of that SharePoint hive
  3. Modify the pages in SharePoint designer

None of these solutions were suitable for our need and here are the reasons:

  1. I do not recommend using the extensibility kit because we need to re-sign all the assemblies with a new key and change all references to the public key token. Also, if you modify the extensibility kit, you are making it very difficult to upgrade to future versions of CS 09, unless you only add web parts or pages. Finally, the extensibility kit does not include the contemporary site, which is the one we want to keep as a basis.
  2. Changing the pages in the layouts folder is not a good idea because you basically change it for all of your sites. Of course it’s not an issue because usually there is only one CS site per machine. but still it can be an issue in a dev machine or if ever CS 09 should be used as Saas (Software as a service). Finally, this solution is not re-deployable.
  3. Modifying the pages in SharePoint is also a plausible solution but again it is not deployable and it breaks the site definition.

So, what is the solution? It is to repackage the Contemporary site SharePoint solution and adding your custom features and modified pages. The following modifications were done in MOSS and not in WSS. I’m sure it is possible in WSS though. Also, for the packaging in wsp, I’m using WspBuilder.

So, here we go:

1. Un-pack the MicrosoftCommerceMOSSDefaultSiteV2.WSP file to any folder, let’s say “C:\ContemporarySite”. Your contents should look like this:

image 

2. Now you need to restructure the features and files for WspBuilder. So essentially you would have:

Copy the following folders in 12\Templates\Features:

CommerceServerContemporarySiteCheckOutStepsInstance CommerceServerContemporarySiteImages CommerceServerContemporarySiteProvisioner CommerceServerContemporarySiteResourceDeployment CommerceServerContemporarySiteResources CommerceServerContemporarySiteSPListSampleData CommerceServerContemporarySiteXslts CommerceServerMyAccountSiteMapProvider

Copy the following folders in 12\Templates:

1033
CONTROLTEMPLATES
IMAGES
LAYOUTS
SiteTemplates

Copy the following folder in 12:
Resources
Copy the following files in the GAC folder:

Microsoft.Commerce.Portal.ContemporarySite.dll
Microsoft.Commerce.Portal.ContemporarySiteCommon.dll

 

Now that the basic structure is done, you are able to re-create the Contemporary site’s WSP solution and deploy it using Commerce Server SharePoint Services configurations tool. Before that though you will need to modify the SharePointCommerceServicesConfiguration.exe.config to take the new WSP file:

<sharePointSolutionGroup name="DefaultSiteAndWebPartsMoss" sharePointPlatform="moss" defaultInSilentMode="True">
            <sharePointSolutions>
                <sharePointSolution id="7b93b2ca-e1e4-4783-a038-14094933c002" file="MicrosoftCommerceWebParts.wsp" version="1.0.0.0" wspKey="1"/>
                <sharePointSolution id="Your solution ID Here" file="Your Solution Name Here.wsp" version="1.0.0.0" wspKey="2"/>
            </sharePointSolutions>
            <defaultWebApplicationSettings name="SharePoint - 8088" port="8088" extendedName="SharePoint - 8089" extendedPort="8089" appPoolId="SharePoint - Pool 8088" appPoolUser="domain\someone"/>
            <defaultSiteCollectionSettings create="True" title="Home" name="ContemporarySite" admin="domain\someone" template="MOSSCSContemporarySite"/>
            <defaultCommerceServerSiteSettings create="True" name="ContemporarySite" description="Commerce Server Site for Commerce SharePoint Contemporary Web Site" siteWithSampleData="False" databaseServer="."/>
</sharePointSolutionGroup>

 

Now you can use the configuration tool to deploy your site. Please be advised though that your MOSS environement needs to be clean because you are essentially redeploying the same feature as the contemporary site. Also, do not modify the name of the Contemporary Site’s site definition configuration names such as “MOSSCSContemporarySite” because the receivers look for those configurations.

In the next part of my post, I’ll show you how to modify the master pages and add new features to your site.



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

Tags: ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 3 Responses

Jun262009

SharePoint Tool Basket

Published by eric at 7:51 AM under SharePoint 2007

Belgian MVP Releases SharePoint Tool Basket on CodePlex!

Picture of SharePoint Tool Basket

MVP Stéphane Eyskens recently produced a new SharePoint project on Codeplex called “SharePoint Tool Basket”. Within two months of launch, the project has appeared in the Top 10 list of the most popular Codeplex Sharepoint projects; the tool basket is proving very popular with the SharePoint community and has already been downloaded over 5,000 times!

This project aims to re-group a number of different SharePoint tools into one single container. The tool basket offers features such as SharePoint Document Rating, Form Designer, Ajax-enabled lookup field, Content Type Explorer, Feature Explorer and Audience to Group convertor.

If you have an interest in Microsoft SharePoint, the Tool Basket is well worth investigating.

Learn more about the project and download the project bits here.



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

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Jun162009

My baby steps to PostSharp 1.0

Published by maxime at 1:11 PM under

So… you downloaded PostSharp 1.0 and you installed it and are wondering… “What’s next?”.

Well my friends, let me walk you through the first steps of PostSharp. What could we do that would be simple enough? Hummm… what about writing to a debug window? That sounds simple enough! Let’s start. So I created a new Console Application project and I added the reference to PostSharp.Laos and PostSharp.Public. As a requirement, the class must be tagged with “Serializable” attribute and implement OnMethodBoundaryAspect (not in all case but let’s start small here).

Next, I have a few methods I can override. The two that we are interested in right now is “OnEnter” and “OnExit”. Inside of it, we’ll say which method we are entering and which one we are exiting. Here are my Guinea pig classes:

public class FooBar
{
    [DebugTracer]
    public void DoFoo()
    {
        Debug.WriteLine("Doing Foo");
    }

    [DebugTracer]
    public void DoBar()
    {
        Debug.WriteLine("Doing Bar");
    } 
}

[Serializable]
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public class DebugTracer : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        Debug.WriteLine(string.Format("Entering {0}", eventArgs.Method.Name));
    }

    public override void OnExit(MethodExecutionEventArgs eventArgs)
    {
        Debug.WriteLine(string.Format("Exiting {0}", eventArgs.Method.Name));
    }
}

See how simple this is? But… does it work? Let’s see the trace of calling each methods:

Entering DoFoo
Doing Foo
Exiting DoFoo
Entering DoBar
Doing Bar
Exiting DoBar

Isn’t that wonderful? Compile execute and enjoy. But… what about the community you say? Of course if the tool is not open source there is probably nothing built around it, right? Wrong!

Here is a few resources for PostSharp that include pre-made attributes that are ready to be used:

That was everything I could find. Do you know any others?



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

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Jun162009

PostSharp – The best way to do AOP in .NET

Published by maxime at 1:10 PM under

Who knows about Aspect-Oriented Programming (AOP)? Come on! Don’t be shy! Ok, now lower your hands. My prediction is that a lot of you didn’t raise their hands. So let’s resume what AOP is:

Aspect-oriented programming is a programming paradigm that increases modularity by enabling improved separation of concerns. This entails breaking down a program into distinct parts (so called concerns, cohesive areas of functionality). […]

So what does it mean truly? Well, it’s a way to declare part of your software (methods, classes, assembly) to have a “concern” applied to them. What is a concern? Logging is one. Exception handling is another one. But… let’s go wild… what about caching, impersonation, validation (null check, bound check), are all concerns. Do you mix them with your code? Right now… you are forced to do it.

The state of current AOP

Alright for those who raised their hands earlier, what are you using for your AOP concerns? If you are using patterns and practices Policy Injection module, well, you are probably not happy. First, all your objects need to be constructed by an object builder and need to inherit from MarshalByRefObject or implement an interface.

This is not the best way but it’s been done in the “proper” way without hack.

What is PostSharp bringing?

PostSharp might be a “hack” if think so. Of course, it does require you to have it installed on your machine while compiling for it to work. But… what does PostSharp does exactly? It does what every AOP should do. Inject the code before and after the matching method at compile time. Not just PostSharp methods but any methods that is inherited from the base class PostSharp is offering you. Imagine what you could do if you could tell the compiler to inject ANY code before/after your method on ANY code you compile. Think of the possibilities. I’ll give you 2 minutes for all this information to sink in… (waiting)… got it? Start to see the possibility? All you need to do is put attributes on your methods/attributes like this:

[NotNullOrEmpty]
public string Name { get; set; }

[Minimum(0)]
public int Age { get; set; }

Now look at that code and ask yourself what it do exactly. Shouldn’t be hard. The properties won’t allow any number under “0” to be inserted inside “Age” and “Name” will not allow any null or empty string. If there is any code that try to do that, it will throw a ValidationException.

Wanna try it?

Go download PostSharp immediatly and it’s little friend ValidationAspects on Codeplex. After you have tried, try to build your own and start cleaning your code to achieve better readability.

And yes… both are Open-Source and can be used at no fee anywhere in your company.

Suggestion to CLR Team

Now, PostSharp force us to have it installed with the MSI for it to work because it needs to install a Post-Compile code injector (like some obfuscation tools). What would be really nice, is to be able to do the same thing built-in with the compiler. The compiler is already checking for some attribute already… I would love to have this “internal working” exposed to the public so that we can build better tools and, more importantly, better code.

UPDATE: I want to mention that PostSharp is NOT open-source. However is free unless you need to package it with your tool.



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

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Jun022009

How to implement “lock” with timeout?

Published by eric at 9:57 PM under C#

Anybody who did any multithreaded application probably used the “lock” keyword. This is actually a good thing.

“lock” is the most optimized way to lock a resource. First let’s take a look at what lock really do. Here is the simple Account class we will use for this post.

using System.Threading;

namespace Banking
{
    public class Account
    {
        private readonly string _accountNumber;
        private double _balance;

        private Account(string accountNumber, double amount)
        {
            _accountNumber = accountNumber;
            Balance = amount;
        }

        public string AccountNumber
        {
            get { return _accountNumber; }
        }

        public double Balance
        {
            get { return _balance; }
            set { _balance = value; }
        }

        public static Account OpenNew(string accountNumber, double amount)
        {
            return new Account(accountNumber, amount);
        }

        public void Deposit(double amount)
        {
            Interlocked.Exchange(ref _balance, _balance + amount);
        }

        public void Withdraw(double amount)
        {
            Interlocked.Exchange(ref _balance, _balance - amount);
        }

        public static void Transfer(double amount, Account fromAccount, Account toAccount)
        {
            // Bad code here. Potential deadlock.
            lock (fromAccount)
            lock (toAccount)
            {
                fromAccount.Withdraw(amount);
                toAccount.Deposit(amount);
            }
        }

        public override string ToString()
        {
            return string.Format("{0} (Balance = {1})", _accountNumber, _balance);
        }
    }
}

Here are some important things to point out about this class:

  • The constructor is private to limit the creators of this class.
  • The public OpenNew method is the only way to create an instance. This ensure that every Account starts with a name and a balance.
  • Deposit and Withdraw methods are thread safe. They both uses Interlocked class which is has low level methods to modify values.
  • Transfer is not thread safe even though it uses locks. There is a potential deadlock if two thread transfer funds using the same accounts at the same time.

Most of the time the transfer method will work without any problem but the is a slight chance of deadlock. Of course this is a fairly simple method and in fact we can use another private object field to lock on like in this sample.

private static object _syncLock = new object();

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    // Bad code here. Potential deadlock.
    lock (_syncLock)
    {
        fromAccount.Withdraw(amount);
        toAccount.Deposit(amount);
    }
}

That mean you will need to use that _syncLock object all the time to be consistent, even if you need to lock only one of the two accounts. And because Transfer is a static method we need to make the _syncLock object static too. That mean that any other call to Transfer will have to wait until this call finish. That is a huge performance issue.

What we really need is to be able to lock actual Account objects and recover from any deadlock. The best way to do this is to use timeouts on the locking process. The caller can catch timeouts and handle it properly instead of waiting forever. Here is a better Transfer method.

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    bool fromLock = Monitor.TryEnter(fromAccount, 1000);
    bool toLock = Monitor.TryEnter(toAccount, 1000);
    try
    {
        if (fromLock && toLock)
        {
            fromAccount.Withdraw(amount);
            toAccount.Deposit(amount);
        }
    }
    finally
    {
        if (fromLock)
            Monitor.Exit(fromLock);

        if (toLock)
            Monitor.Exit(toLock);
    }
}

This is a lot more code to write. Actually this is not far from what the lock keyword would do. Because if you look at your code with Reflector you will see that lock does translate to Monitor.Enter and Monitor.Exit (your have to look in IL not in C#). So a simple lock statement like this.

lock(obj)
{
    // do somtehing
    Console.WriteLine("Locked");
}

Would be translated to.

Monitor.Enter(obj);
try
{
    // do somtehing
    Console.WriteLine("Locked");
}
finally
{
    Monitor.Exit(obj);
}

You won’t see it in C# (with Reflector) but if you look at IL code you will see exactly the same sequence twice.

So to solve our problem, would it be nice to have something like this?

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    Safe.Lock(new [] {fromAccount, toAccount}, 1000, () =>
    {
        fromAccount.Withdraw(amount);
        toAccount.Deposit(amount);
    });
}

This look pretty much like the well known lock keyword, isn’t it? Now how can we do this? That’s better. The Safe static call has a Lock static method that take care of everything. The fist argument can be a single object or an array of objects. This allow locking multiple object at once. The Lock method use the Monitor.TryEnter to acquire lock on objects. If this can be done before the timeout occur the Action argument is executed.

Of course this code can and should be surrounded with a try-catch block. here is how to do so.

public static void Transfer(double amount, Account fromAccount, Account toAccount)
{
    var retries = 10;

    while (retries-- > 0)
    {
        try
        {
            Safe.Lock(new[] { fromAccount, toAccount }, 1000, () =>
            {
                fromAccount.Withdraw(amount);
                toAccount.Deposit(amount);
            });
            break;
        }
        catch (TimeoutException e)
        {
            if (retries == 0)
                throw;
            Thread.Sleep(100);
        }
    }
}

In this code snippet it will retry at most 10 time to lock toAccount and fromAccount before giving up. Notice that only the TimeoutException is handled, so any other exception will be thrown immediately and stop the process. The break at the end of the try block let us out as soon as it works.

This is a good timeout pattern and easy to implement in your own code. Give it a try and let me know if it works.

Here is the full code for the Safe class.

using System;
using System.Linq;
using System.Threading;

namespace MultithreadHelper
{
    public class Safe : IDisposable
    {
        private readonly object[] _padlocks;
        private readonly bool[] _securedFlags;

        private Safe(object padlock, int milliSecondTimeout)
        {
            _padlocks = new[] {padlock};
            _securedFlags = new[] {Monitor.TryEnter(padlock, milliSecondTimeout)};
        }

        private Safe(object[] padlocks, int milliSecondTimeout)
        {
            _padlocks = padlocks;
            _securedFlags = new bool[_padlocks.Length];
            for (int i = 0; i < _padlocks.Length; i++)
                _securedFlags[i] = Monitor.TryEnter(padlocks[i], milliSecondTimeout);
        }

        public bool Secured
        {
            get { return _securedFlags.All(s => s); }
        }

        public static void Lock(object[] padlocks, int millisecondTimeout, Action codeToRun)
        {
            using (var bolt = new Safe(padlocks, millisecondTimeout))
                if (bolt.Secured)
                    codeToRun();
                else
                    throw new TimeoutException(string.Format("Safe.Lock wasn't able to acquire a lock in {0}ms",
                                                             millisecondTimeout));
        }

        public static void Lock(object padlock, int millisecondTimeout, Action codeToRun)
        {
            using (var bolt = new Safe(padlock, millisecondTimeout))
                if (bolt.Secured)
                    codeToRun();
                else
                    throw new TimeoutException(string.Format("Safe.Lock wasn't able to acquire a lock in {0}ms",
                                                             millisecondTimeout));
        }

        #region Implementation of IDisposable

        public void Dispose()
        {
            for (int i = 0; i < _securedFlags.Length; i++)
                if (_securedFlags[i])
                {
                    Monitor.Exit(_padlocks[i]);
                    _securedFlags[i] = false;
                }
        }

        #endregion
    }
}


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

Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses