Wednesday, December 26, 2007

Microsoft Sync Framework CTP

Microsoft has released the Microsoft Sync Framework CTP 1 few weeks ago.
With the MS Sync Framework you can easily synchronize any application, any type of data, using any protocol over any network.

The steps below explains how you to synchronize a folder. In fact, you can use the following example to create a backup of a certain folder:

//Start method
public void Backup()
{
/*1. Create or retrieve SyncId file (a Sync Id file contains a GUID to uniquely identify each folder*/
SyncId sourceSyncId = GetSyncId(Path.Combine(sourcePath, idFileName));
SyncId destinationSyncId = GetSyncId(Path.Combine(destinationPath,idFileName));

/* Adding synchronization options */
FileSyncOptions options = FileSyncOptions.ExplicitDetectChanges | FileSyncOptions.RecycleDeletes;

/* Adding synchronization filters: do not synchronize/backup the SyncId file.*/
FileSyncScopeFilter filter = new FileSyncScopeFilter();
filter.FileNameExcludes.Add(idFileName); // Exclude the generated SyncId file

/* Detect synchronization changes.*/
DetectChanges(sourceSyncId, sourcePath, filter, options);
DetectChanges(destinationSyncId, destinationPath, filter, options);

/* Synchronize (backup) source to destinationfolder*/
SyncFiles(sourceSyncId, destinationSyncId, sourcePath, destinationPath, filter, options);
}


In the Backup() method we used following supporting methods:

private void DetectChanges(SyncId syncId, string path, FileSyncScopeFilter filter, FileSyncOptions options)
{

using (FileSyncProvider provider = new FileSyncProvider(syncId, path, filter, options))
{
provider.DetectChanges();
}
}

private void SyncFiles(SyncId sourceSyncId, SyncId destinationSyncId, string sourcePath, string destinationPath, FileSyncScopeFilter filter, FileSyncOptions options)
{

using (FileSyncProvider sourceProvider = new FileSyncProvider(sourceSyncId, sourcePath, filter, options))
using (FileSyncProvider destinationProvider = new FileSyncProvider(destinationSyncId, destinationPath, filter, options))
{
//Create SyncAgent
SyncAgent agent = new SyncAgent();
agent.LocalProvider = sourceProvider;
agent.RemoteProvider = destinationProvider;

//Upload = Synchronize files from LocalProvider to RemoteProvider
agent.Direction = SyncDirection.Upload;

//Synchronize!
agent.Synchronize();
}
}

private SyncId GetSyncId(string idFilePath)
{

SyncId replicaId = null;

//Try to read existing ReplicaID
if (File.Exists(idFilePath))
{
using (StreamReader sr = File.OpenText(idFilePath))
{
string strGuid = sr.ReadLine();
if (!string.IsNullOrEmpty(strGuid))
{
replicaId = new SyncId(new Guid(strGuid));
}
}
}
//If not exist, Create ReplicaID file
if (replicaId == null)
{
using (FileStream idFile = File.Open(idFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(idFile))
{
replicaId = new SyncId(Guid.NewGuid());
sw.WriteLine(replicaId.GetGuidId().ToString("D"));
}
}
}

return replicaId;
}


