torsdag, september 15, 2011

Quick Tip: Accessing MapPath method When HttpContext.Current is null

If you ever tried to use the HttpContext.Current.Server.MapPath method from a thread or within a Sitecore EventHandler, you will notice, that the HttpContext.Current is null.

How do you get the absolute path of a file when you only know the relative path? Well, you can’t use HttpContext.Current.Server but you can use the alternative:

HostingEnvironment.MapPath("~/App_Config/MailTalkServices.config");
Located in the namespace: 
System.Web.Hosting;

torsdag, december 17, 2009

.NET Developer on a Macbook Pro running Windows 7

Yes I know, It is strange but very true.

I am a Microsoft .NET programmer and I use a 17” Unibody Macbook Pro Mid 2009 model, with a 2.66 GHz CPU, 8 GB RAM, and a Intel X-25m 160GB SSD hard drive. On top of that, I'm running Windows 7 as my primary OS spending 99% of my time on it, and using 90% of my time in Visual Studio 2008, Outlook 2010 Beta or Google Chrome.

And I am happy. Well now I am, but it has been a hassle. For a little over a year, I have been struggling to make this baby perform under Windows 7, and I has not been easy. I must have used 100 hours reading blogs, discussion forums and reading web pages on the subject. 

This is actually my second Unibody Macbook Pro. My first was a 15" but I sold that one and bought the 17” model instead. This proved to be a good decision. The 17” has a marvelous battery life and a fantastic screen compared to the 15” model. It is also a lot more silent and not as hot during intensive use.

I am besides being a .NET developer also a consultant. It has been quite funny to see how my customers make funny faces when I sit down around the conference table, introducing myself as a Microsoft specialist, pulling a Macbook Pro from my briefcase. However, some of them have told me that they actually had the same idea and I made a promise to one of them to explain how I made it perform under Windows 7. What better way of doing that than writing a series of blog posts.

I will over the next few days write about what I did to make it perform, and describe the one issue that remains to be solved: How to enable AHCI and thus SATA2 speeds in Windows 7. But more on that later.

fredag, august 29, 2008

Sitecore and .NET 3.5 SP1

Sitecore 6 was the victim of a bug in Microsoft .NET 3.5 SP1 – which meant that Sitecore 6 developers could not use Visual Studio 2008 SP1 or .NET Framwork 3.5 SP1.

You can read alle about it at Alexey Rusakov's blog

However, I just discovered that Sitecore just now released a patch addressing this very problem. I tested it, and it seems to work.

What you want to do, is download Update rev.080820 from sdn5.sitecore.net

Good work Sitecore :-)

fredag, november 30, 2007

Sitecore on .NET 3.5


I can report that using Sitecore with .NET 3.5 and C# 3.0 truly is a seamless transition.


This is especially good news for us developers who tried to upgrade from .NET 1.1 to .NET 2.0.
Back in the day, the transition supposed to be seamless, but surely was not. There was always some strange library containing some braking change, or a project model
who was removed - only to make life difficult for us developers.
This is by my experience NOT the case when upgrading from .NET 2.0 to 3.5.


I have been running a production environment of Sitecore in .NET 3.5 for a couple of weeks now (since we
Microsoft Gold Partners got VS2008) – and there have been no problems so far.
But why is that?


Well:

– There has been no change what so ever in the CLR runtime. It’s still 2.0. This was not the case coming from 1.1 to 2.0. MS had to update the CLR to include generics (parametric polymorphism)

– The C# Compiler has changed, but the target of the compiler remains.

– The library changes are purely additive. Meaning, that things you used in
.NET 2.0 remain the same - and all the new features have been added in new
.dlls, not changing the old ones.

So - Happy coding using C# 3.0 for Sitecore.


To finnish of, lets reflect on the different way to bind children of an Item to a repeater control in Sitecore:


(Wich one do you like the most ?)

//The sitecore way



childrenRepeater.DataSource = Context.Database.SelectItems("/sitecore/content/home/*[@@templatename='DisplayBox']");


//C# 1.0 way, using a standard foreach loop



ArrayList list = new ArrayList();



foreach (Item item in Sitecore.Context.Item.Children) {
if (item.TemplateName == "DisplayBox")
list.Add(item);
}
childrenRepeater.DataSource = list;


//C# 2.0 way, using the iterator pattern (yield statement),and anonomouse delegate


childrenrepeater.DataSource = delegate {



foreach (Item child in Sitecore.Context.Item.Children) {
if (child.TemplateName == "DisplayBox")
yield return child;
}
};


//C# 3.0 way using the query syntax
childrenRepeater.DataSource = from Item child in Sitecore.Context.Item.Children
where child.TemplateName =="DisplayBox"

select child;



childrenRepeater.DataBind();



torsdag, november 29, 2007

MailMonitor Sitecore Edition

I have been working on a product called Mail Monitor for years now. It is my pet project and has been for the last 3-4 years or so.

Mail Monitor is an E-mail /SMS campaign tool written in C# hosted on ASP.NET and uses all the cool stuff released from Microsoft within the last years. (Except Silverlight, for now). It is a tool written by a super nerd (me) and is therefore highly extendable using Providers, web-services, Remoting and GoF patterns.

But MailMonitor is not new – but the fact that I made a version for Sitecore is.

For now check out these screenshots.

søndag, april 29, 2007

.NET Remoting Removed from Sitecore

Some time ago I blogged about how Sitecore would include .NET Remoting, a feature that would make Sitecore more scalable and flexible.

Introducing Remoting support was a fundament for creating integration to Sitecore from applications that would not be hosted on the same process as the CMS – a scenario that is very likely in the enterprise. It would also open up the possibility of creating custom tools that could be run from any machine not running Sitecore, even supporting the creation of a Windows Power Shell client.

In essence, the only big different was the all classes in Sitecore.Kernel ultimately would implement MarshallByRefObject something that does not have any impact on the performance of the system, the rest was configuration. It means that supporting .NET Remoting is nearly effortless and free, whereas the benefits are great and powerful.

I just realized, to my great surprise, that none of the classes that used to implement MarshallByRefObject during the Beta period of Sitecore 5.3 still do.
I simply do not understand why Sitecore made this change, and would love to hear their input on this.

søndag, januar 14, 2007

Using the ObjectDataSource with Singleton and/or Interface instances

When using Visual Studio 2005 to configure the ObjectDataSource, you will only be presented the option to bind against classes that implement the class System.Web.UI.WebControls.ObjectDataSource. The ObjectDataSource will pr. default create its own instance of your ObjectDataSource class using reflection and use this that instance to retrieve objects that are to be bounded to you data control (for example the GridView).


As a consultant I often see developers having their own data retrieval classes, but when they want to use them in an ObjectDataSource, the class is wrapped in another class implementing the System.Web.UI.WebControls.ObjectDataSource only to satisfy Visual Studio. This leads to twice the complexity – and replication of code. The technique cowered in this blog post might be trivial to some, but I believe that the point cannot be made clear enough.


A better approach is to configure the ObjectDataSource tag to make use of the already present data retrieval class and tell the ObjectDataSource to use exact the instance of you class that you want it to use. This can be necessary if you have decided to only expose interfaces to you client, or if you data access class is implemented as a GoF Singleton or Factory design pattern (thus not letting the ObjectDataSource create an instance of your data retrieval class).


<asp:ObjectDataSource ID="_transactionData" runat="server"
    
TypeName="MailMonitorServer.Locator.ITransactionLocator"
    
DataObjectTypeName="LinkTrackerServer.ITransaction"
    
SelectMethod="Find" 
    
OnObjectCreating="ObjectDataSource_ObjectCreating" 
    
OnSelecting="ObjectDataSource_Selecting" 
    
EnableCaching="false" >
</asp:ObjectDataSource>


This code shows how I use the ITransactionLocator to locate transactions. The thing to notice here is that the ITransactionLocator (TypeName attribute of the ObjectDataSource) is in fact an interface (we cannot create instances of it from the client application) and the only way of getting an instance of this interface is through a Singleton pattern (more about that later).


The DataObjectTypeName defines that the type of the objects that are returned by the ITransactionLocator are of type ITransaction. In order to instruct the ObjectDataSource to use exactly your instance of the ITransactionLocator, and therefore not use reflection to create its own instance, I hook into the OnObjectCreating event.


protected void ObjectDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e) {
    
e.ObjectInstance = InstanceHelper.Instance.TransactionLocator;
}


Here I assign the singleton instance of my locator class to the arguments ObjectInstance property. This way the ObjectDataSource uses only this instance.