Resources

  • Click here to download the MS Sync Framework CTP 1.

  • Sync framework Development Center

  • Sync framework Blog
  • Saturday, December 22, 2007

    Integrated WiX support in SharpDevelop


    In fact, WiX is the Open source toolset which generates Windows Installation packages or MSI files. WiX provides command line tools to build MSI packages.


    Wikipedia describes the WiX toolset as follows:

    The Windows Installer XML toolset (WiX), pronounced "wicks", is a free, open-source toolset that builds Windows Installer (MSI) packages from an XML document. It supports a command-line environment that developers may integrate into their build processes to build MSI and MSM setup packages. ...

    The developer has to create an xml file with .Wxs extension. This file contains all files, folders, registry keys, SQL databases, IIS directories, users, shortcuts, … which must be included in the installation. Creating the .Wxs file is not that easy. Currently, there is no user-friendly application to create this file. There is already an Open Source project, called WixGUI, but they haven’t released anything yet ...


    Compilation process


    To build our MSI file with WiX, we need 2 executables: Candle.exe & Light.exe.
    1.Candle compiles the .Wxs file into a .WixObj file. (intermediary xml file)
    2.Light transforms the .WixObj into the final MSI package

    You can create your own batch file with following commands:
    candle Test.wxs
    light.exe -out Test.msi Test.wixobj

    Sharp Developer



    Did you ever heard about SharpDevelop? SharpDevelop is the Open Source Integrated Development Environment in contrast to Visual Studio IDE. SharpDevelop has also integrated WiX support. You can visually create your .Wxs file. You can also design custom installation dialogs and watching the result before executing the installation package. By pressing F5 (alias ‘Build solution’) the Candle and Light executables are automatically executed. So by building your solution, your MSI file will be created automatically!

    SharpDevelop has Setup projects which has built-in WiX support:


    In the Setup project you have a tree-structure with all files, directories, components, ... which can be added visually.


    You can also view the resulting customized installation dialogs, without executing the installation package:



    Remarks


    There is also a project, called Votive, which provides WiX support for Visual Studio .NET/2005/2008. This integration allows you to have intelliSense in the Wxs file, but you cannot create files, directories, etc… visually!


    References


    SharpDevelop Community
    WiX online tutorials
    Article on SharpDevelop and integrated WiX support

    Tuesday, November 27, 2007

    Syntax formatters for blogs

    Do you prefer an online code formatter for blogs? click here to use the Ejeliot Code Formatter

    Alternative: Syntax Highlighting for Windows Live Writer

    Check also the 10 tips for Windows Live Writer on this website.

    Monday, November 26, 2007

    Creating drawings on Mobile devices

    I am currently developing a mobile application for my customer. In that application the customer wants to create and modify pictures/drawings. Those pictures must be stored in a database as binary data.


    Possible solutions
    There are two possible solutions:

  • Using the Microsoft Ink controls

  • Implementing a custom paint




  • Using the Microsoft Ink conrols
    The Microsoft Ink controls are not included in the .NET framework. You must download the Microsoft Windows XP Tablet PC Edition Software Development Kit 1.7 to use the Microsoft.Ink namspace. After installation the Microsoft.Ink library will be installed in the GAC.

    The Ink controls are especially developed for Tablet PCs. In fact the Ink controls provides a wrapper class around a COM component.


    The namespace contains 4 Ink controls:
  • InkEdit

  • InkPicture

  • InkCollector

  • InkOverlay


  • In our project, we are using the InkCollector to create and modify drawings. It is not necessary to use the Ink controls for text recognition. In fact it is also an out-of-the-box drawing surface to generate images.


    We can store the drawings created by the Ink controls in:
  • ISF (Ink Serialized Format)

  • Fortified Gif image (regular Gif + metadata in ISF)

  • HTML (with Base64-encoded fortified gif)

  • Xml (with Base64-encoded ISF)




  • When you need to modify the stored files, you must use a ISF/Xml file or Fortified gif image.

    You can save the Ink as fortified Gif or ISF/Xml file by calling the Save method on the Ink property of the ink control.

    byte[] fortifiedGif = anInkCollector.Ink.Save(PersistenceFormat.Gif)

    When it is not necessary to modify the images in the future, you can access the Renderer property on the Ink control to generate a picture in a .NET ImageFormat (Gif, jpg, Bmp, Png, ...)



    Click here to learn more about the Microsoft.Ink namespace.

    Custom Paint solution
    In fact, it seems to be quite easy, but writing a good custom paint is not easy at all. I conduct the possibilities and I survived following problems:

    The more lines, points on the form, the more the form is flickering
    Drawing too fast, do not result in a solid line, but in a range of dots.

    The first problem can be easily resolved by a search on Google. (Code Project flicker-free drawing project). The second problem is tough!. In fact the MouseMove event does not fire for each movement an event. This result in a dotted line, not in a solid line ! We can use a Line-Drawing Algorithm, for example the 'Bresenham Line-Drawing algorithm.

    You can download the Phoenix Paint project (Open source project under BSD license), author: http://grapefruitopia.com.


    Conclusion
    Both solutions provides a drawing tool. The Ink controls are specially created for Tablet PCs and uses the Ink Serialized Format to store drawings. On the other hand, the custom paint solution is more open. You determine the resolution, size, colors, format and compression.

    The choice is up 2 you !

    Monday, September 17, 2007

    Using SandCastle with XpertBuildDoc

    This weekend I read a nice about SandCastle article of Maarten Balliauw.

    I also want to mention that besides the SHFB project, we can also use the XpertBuildDoc add-in for Visual Studio 2005. Which is also free and is also integrated into Visual Studio 2005.

    You can download the add-in here



    More information
    SandCastle June 2007 CTP
    XPertDoc products
    XPertBuildDoc forums
    Francis Dion's blog

    Tuesday, August 28, 2007

    Tuesday, August 07, 2007

    In this blog post I refers to the Microsoft SDK for Open XML Format to create Word documents with .NET code. Microsoft Office Word, Excel, PowerPoint2007 are using the Open XML format as file format. This format is based on ZIP and XML. The following example will help you to create Word documents programmatically.


    Guidelines

    1. Add '\OpenXMLSDK\1.0.0531\lib\Microsoft.Office.DocumentFormat.OpenXml.dll' as reference to your Visual Studio project.
    2. Add another reference to the WindowsBase dll of the .NET 3.0 framework.
    3. Adding word document through the following code:

      // How to: Create a new package as a Word document.
      public static void CreateNewWordDocument(string document)
      {
      using(WordprocessingDocument wordDoc = WordprocessingDocument.Create(document,WordprocessingDocumentType.Document))
      {
      // Set the content of the document so that Word can open it.
      MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
      SetMainDocumentContent(mainPart);
      }
      }

      // Set content of MainDocumentPart.
      public static void SetMainDocumentContent(MainDocumentPart part)
      {
      const string docXml = @" Hello world!"

      using (Stream stream = part.GetStream())
      {
      byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
      stream.Write(buf, 0, buf.Length);
      }
      }

    Tips
    To create Excel sheets, you can use the SpreadsheetDocument and to create Powerpoint presentations you can use the PresentationDocument

    Downloads
    Microsoft SDK for Open XML Formats (Microsoft)
    Open XML File Format Code Snippets for Visual Studio 2005 (Microsoft)
    Office Open XML Format file creation (CodePlex)

    Friday, July 27, 2007

    Visual Studio 2008 beta 2 released

    Visual Studio 2008 beta 2 has been released.

    Click on the link to download:
    http://msdn2.microsoft.com/en-us/vstudio/default.aspx

    Thursday, July 26, 2007

    Using the SQL Server's Timestamp datatype

    The Timestamp datatype is supported by SQL Server 2000 and SQL Server 2005.

    It is a good way to indicate the row version because it represents a unique value.

    A field defined as 'timestamp' is automatically updated by SQL Server when rows are inserted or updated. You cannot read the content of a timestamp field in the Management Studio. It is encapsulated as 'binary'. ('Timestamp' is stored in 8 bytes as binary(8)).

    Why is the timestamp datatype useful?

    The timestamp datatype guarantees to be unique across the DB. It is generally used as a DB generated ID in tables.

    Other methods?
    You can also use a DateTime datatype to indicate a row's version. A datetime field is not automatically updated and is not unique across the database.

    Click here to read more about SQL Server 2000/2005 datatypes

    Wednesday, July 25, 2007

    Workflow Persistency: adding Oracle and MySQL support

    Workflow Foundation (WF) provide assistance to use SQL Server as datasource for workflow persistency and tracking.Companies which want to work with Oracle, cannot use the same scripts and default logic.
    Workflow Foundation uses services to accomplish this task. Normally you want add a SqlWorkflowPersistenceService to the Workflow Runtime Manager to enable workflow persistency.
    In case of Oracle you can download the Oracle Persistency Service for Oracle databases written by Mick.



    For Oracle & MySQL support, you can download the Workflow Foundation Tools (release 0.2.2 -alpha at this moment)Release date: 15th July 2007



    To read more about 'Workflow Persistence' you can read the sample chapter of Bruce Bukovic's book by clicking on this link.

    Tuesday, July 24, 2007

    Bruce's fantastic: 'PRO WF, Windows Workflow in .NET 3.0'

    I would like to suggest the wonderful book of Bruce Bukovics.
    Last month I read his book "Pro WF: Windows Workflow in .NET 3.0." which I can only suggest to everyone!

    The book explains you every aspect of Workflow Foundation in a very practical way!
    So, just buy and read the book.

    To read his blog, just click here.

    Tuesday, June 19, 2007

    EventDeliveryFailedException in State Machine Workflow

    I am currently diving into Windows Workflow Foundation. During my first steps (kind of hello world examples), some errors occurs ... Sometimes it's hard to resolve some errors...
    Let's have a look at the EventDeliveryFailedException ...

    Has this error ever occured?
    An unhandled exception of type 'System.Workflow.Activities.EventDeliveryFailedException' occurred in System.Workflow.Activities.dll.
    Additional information: Event "AskWorkflowValues" on interface type "App.GeneralLib.IMyService" for instance id "8385d402-19fb-4549-a765-c7e2b4c0a856" cannot be delivered.

    When adding an eventDrivenActivity to a State Machine's worfklow State Activity, you wouldn't receive this exception when firing an event from the host application to the workflow.

    This exception only occurs, in my case, when adding an eventDrivenActivity to the State Machine's workflow self... (and not to a state activity).


    Solution

    The host application fires an event through a local service method. In that method you must specify the ExternalDataEventArgs parameter. Now to resolve the problem you must set the WaitForIdle property of the ExternalDataEventArgs instance.

    If this property is true then the workflow should go idle before raising the event by the host application through the local service. At default, this property is false and the event can only be catched by an EventDrivenActivity within a State Activity. So, in other words the workflow has to process it things first before this event can be deliverd. That's why the WaitForIdle must be true.


    Local Service Interface

    [ExternalDataExchange]
    public interface IMyService
    {
    event EventHandler AskWorkflowValues;
    }


    Local Service implementation

    [Serializable]
    public class MyService:IMyService
    {
    public void OnAskWorkflowValues(ExternalDataEventArgs e)
    {
    if (AskWorkflowValues != null)
    {
    AskWorkflowValues(null, e);
    }
    }



    Host application

    ...
    //calling local service's method to fire an event to the state machine workflow

    localService.OnAskWorkflowValues(GetEventArgs(instance.InstanceId));
    ...

    ExternalDataEventArgs GetEventArgs(Guid instanceId)
    {
    ExternalDataEventArgs e = new ExternalDataEventArgs(instanceId);
    e.WaitForIdle = true;
    return e;
    }

    Wednesday, June 13, 2007

    Debugging Workflows in Visual Studio 2005

    To debug your workflow library, execute following steps:


    1. Compile both projects (GUI/Business Workflow library)

    2. Go the the Workflow Library project's properties

    3. Go to the Debug tab

    4. Set the 'Start External Program' below the 'Start Action' section

    5. Browse to the compiled GUI project and select the executable (.exe).

    6. Make sure that your Business Workflow Library is set as startup project

    Monday, May 07, 2007

    Tuesday, April 17, 2007

    TaskPanes and Javascript in InfoPath 2003

    Using HTML, CSS and JavaScript in Task panes is sometimes very tricky. Some functionalities are not allowed, but InfoPath do not alert errors … frustrating … isn’t it ?

    HTML/CSS samples

    • Show/Hide DIV tags

    Javascript samples

    • onload event of BODY tag
    • javascript included in href attribute of anchor
    • you are not allowed to talk to window.external.Window.XDocument; when using ASP.NET pages in a fully trusted, signed form.

    Printing the Task pane’s content

    Do not add the javascript:window.print() method not to the href attribute of the anchor tag to print … In this way (using href) you are not sure (100%) that the print functionality works! InfoPath 2003 do not generate errors when you try to trigger the print link, but … in Internet Explorer this works perfectly!

    A possible solution is using the onClick event of the anchor tag. In this way you are sure that the window.print() method is called and the Print window will appear.

    There is no other way to print the content of a custom task pane. So use the window.print();


    Export to Word and Excel

    It is quit simple to export your custom task pane content to Word and Excel. Because Word and Excel supports HTML, we can save the content of our custom task pane (html) as Word or Excel document

    Suppose you an ASP.NET web page (.aspx) which button to export content to Word and Excel.

    When the user clicks on the ‘export to Word’ button, we will dynamically add a very small IFrame tag to the page which will call another ASP.NET page. This page is responsible to generate the word or excel document. You can use the QueryString to add a parameter which indicates the type of export (xls/doc).

    Response.AddHeader("content-disposition", "attachment;filename=defaultExportFileName");
    Response.ContentType = @"application/msword";
    Response.Write(“your html content”);

    The Content Types are defined in the register (HKEY_CLASSES_ROOT). Select the .doc or .xls folder and have a look at the Content Type.

    When clicking on the ‘Export to Word’ button, a download window will pop up to open or save your document.

    Use HTML pages in fully trusted, signed forms

    It is impossible to call window.external.Window.XDocument when using an ASP.NET page in a fully trusted, signed form. The external window seems to be unavailable at that moment.

    If we use an static HTML page as Task pane, we can access the external window!
    I suggest to communicate from InfoPath 2003 to the task pane. The communication in the other way is quit difficult if you use fully trusted, signed forms.

    Using parameters in HTML Task Pane

    It is possible to use a QueryString, also with a static HTML page which is included as resource file. Just call aHtmlTaskpaneObj.Navigate("start.html?key=value");

    You can parse the QueryString by using JavaScript. [Read article about parsing javascript]

    Hiding Task panes at startup

    It is not allowed to hide Task Panes in the Start Up method because not all InfoPath objects are loaded at that time. So it is possible that your Task pane is not hidden, when the form is started. The time the task pane needs to hide depends on the form load.

    Thursday, March 29, 2007

    Blogger is integrated in Microsoft Office Word 2007

    Writing blog posts in Microsoft Office Word 2007 is now much easier.



    1. Click on the Office button to select 'New'
    2. Select 'New Blog Post…'
    3. Configure your blog provider (in my case Blogger)





    4. After registrating the blog provider, you are able to publish posts on your blog !



    Taskpanes: Moving, resizing and navigation

    Have you ever had the idea to move your InfoPath 2003 taskpane to the bottom of your screen, to the left or the right?
    A taskpane cannot be moved (in default cases), but by using customized Office code we can do it !

    Move and resize task panes

    using Microsoft.Office.Interop.InfoPath.SemiTrust;
    using Microsoft.Office.Core;
    using System.Reflection;

    //The following function unwraps the CommandBars object so that the CommandBars object
    //is easier to use in the code.
    private CommandBars UnwrapCommandbarsObject(ObjectWrapper commandBarsWrapper)
    {


    //Get the System.Type object for the CommandBars wrapper object.
    Type t = commandBarsWrapper.GetType().BaseType;

    //Use the Type object to retrieve the InnerObject property of the wrapper.
    CommandBars objCommandBars = (CommandBars)t.InvokeMember("InnerObject", BindingFlags.Public BindingFlags.NonPublic BindingFlags.Instance BindingFlags.GetProperty, null, commandBarsWrapper, null);

    //Return the result.
    return objCommandBars;
    }



    //Move/Resize
    private void ButtonClickAction()
    {
    CommandBars objCommandBars = UnwrapCommandbarsObject( (ObjectWrapper) thisXDocument.View.Window.CommandBars);

    CommandBar oCommandBar = objCommandBars["Task Pane"];
    oCommandBar.Width = 600;

    }



    Navigate to website urls
    HTMLTaskPane tp = (HTMLTaskPane)this.thisXDocument.View.Window.TaskPanes[0];
    tp.Visible = true;
    tp.Navigate("
    myWebSite");

    In InfoPath 2007 it would be:
    HtmlTaskPane pane = (HtmlTaskPane)this.CurrentView.Window.TaskPanes[0];


    Requirements

    • You need full trust!
    • Add a reference to COM component -> Microsoft Office 11 Object Library

    Disadvantage

    • Changing the behaviour of your TaskPane at runtime, also effects InfoPath at design time !
      You can only undo the TaskPane customization by re-executing the reversed code.

    Resources

    Tuesday, March 06, 2007

    How to Validate Arguments Of Public Methods? (Microsoft Design - CA1062)

    FxCop can drive you crazy, but ... It improves the quality of your code!
    Tip: enable the Code Analysis in the beginning!

    I am sure that you have ever seen the following FxCop warning:
    Microsoft.Design --> CA1062:ValidateArgumentsOfPublicMethods

    This article gives you a uniform way of validating parameters!


    1. Validating parameters in every public method
    If you have to check every parameter every public method. This means that you add at least 3 lines ...

    Example
    if( condition )
    {
    // exception statement;
    }

    Disadvantages:

    • Re-writing code every time you need to check parameters
    • 3 lines of code extra in every public method which has parameters.

    2. Using the ParameterCheck class for Parameter validations
    You can reduce the 3 lines of code into 1 line. Just make a separate Visual Studio Project which is responsable to check parameters. It is a static class which has static methods.

    ParameterCheck Method Overview

    • NotNullOrEmpty
      Checks if a string is empty or null
    • NotNull
      Checks when an object is null. In case of a DateTime object, it cannot be the MinValue (which will be compared with null)
    • WithinRange (for int)
      Checks if the Int value (16/32/64 bit) has a value within the range (ranges inclusive)
    • WithinRange (for double)
      Checks if the decimal value (decimal, single, float, double) has a value within the range (ranges inclusive)
    • WithinRange (for DateTime)
      Checks if the DateTime value has a value within the range (ranges inclusive)
    • BiggerOrEquals (for int)
      Checks if a number has a value which is bigger or equals to the minimum value (minimum value included)
    • SmallerOrEquals (for int)
      Checks if a number has a value which is smaller or equals to the maximum value (maximum value included)

    Example
    public static void NotNullOrEmpty(string parameterName, string parameterValue)
    {
    if (String.IsNullOrEmpty(parameterValue))
    {
    throw new ArgumentNullException(parameterName);
    }
    }


    Advantages

    • Just 1 line of code!
    • Reusability!
    • Same result
    Disadvantage

    • FxCop/Code Analysis does not recognize your class as being a valid parameter validation. You should add a SuppressMessage (right-click on the warning in the error list and select 'suppress message')

    You can download the code of this article here.

    Thursday, February 22, 2007

    The fabulous 40

    40 application templates for Windows Sharepoint Services 3.0 are available. They are developed with Office SharePoint Designer 2007 and incorporate many of the new features in WSS 3.0.

    You can download them as a single package download. (English version)

    Tuesday, February 20, 2007

    Surviving the MCTS 70-536 exam

    This morning I finally passed Exam 70–536: Microsoft .NET Framework 2.0 - Application Development Foundation. Which is a good start to become Microsoft Certified Technology Specialist: .NET Framework 2.0 Web Applications.

    To study this exam, I used the MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0–Application Development Foundation. A very good study guide to pass this exam!

    Monday, February 19, 2007

    How to manually decoupling your Visual Studio 2005 solution from Visual Source Safe 2005

    Follow these steps to decouple your VS .NET 2005 Solution from Visual Source Safe 2005 by yourself:

    1. First of all: take a backup ! ;-)
    2. Go to the properties of the folder where you can find all your project files.
      Uncheck the 'Read-only' checkbox.
    3. Open the .csproj file and delete following tags
      <SccProjectName>SAK</SccProjectName>
      <SccLocalPath>SAK</SccLocalPath>
      <SccAuxPath>SAK</SccAuxPath>
      <SccProvider>SAK</SccProvider>

      You can find them below the Project > PropertyGroup tags
    4. Delete following files:
      *.vspscc
      *.user
      *.scc

    5. Go to the solution file and delete following lines
      Project
      SccProjectName = ...
      SccAuxPath = ...
      SccLocalPath = ...
      SccProvider = ...

      GlobalSection(SourceCodeControl) = preSolution
      SccNumberOfProjects = ...
      SccLocalPath0 = ...
      SccProjectUniqueName1 = ...
      SccLocalPath1 = ...
      SccProjectFilePathRelativizedFromConnection1 = ...
      SccProjectUniqueName2 = ...
      ...
      SccLocalPath9 = .
      SccProjectFilePathRelativizedFromConnection9 = ...
      EndGlobalSection
    6. Open your solution file again...
      If your solution doesn't want to open Visual Studio, then you have to open Visual Studio 2005 manually.Open the solution file through the Open Dialog in VS 2005.

    Succes!


    Thursday, February 15, 2007

    SharePoint, WebParts, Impersonation and Editing List Items

    What the hell is Impersonation?
    Impersonation is one of the most useful mechanisms in Windows security. It's also fragile and easy to misuse. Careful use of impersonation can lead to a secure, easy-to-administer application. Misuse can open gaping security holes. In fact Bob can be Sarah and Sarah can be Bob :-)

    Impersonation is still useful in some cases. This story is about WSS 2.0/Microsoft Sharepoint Portal Server 2003, but is still interesting for other applications in .NET.

    Suppose ..
    You have to create a webpart which can give users read permissions to certain files or folders.
    You want to store extra information in a custom list with custom properties (from/until/user's full name).

    The SharePoint List, which is the data store, must be synchronized through the webpart. Attention, the user may not modify the list by himself. So in this case, the list is read-only for a certain group of people and the webpart is our user interface, which can modify the list.

    Solution
    To be sure that the current user can only view the list, we will deny the edit list items' permission and only give him the read-only permission on the list.
    Now we have a problem ... How can we write data programmatically to the custom List if you haven't the 'edit list items' permission? Of course, "Bob will we Sarah" ... impersonation !

    Impersonation
    The webpart is running as the current user called Bob. Suppose that 'Sarah' is a 'background user' which has the permission to edit list items. Bob hasn't the permission so ... He transforms into 'Sarah'. Click here to download the Impersonator class which helps you by transforming Bob into Sarah.

    // current user : Bob (read only list permission)

    Impersonator imp = new Impersonator("domain", "Sarah", "password");
    imp.Impersonate();

    // current user : Sarah (edit list permission)
    // => now you can create new list items into the custom list

    imp.Undo();

    // Do not forget to call Undo(). This will stop the impersonation, which transforms Sarah back into Bob.

    Editing List Items and Security conflicts

    Please write the code below after the Impersonate() call and before the Undo() call.
    It seems to be very easy. It is logical ... but permissions are tricky ...


    SPSite site = new SPSite("http://server");
    site.AllowUnsafeUpdates = true; //resolves this problem: The security validation for this page is invalid

    SPWeb web = site.Rootweb;
    SPList list = web.Lists["My Custom List"];

    SPListItem newItem = list.Items.Add();
    newItem["from"] = DateTime.Now;
    newItem["until"] = DateTime.Now.AddDays(10);

    newItem.Update(); // you only need the permission to edit List Items.
    list.Update(); //when updating the list, you need to have the permission to modify List settings
    //in this case we don't need an list update, because Sarah has no sufficient rights.

    Difference between SPListItem.Update() and SPList.Update()

    If you are administrator or another person which can modify the List settings, you can call the SPList.Update() without any problems. SPList.Update() do not only update the data in the list, but also fields and settings. That's why you need some more rights.

    If you can only edit List Items, you need to call the SPListItem.Update() method.

    This is very logical, but so frustrating when receiving an E_ACCESSDENIED exception.


    More Information on SharePoint Security and Impersonation
    Click here to read Jay Nathan's article on 15seconds.

    Tuesday, February 06, 2007

    I've been tagged... siX things you don't know about me

    Did you know ... ?!


    1. ... I love Spain. A great country, The sun and an attractive language! If I have some leisure time I would follow spanish lessons (long term course). Kristof goes latino ;-)

    2. ... I followed 'spanish lessons for travelling' Last year?

    3. ... I love the French wines. The wines in the region Languedoc-Roussillon are absolutely fantastic and fruity. Mmm.. Once I visited a castle in Fitou (the best and sweetest white wine I ever met).

      Tip
      :
      Muscat De Rivesaltes
      http://www.twis.info/wineregion.php?ID=241&action=setLanguage&LANGUAGE=nl

    4. I am very fascinated in trains and miniature trains. Once i had the opportunity to have a ride from Ghent to Ostend with a real Belgian engine.

    5. . Favorite computer games
      - Roller Coaster Tycoon 3
      -
      Sim City 4

    6. I have a Roland Synthesizer (E-60) at home to make some music (yeah ... a keyboard with PS/2 ... ;-)

      (this is the
      renewed design of this keyboard.)

    Now it's my turn to tag some people ;-)

    Tuesday, January 30, 2007

    7 Development Projects for Sharepoint 2007 and Sharepoint Services 3.0

    Thanks to Geert I found this interesting e-book about Sharepoint 2007

    It's a free book about 7 Development Projects for Microsoft Office Sharepoint Server 2007 and Windows Sharepoint Services 3.0

    You can download it
    here

    Querying Data Connections using the InfoPath 2007 Object model

    Web services are completely integrated in InfoPath 2003/2007. We can submit and retrieve data whenever we want. If the current InfoPath functionalities does not satisfy your manager's ideas, you can improve your forms with custom code. Today I show you how to integrate web services by using the InfoPath 2007 Object Model

    Actually, the way you used the Object Model in InfoPath 2003 has been changed since InfoPath 2007 has been released. The new Object Model is completely managed and is integrated with the .NET Framework 2.0 classes (System.Xml namespace)

    Suppose we have a ASP .NET Web Service on server which defines the following web method:

    [WebMethod]
    public string SayHello(string name)
    {
    return "Hello " + name;
    }

    • Now, Open your InfoPath Form Template and add a button on the screen
      (Design Tasks > Controls > Button)
    • Open the Button's properties by double-clicking on the button
    • Click on the 'Edit Form Code...' button to start up the Visual Studio Tools for Applications.
      (you can choose the programming language through the Form Options item in the Tools menu)
    • Add the following lines of code to your button handler:

      //do not forget to import the System.Xml namespace at the top of this class
      using System.Xml;

      //Create Xpath Navigator for WebService Data Source
      //"SayHello" = the name of the data connection

      XPathNavigator nav = this.DataSources["SayHello"].CreateNavigator();

      //Xpath expression to retrieve parameter xml node
      // tns:SayHello = method
      // tns:name = name of the argument at server side

      XPathNavigator webServiceNavi = nav.SelectSingleNode("dfs:myFields/dfs:queryFields/tns:SayHello/tns:name", this.NamespaceManager);

      //set parameter(s)
      webServiceNavi.SetValue("Kristof");

      //retrieve data: call the "SayHello" webservice
      DataConnection conn = this.DataConnections["SayHello"];
      conn.Execute();
    • The web method returns a string. You can drag and drop the dataFields section of your secondary data source (which corresponds to your web service connection) to the screen.

    Attention

    • Using managed code in Browser Enabled Forms needs an administrator approval
    • In browser enabled forms you will mainly use web services to retrieve data
    • Have a special attention for the security issues
      - use Data Connection Files in Data Connection Libraries (UDCX)
      - InfoPath Forms Services makes the big picture more difficult, it introduces a extra tier.

      With InfoPath 2003, you never had to worry about security issues.
      You ran InfoPath on tier 1, and the Web service on tier 2. Now that you are designing forms that run in a web browser, you'll need to think about tier 3.


    Tips

    • Did you know that you can use your 'Receiving Data Connections' to send data? The parameters specified at server side can be used to return a filtered set of data or as input for the database ...
    • Did you know that you can use your own .NET classes or Data Sets as parameter or as return value in web methods? Both are serializable to xml.

    Monday, January 22, 2007

    Creating Custom Taskpanes with .NET User Controls in VSTO

    Developing InfoPath Add-In

    With VSTO 2005 (Visual Studio Tools for Office) you can easily create InfoPath add-ins!
    Watch ...


  • First download VSTO on the Microsoft website (free download)
  • After installation, start up Visual Studio 2005 and select the InfoPath2007 add-in as template.
  • In your project contains 2 methods:
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)

  • Since InfoPath 2007 we can use .NET User Controls as Custom Task Pane. In InfoPath 2003 we had to use JavaScript, ASP.NET or HTML files. We can also use help files (CHM files) as custom task pane.
  • Add a new Item to your project (User Control)You can add Windows controls to this User Control.

  • To show the Custom TaskPane we have to add some code to the ThisAddIn_Startup method.In the Startup method you call the CreateCustomPane() method below:

    private TaskPaneUC tpuc;

    private void CreateCustomPane()
    {
    this.tpuc = new TaskPaneUC();
    this.tpuc.submitEvent += new TaskPaneUC.OnSubmit(tpuc_submitEvent);
    this.tpuc.switchViewEvent += new TaskPaneUC.OnSwitchView(tpuc_switchViewEvent);
    this.tpuc.exitEvent += new TaskPaneUC.OnExit(tpuc_exitEvent);

    this.ctp = this.CustomTaskPanes.Add(tpuc, "Happy 2007");
    this.ctp.Visible = true;
    }
  • For redirecting button actions to the ThisAddIn.cs we use delegates and events.


    Example
    TaskPaneUC.cs
    public delegate void OnSubmit(object sender, SubmitArgs args);
    public event OnSubmit submitEvent;


    ThisAddIn.cs
    private void CreateCustomPane()
    {
    this.tpuc.submitEvent += new TaskPaneUC.OnSubmit(tpuc_submitEvent);
    }
  • Through the User control in this example you can do the following tasks

    • Set a field’s value
    • Switch View

    • Exit application



      Download this example here.

    Installing the InfoPath Add-In

    The add-in will be automatically installed when debugging the application.
    For deployment you can use the Setup project which will be added automatically to your project.


    Uninstalling the InfoPath Add-In


    When you move the InfoPath Add-In project to another location, the Add-in will be automatically deactivated.

    Overview of InfoPath Add-In


    1. Open InfoPath 2007.
    2. Go to the Help menu and select 'Privacy Options'

    Friday, January 19, 2007

    Walkthrough: Publishing administrator-approved form templates

    A. Steps at client-side (for InfoPath developers)

    1. Create an InfoPath form and use managed code (C#) as business logic.The business logic needs full trust on the server to run.

    2. Save your form and publish it to a SharePoint Server with or without InfoPath Forms Services

    3. If you opt for ‘Document Library’ a library will be created or updated and the template can only be used in this library. If you opt for ‘Site Content Type’, you can use your template in multiple document libraries on several sites. A site content type is nothing more than a type of document with some specific properties.
      In this situation you cannot opt to create a document library or a content type because you used managed code. You must select ‘Administrator-approved form template (advanced)’. We need the ‘full trust’ security level to run .NET code.


    4. We can’t publish the form directly on the Sharepoint Server. First of all we must store the InfoPath form to a location which is accessible for the administrator.



    B. Steps at server-side (for administrator)

    1. Go to Central Administrator > Application Management. Select ‘Manage Form Templates’ in the ‘InfoPath Forms Services’ section.

    2. Click on ‘Upload Form template’. The admin must browse to the location where the InfoPath form was stored by the developer.

    3. Open the context menu of the uploaded file in the Form Templates List. Select ‘Activate to a Site collection’. This will publish the InfoPath Form as a Site Content Type to a site collection.

    C. Steps at server-side (for site owners)

    1. Go to the site collection on which you activated the InfoPath form template. Open the list where you want to install the form template.Click on Settings and select ‘Site Settings’. Click on ‘Advanced Settings’ in the ‘General Settings’ section and activate the content type management. (select ‘Yes’)

    2. Now you will be able to manage the Content Types. Click on ‘Add from existing site content types’ to add the activated Form Template as Site Content in this list.




    3. Go back to your list and Click on the ‘New’ Button to start a document based the uploaded Form Template.

    Wednesday, January 10, 2007

    Embedding audio and video in InfoPath 2007 forms

    Microsoft InfoPath 2007 offers now Custom Controls:
    1. ActiveX controls (uses COM and ActiveX technologies)
    2. Template Parts (reusable form pieces)

    --> You can embed audio and video if you use an ActiveX custom control.



    Using ActiveX Custom Controls
    1. Go to menu View
    2. Click on Design Tasks
    3. Select Controls in the 'Design Tasks' Task pane
    4. Click on the 'add or remove custom controls' button to install your custom
    control
    5. Click on the Add button and select ActiveX Control
    6. Select the Windows Media Player control
    7. Select the necessary properties for databinding and finish the wizard.

    After you have added the control, you can drag and drop the control on your screen.
    Right-Click on the control and select the 'Windows Media Player properties'
    Fill in the URL to automatically embed the file to play.



    Attention ...
    ActiveX controls must be installed on each user's computer,
    but you can opt to include a .cab file (which contains the custom activeX control)
    in your template which automatically installs and registers your control.
    (you can specify the .cab file in the 'steps' wizard above.


    ---

    Reference: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1039675&SiteID=1

    VSTA/VSTO problem when installing Office InfoPath 2007 & .NET 3.0 *solved*

    Error message:
    InfoPath cannot start Microsoft Visual Studio Tools for Applications.To work with Visual Basic or C# code, Microsoft Visual Studio Tools for Applications (VSTA) is required. the Microsoft .NET Framework 2.0 and Microsoft Core XML Services 6.0 must be installed prior to installing VSTA. To install VSTA, open Add or Remove Programs, locate your 2007 Microsoft Office System installation, and then click Change [full problem description on Jeroen Ceuppens ' blog]

    The problem has a very simple solution, just respect the way you install the Office products.

    SOLUTION: Please respect the following installation order ...

    1. Install the Microsoft Office 2007 clients
    without .NET programmability support for .NET Framework version 2.0

    2. Install the .NET 3.0 framework
    3. Install the Microsoft Office Sharepoint Portal Server 2007
    4. Go to 'Add or Remove Programs...' and add the '.NET programmability support for .NET Framework version 2.0' right now. The installation makes sure that it has to use the .NET 2.0 framework which is already installed on the computer.

    The ultimate test...
    5. Start up Microsoft Office InfoPath 2007.
    6. Save your blank template on your disk
    7. Go to menu Tools > Programming > Microsoft Visual Studio Tools for Applications

    Information about VSTA - Visual Studio Tools for Applications
    You can find the VSTA executable on this location:
    C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\vsta.exe
    C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\vsta.exe.config
    Have a look at the vsta.exe.config file. You will see that vsta.exe requires the v.2.0.

    <supportedruntime version="v2.0.50727" safemode="true"/>
    <requiredruntime version="v2.0.50727" safemode="true"/>

    Remark
    A better solution would be: first install the Office 2007 server products and afterwards you can install all Office 2007 Clients on it. (I did not test this remark ...)

    Tuesday, January 09, 2007

    Articles: Using .NET applets in browsers & NHibernate explained

    Check out following articles:

    Geert Verhoeven is writing about .NET applets. Simply using .NET controls within your browser. Read the article about his first .NET applet.

    Maarten Balliauw wrote an article about NHibernate, the .NET version of Hibernate.

    VSTA/VSTO problem when installing Office InfoPath 2007 & .NET 3.0 ...

    Jeroen Ceuppens (a collegue) and I experienced some troubles when using Office InfoPath 2007 in combination with .NET 3.0.

    When you try to start up VSTA within InfoPath 2007, you will receive a message which says that VSTA is not installed on your computer yet ... The computer is also complaining about MSXML 6.0... So MSXML 6.0 and VSTA must be installed on your computer ?!

    Jeroen described the whole problem on his
    blog. Please check out and provide us some feedback if possible!