In this case the ITransactionLocator’s Find method needs a special parameter (not covered by the standard <selectparameter> tags. To customize the parameter sent to the Find method I hook into the OnSelecting event.


protected void ObjectDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {
    
IDealer dealer = (IDealer) Session["dealer"];
    e.InputParameters.Add("account", dealer.Account);
}


In this manner I also have complete control of the parameters that are sent to my ITransactionLocator.


I hope this little code will give you a new idea of now flexible the ObjectDataSource implantation really is.

tirsdag, november 14, 2006

Visual Studio 2005 Build Performance

I had some performance issues with my Visual Studio 2005, where one of my C# ASP.NET web sites simply took forever to build and compile. I knew that there was an issue in VS 2005 with large Visual Basic projects due to a compiler error in the Visual Basic compiler(http://blogs.msdn.com/webdevtools/archive/2006/07/24/677180.aspx) but I am not using VB!

Then it hit me, ASP.NET web sites can run with both C# and VB code mixed so the Visual Basic compiler must run each time you build your website. To test this, I simply removed Visual Basic from my installation (seldom use it anyway) and bang ! – My website builds lightning fast again.

The lesson learned is this:
- Performance problems with compiling your website?
- Remove Visual Basic from your Visual Studio installation! (or apply the MS hotfix)

Resume of a lecture

I attended Anders Hejlsberg’s guest lecture at ITU Copenhagen last Friday and want to share with all of you the information he revealed.

First of all – it was a great lecture. He showed how all the language features of C# 3.0 together made LINQ possible and explained how they implemented LINQ using every one of these new language features. I must say that C# 3.0 is innovation on a high level, surely a something I will be waiting for with anticipation.

Besides from a great lecture, Anders revealed some information I want to share with you. (I hope MS don’t mind)

Concurrent Programming
The next step, after the release of C# 3.0 and LINQ – the language team will probably focus on concurrent programming. Anders believes that the available constructs for concurrent programming simply are to complex for the average programmer (Threads and so fourth) Therefore they will look at how they can improve the runtime and/or the language to better support concurrent programming, making it easier for developers to take advantage of multiple CPU’s that are getting more and more common in standard PC.

Release of C# 3.0 and LINQ
Anders revealed that the language team currently is improving some details of the compiler for C# 3.0 and we (the general public) will have a beta version of the next Visual Studio codename “Orcas” in about six months. He also ensured that there will be no more CTP – only Betas from now on.

UPDATE 2007-03-09
-----
Seams that Anders Hejlsberg was wrong :-)Last week a new CTP (March CTP) was released after all. I wonder if the Beta still will be available six months after the lecture ?
------------

Last note
There will finally be a Set collection implementation available in Orcas. Jubii.

tirsdag, oktober 31, 2006

Anders Hejlsberg in Copenhagen (IT University)

I just learned from my former professor (Peter Sestoft) that Anders Hejlsberg will host a guest lecture at ITU, Copenhagen on November 10th at 14:00 hours.

As you probably already know, Anders is the man behind C# and this lecture will contain a walkthrough of the new language features of C# 3.0 as well as his reasons for including these language features in this future release of C#.

C# 3.0 will include really cool features like:
- Implicitly typed local variable declaration: (for example var i = 42)
- Extension methods (the possibility to extend existing types with additional methods)
- Lambda expressions (cool SML like syntax for methods: x=> x + 42 )
- Greater type inference
- Object and collection initializers ( shorter syntax for creating instances)
- Anonymous types (like: new{Name = “Runi”, Language=”C sharp”})
- Implicity types arrays
- And the LINQ (declarative type safe access to query relational and hieratical data)

To register for this FREE event, register here:
http://www.microsoft.dk/MSDN/Hejlsberg@ITU

I will surely be there - see you all.

/Runi

fredag, oktober 27, 2006

Sitecore Instructur at last

I have yesterday reached the level of higher existence (or competence) - Sitecore V5 Certified Instructor, Level 2.

I just completed my first instruction in the Sitecore API course. It was actually quite giving and interesting to teach Sitecore on a lower level, surely something I want to do again.

Actually, if everything goes well, my next instruction session will be in Holland sometime late next month.

onsdag, oktober 25, 2006

Dont trust your debugger

I just waisted a couple of hours because of a strange behaviour in the Visual Studio debugger.
Consider the following code:

object
obj = new String('a',1); //"a"
string str = new String('a',1); //"a"
Console.Out.WriteLine(obj == str); //ln1
Console.Out.WriteLine(str == obj); //ln2
Console.Out.WriteLine((string)obj == str);//ln3
Console.Out.WriteLine(str ==(string)obj); //ln4
Console.Out.WriteLine(obj.Equals(str)); //ln5
Console.Out.WriteLine(str.Equals(obj)); //ln6

Now, add breakpoints in Visulal Studio on line 1 to 6 - and make the debugger evaluate the expression before it is printet to the console.


What would you (the debugger) expect the output to be? The Visual Studio Debugger says:
true
true
true
true
true
true


This is however not the case. The actual output is:
false
false
true
true
true
true


There is really nothing strange about the result. The == operator does not just call the Equals method blindly and virtually as one might expect. It is actually an operator that compares references unless overridden.

By default the == operator compares for reference equality. So if == tests for reference equality, this would explain the behavior of the result of ln1 and ln2, but not ln 3 and 4. This is because the == operator has been overridden in the String class to call the Equals method, thus comparing the value of the string rather than its reference. (this explains ln 3 and 4).

The runtime system determines which operator to call based on the runtime type (the type of the reference rather than the type of the instance). In ln 1 and 2 the == operator of the Object class is used, where in ln3 and ln4 the operator as defined in the String class is used.

So much for the == operator. The strange thing however, is that the Visual Studio debugger does not seam to get this. (VS2003). I used a lot of time debugging an expression inside an 'if' statement, which evaluated to false (by the debugger) but the if - statement - body was entered anyway. Grrr – I’m a bit pissed at the debugger.

torsdag, august 31, 2006

Media Library Posts Removed

Sitecore has asked me to remove my Sitecore 5.3 Media Library Part 1 - 5 blog posts which gave a preview of the Media Library in Sitecore 5.3 beta because of changes in the final version. I will of course honor this request, whereas these posts no longer are available. For info on Sitecore – contact Sitecore

A Sitecore Core Developer goes solo

I made a decision a couple of months ago of going back to my old discipline of software consulting. This means that I have resigned my position at Sitecore as a Core Developer and QA manager, and have created a Software Consultancy firm called “Delegate ApS” (I know, quite C#’ish)

My decision has been a hard one and has nothing to do with me not being happy with working on this amazing product. I simply missed the kick of being around real customers and following projects through.

During the time of employment at Sitecore I have learned allot of hardcore stuff. Specially working with Ole and Jacob (Core Developers and innovators of Sitecore) has been extremely giving. Before working at Sitecore, I was a consultant and have therefore worked with allot of developers through the years. Without comparison, the guys at Sitecore are the most competent. I will truly miss the high level of abstraction there guys are able to discuss architecture on.

However, this will not be the end of my work with Sitecore. Sitecore will make sure that I become a Sitecore Certified Trainer as soon as possible and I have decided that my new firm (Delegate ApS ) is to become a certified Sitecore Partner within a month or so. This means that I will finally sit on the other end of the table and experience actually working with the product, instead of creating the product.

All the luck in the world to Sitecore here at the end of my voyage as an Sitecore employee.

tirsdag, maj 02, 2006

InPlaceEditExtender for April CTP release of ATLAS

Nikhil Kothari created a fine ATLAS control named InPlaceEditExtender. The control does not work on the April CTP of ATLAS, so I modified the javascript to comply with the April CTP release, as well as added some support for dropdowns.
Download the control from Nikhil's blog, and replace the javascript with the following javascript and you will have the InPlaceEditExtender control for April CTP:

Type.registerNamespace('nStuff.Samples.InPlaceEdit');

 

nStuff.Samples.InPlaceEdit.InPlaceEditBehavior = function() {

    nStuff.Samples.InPlaceEdit.InPlaceEditBehavior.initializeBase(this);

 

    var _labelCssClass;

    var _labelHoverCssClass;

 

    var _labelElement;

    var _isEditing = false;

    var _isInputControl = false;

 

    var _textBoxBlurHandler;

    var _labelFocusHandler;

    var _labelMouseOverHandler;

    var _labelMouseOutHandler;

    var _validatedHandler;

 

    this.get_isEditing = function() {

        return _isEditing;

    }

 

    this.get_labelCssClass = function() {

        return _labelCssClass;

    }

    this.set_labelCssClass = function(value) {

        _labelCssClass = value;

    }

 

    this.get_labelHoverCssClass = function() {

        return _labelHoverCssClass;

    }

    this.set_labelHoverCssClass = function(value) {

        _labelHoverCssClass = value;

    }

 

    this.beginEdit = function() {

        if (_isEditing) {

            return;

        }

 

        var textBoxElement = this.control.element;

        textBoxElement.style.display = '';

        _labelElement.style.display = 'none';

        if(!textBoxElement.disabled)

            textBoxElement.focus();

 

        _isEditing = true;

        this.raisePropertyChanged('isEditing');

    }

 

    this.dispose = function() {

        if (_labelElement) {

            _labelElement.detachEvent('onfocus', _labelFocusHandler);

            _labelElement.detachEvent('onmouseover', _labelMouseOverHandler);

            _labelElement.detachEvent('onmouseout', _labelMouseOutHandler);

 

            _labelElement = null;

            _labelFocusHandler = null;

            _labelMouseOverHandler = null;

            _labelMouseOutHandler = null;

        }

 

        if (_textBoxBlurHandler) {

            var textBoxElement = this.control.element;

            textBoxElement.detachEvent('onblur', _textBoxBlurHandler);

            _textBoxBlurHandler = null;

        }

 

        if (_validatedHandler) {

            this.control.validated.remove(_validatedHandler);

            _validatedHandler = null;

        }

 

        nStuff.Samples.InPlaceEdit.InPlaceEditBehavior.callBaseMethod(this, 'dispose');

    }

 

    this.endEdit = function() {

        if (!_isEditing) {

            return;

        }

        if (_isInputControl && this.control.get_isInvalid()) {

            return;

        }

 

        var textBoxElement = this.control.element;

        _labelElement.innerHTML = textBoxElement.value;

        _labelElement.style.display = 'block';

        textBoxElement.style.display = 'none';

 

        _isEditing = false;

        this.raisePropertyChanged('isEditing');

    }

 

    this.getDescriptor = function() {

        var td = nStuff.Samples.InPlaceEdit.InPlaceEditBehavior.callBaseMethod(this, 'getDescriptor');

 

        td.addProperty('isEditing', Boolean, /* readOnly */ true);

        td.addProperty('labelCssClass', String);

        td.addProperty('labelHoverCssClass', String);

        td.addMethod('beginEdit');

        td.addMethod('endEdit');

        return td;

    }

 

    this.initialize = function() {

        nStuff.Samples.InPlaceEdit.InPlaceEditBehavior.callBaseMethod(this, 'initialize');

 

        _labelElement = document.createElement('LABEL');

 

        var textBoxElement = this.control.element;

        var textBoxBounds = Sys.UI.Control.getBounds(textBoxElement);

        var containerElement = document.createElement('SPAN');

 

        textBoxElement.parentNode.insertBefore(containerElement, textBoxElement);

        containerElement.appendChild(textBoxElement);

        containerElement.appendChild(_labelElement);

 

        textBoxElement.style.display = 'none';

        if(textBoxElement.tagName == 'SELECT')

            _labelElement.innerHTML= textBoxElement.options[textBoxElement.selectedIndex].text;

        else

            _labelElement.innerHTML = textBoxElement.value;

        _labelElement.tabIndex = textBoxElement.tabIndex;

        _labelElement.className = _labelCssClass;

        _labelElement.style.display = 'block';

        _labelElement.style.width = textBoxBounds.width + 'px';

        _labelElement.style.height = textBoxBounds.height + 'px';

 

        _textBoxBlurHandler = Function.createDelegate(this, this._onTextBoxBlur);

        _labelFocusHandler = Function.createDelegate(this, this._onLabelFocus);

        _labelMouseOverHandler = Function.createDelegate(this, this._onLabelMouseOver);

        _labelMouseOutHandler = Function.createDelegate(this, this._onLabelMouseOut);

 

        textBoxElement.attachEvent('onblur', _textBoxBlurHandler);

        if (Sys.Runtime.get_hostType() == Sys.HostType.InternetExploreJ) {

            _labelElement.attachEvent('onfocus', _labelFocusHandler);

        }

        else {

            _labelElement.attachEvent('onclick', _labelFocusHandler);

        }

        _labelElement.attachEvent('onmouseover', _labelMouseOverHandler);

        _labelElement.attachEvent('onmouseout', _labelMouseOutHandler);

 

        if (Sys.UI.InputControl.isInstanceOfType(this.control)) {

            _isInputControl = true;

            _validatedHandler = Function.createDelegate(this, this._onValidated);

            this.control.validated.add(_validatedHandler);

        }

    }

 

    this._onLabelFocus = function() {

        if (_labelHoverCssClass && _labelHoverCssClass.length) {

            Sys.UI.Control.removeCssClass(_labelElement, _labelHoverCssClass);

        }

 

        this.beginEdit();       

    }

 

    this._onLabelMouseOut = function() {

        if (_labelHoverCssClass && _labelHoverCssClass.length) {

            Sys.UI.Control.removeCssClass(_labelElement, _labelHoverCssClass);

        }

    }

 

    this._onLabelMouseOver = function() {

        if (_labelHoverCssClass && _labelHoverCssClass.length) {

            Sys.UI.Control.addCssClass(_labelElement, _labelHoverCssClass);

        }

    }

 

    this._onTextBoxBlur = function() {

        this.endEdit();

    }

 

    this._onValidated = function(sender, eventArgs) {

        if (this.control.get_isInvalid()) {

            this.beginEdit();

        }

    }

}

//Type.registerSealedClass('nStuff.Samples.InPlaceEdit.InPlaceEditBehavior', Sys.UI.Behavior);

nStuff.Samples.InPlaceEdit.InPlaceEditBehavior.registerSealedClass('nStuff.Samples.InPlaceEdit.InPlaceEditBehavior', Sys.UI.Behavior);

Sys.TypeDescriptor.addType('nk', 'inPlaceEdit', nStuff.Samples.InPlaceEdit.InPlaceEditBehavior);

tirsdag, april 11, 2006

Sitecore performance

ScottGu posted a blog entry where he explains the danger of setting debug=true in production enviroments.

The consequenses include:

1) Compilation of pages takes longer
2) Code executes slower
3) More memory is used at runtime
4) Scripts and images from WebResources.axd are not cached.

This is specially Sitecore relevant.


debug="false" is our friend

For details, see Scott's blog post.

http://weblogs.asp.net/scottgu/archive/2006/04/11/442448.aspx

fredag, april 07, 2006

.NET Remoting in Sitecore

The upcoming release of Sitecore (I guess it will be named Sitecore V5.3) will include a lot of new cool features. One of my favorite new features Im working on is remote invocation of Sitecore objects through .NET Remoting - giving you remote access to almost the entire Sitecore API (SitecoreKernel.dll) from any .NET client.

Hopefully the Remoting features will be stable enough to make the final release.

To enable your non-sitecore project (for example a Forms application) to use Sitecore Remoting, simply add a reference to Sitecore.Kernel.dll and you are good to go.

Access to Sitecore API is achieved through the new Sitecore.Remoting namespace, where you will have to know about two new types: The RemoteFactory and RemotingClientConfigurator. Only one line of code is necessary in order to get a remote reference to Sitecore:

Sitecore.Remoting.RemotingClientConfigurator.Configure(_sitecoreurl, "admin", "");



This snippet sets up the connection to Sitecore at a given url, with the username 'admin' and the empty password.

To access Sitecore objects, simply use the new RemoteFactory object (a remoting enabled version of the Factory class):

RemoteFactory factory = new RemoteFactory();



You now have access to all Sitecore objects. For example:

factory.GetDatabase("master").GetRootItem()



This will get you the root item of the master database.

In a later post, I will show how Sitecore can be managed and scripted through Microsofts new shell: MONAD using the new Remoting features.

Hopefully other more or less useful programs will be developed as a result of the introduction of .NET Remoting in Sitecore. I talked to Alexy Rusakov (Sitecore developer from our Ukraine division) about creating an addin to the Google toolbar showing a list of items who's workflow step is assigned to a specific user.

Only your imagination is the limit :-)


Regards

tirsdag, marts 28, 2006

Atlas StopableTimer

I tried out the March CTP release of Microsofts new Ajax implementation Atlas. The library now has a "go live" license making it even more interesting for us real life programmers.

The TimerControl included in Atlas March CTP has a problem. It cannot be stopped ones started. I guess that this is intentional (that’s what the documentation says) but the fact remains. You often want to be able to update a page, only while some task is run on the server.

A user on the Atlas forum named Rama Krishna (that’s his username) came up with a clean and great solution to create a stopable timer control (see the post here). However, the posted control only worked on the January CTP release.

I took his control and modified and updated it for the March CTP release (All credit to Rama).

The control emits a client-side timer control (xml) and assigns an id to it. (The base TimerControl does not). Then a small piece of java script is registered to handle enabling and disabling the timer at startup.

First put the following in the App_Code folder:

using System;

using Microsoft.Web.UI.Controls;

 

namespace CustomControls {

 

    public class StopableTimer : TimerControl {

        public StopableTimer() {

        }

 

        protected override void OnPreRender(EventArgs e) {

            base.OnPreRender(e);

            if (Page.IsPostBack) {

              Page.ClientScript.RegisterStartupScript(

          Page.GetType(), "TimerStop",

                    "Sys.Application.findObject('" +

            UniqueID +

            "').set_enabled(" +

            (Enabled ? "true" : "false") +

            ");"

                    , true);

          }

        }

 

        protected override void RenderScript(Microsoft.Web.Script.ScriptTextWriter writer) {

            writer.WriteStartElement("timer");

            writer.WriteAttributeString("id", UniqueID);

            writer.WriteAttributeString("interval",

          Interval.ToString(System.Globalization.CultureInfo.InvariantCulture));

            writer.WriteAttributeString("enabled", Enabled.ToString());

            writer.WriteStartElement("tick");

            writer.WriteStartElement("postBack");

            writer.WriteAttributeString("target", UniqueID);

            writer.WriteAttributeString("eventArgument", string.Empty);

            writer.WriteEndElement();

            writer.WriteEndElement();

            writer.WriteEndElement();

        }

    }

}



When you have created the control, you only need to register it on you aspx page - and use it as you would use a TimerControl

<%@ Register Assembly="App_Code" Namespace="CustomControls" TagPrefix="AppCode" %>

fredag, december 30, 2005

Sitecore ASP.NET 2.0 final version released

We will release Sitecore version 5.2.0.2 today. This is the ASP.NET 2.0 version of Sitecore version 5.1.1.8

torsdag, december 22, 2005

Sitecore Portal

This post is a draft of how to use the build in portal functionality in Sitecore V5.1.1.x. Please provide input on its content so that this post can become an article in time.

Using the ”Sitecore Today” portal in you own applications.
Sitecore has build in a simple portal framework used in some applications in the Sitecore GUI client. It is possible to use this framework in your own applications by the means of creating some XML (XAML like) controls and some code. This is an instruction on how to get started.

1) Create the Portal Layout
The first thing you need to do is to create the layout that defines the portal. To create such layout, start the layout studio and click File -> new -> XML Layout. The “Create XML Layout wizard” appears.

Press next and name the layout what you like. For this example the layout is called “Portal Demo”. Press next two times to place the layout in the layouts folder, and finish the wizard.

The layout studio opens the newly created xml layout and displays its content in a window. Delete the content of the editor, and replace it with the following:

<?xml version="1.0" encoding="utf-8" ?>
<control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense">
<PortalDemo>
<FormPage Scroll="yes">
<CodeBeside Type="Example.PortalDemo,MyDll"/>
<Stylesheet Src="/sitecore/portal/tech/tech.css"/>
<Portal ID="PortalDemo" DataSource="/sitecore/content/Home/PortalDemo/Portal" RefreshPageOnRedraw="true">
<Border Class="Portal">
<GridPanel Columns="3" Width="100%" Height="100%" CellSpacing="4" CellPadding="4">
<PortalZone ID="Left" GridPanel.Width="33%" GridPanel.Class="PortalColumn" GridPanel.VAlign="top" GridPanel.Height="100%"/>
<PortalZone ID="Mid" GridPanel.Width="33%" GridPanel.Class="PortalColumn" GridPanel.VAlign="top"/>
<PortalZone ID="Right" GridPanel.Width="33%" GridPanel.Class="PortalColumn" GridPanel.VAlign="top"/>
</GridPanel>
</Border>
</Portal>
<Frame ID="Sidebar" Width="6" Height="100%" Style="position:absolute; left:expression(parentNode.clientWidth-6); top:0"/>
</FormPage>
</PortalDemo>
</control>

The fist element defines that this is a control and the second element <PortalDemo> defines the name of the layout. The portal uses the FormPage <FormPage Scroll="yes"> with scrolling and has a codeBeside class type of PortalDemo located in the dynamic linked library MyDll.
The creation of the codeBeside type will be explained in the next step. The <Stylesheet/> element points to the same style sheet that is used for the “Sitecore Today” application found in the Sitecore client, but can just as well be replaced by our own custom style sheet to achieve you own look and feel.

The next element <Portal> defines the actual portal and it defines where in the content tree its portlets (Sitecore items) are to be found. We will create these items shortly.

The portal element defines the portalZones where portlets can be placed by Id. In this example we have defined tree zones named Left, Mid and Right.

The last element <Frame> defines a sidebar users can invoke to add and remove portlets to their portal.

2) Create the layout code beside class
As seen, the portal defines a code beside class, with the sole purpose of adding portlets to the sidebar.

Create a new class Named PortalDemo in the namespace Example. The source should look like this:

using System;
using Sitecore;
using Sitecore.Text;
using Sitecore.Web.UI.HtmlControls;
using Sitecore.Web.UI.Sheer;
namespace MyPortal {
public class RuniPortal : BaseForm {
protected Frame Sidebar;

protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
if (!Sitecore.Context.ClientPage.IsEvent) {
UrlString url = new UrlString(UIUtil.GetUri("control:PortalSidebar"));
url.Add("pid", "Sidebar");
url.Add("pds", "/sitecore/content/Home/Portal sidebar");
url.Add("pt", "/sitecore/content/Home/PortalDemo/Portal");
url.Add("pn", "PortalDemo");

Sidebar.SourceUri = url.ToString();
}
}

#endregion
}
}

The PortalSidebar control is used to contain portlets and requires some url parameters as setup. The first parameter defines the control to use, the second the id of the control, the third the location of the Sitecore items defining the sidebar and the fourth the path of the portal and the last the name of the portal.

3) Creating a portlet
Portlets can be created with any control, as long as the items that are defining it are based on the portlet template. However, to support moving and adding new portlets from the portlet itself, a special control must be created.

To create a portlet which basically wraps the document control, create a new xmlcontrol from the layout studio and paste the following xml into it (same procedure as in step 1):

<?xml version="1.0" encoding="utf-8" ?>
<control xmlns:def="Definition" xmlns="http://schemas.sitecore.net/Visual-Studio-Intellisense">
<DocumentPortlet ID="DocumentPortlet" def:inherits="DocumentPortletXmlControl,Sitecore.Client" > <!--The id is used for moving between columns-->
<DefaultPortletWindow def:ID="Window" Header="Document" Icon="Applications/16x16/star_yellow.png"> <!-- The id is used for the context menu popup -->
<Document def:ID="document"/>
</DefaultPortletWindow>
</DocumentPortlet>
</control>

The newly defined controls is called “DocumentPortlet” and uses the DefaultPortletWindow control to render the portlets surrounding frame, giving it support for moving it from portalzone to portalzone and showing and hiding it. This DocumentPortlet must also have a code beside file which we will create afterwards.

Inside the DocumentPortlet, the Document control is used to render the item’s content. Now create the codebeside class:

using System;
using Sitecore.Web.UI.XmlControls;

public class DocumentPortletXmlControl : XmlControl {
protected XmlControl Window;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);

if (!Sitecore.Context.ClientPage.IsEvent) {
Window.ID = ID + "_window";
}
}
}

This is a required step in order to make sure that the id of the control is valid.

When this step is completed, it is time to create the Sitecore items to support the Portal, and the Portal sidebar.

4) Creating the Portal Items
Create a new Item in the content editor based on the Document template. The name of this item should be the same as defined in the PortalDemo layout created in previous step.

Choose the PortalDemo as the default layout in the layout window in the content editor, and save it.

As a child of the newly created PortalDemo item, create a new item based on the Portal template.

Under the new item, create another item named “Test” based on the template portlet, and fill in the description, and ID. In the “Control name” field add the name of the portlet control we just created: “DocumentPortlet”. In the zone filed, write for example: “Right” to place the portlet in the portal zone named Right.

5) Creating the sidebar Items
Create a new Item under the Home item named Portal sidebar. The Item must be based on the Portal template.

Create a new Item under the “Portal sidebar” based on the Portlet template named “Configurator”. Give it the Item ID: “PortalConfiguratorPortlet” and the Name “PortalConfiguratorPortlet” In the Zone field write “DefaultZone” and in the Order field write “10”. Check the “Default” checkbox.

6) Displaying the Portal
The portal should now be configured with one portlet, and can be seen in the client. Navigate to http://yourserver/PortalDemo.aspx to display the newly created portal. You can invoke the sidebar by moving the mouse towards the right of the browser.

Good luck.