InfoPath - check leap year using expression

 

This is a fun one.

  1. Use the undocumented msxsl:utc function, which checks / converts a date into a normalized representation.

    image

  2. So, what will happen if I test it with with a garbage date, say, the 29th of February of 2001, which isn't a leap year?

    image
  3. So just check if the result of the utc function returns empty string or not.

Expression

msxsl:utc(concat(my:year, "-02-29")) != ""

Pasting pictures from clipboard to SharePoint in browser, via Silverlight 5

Silverlight 5 was quietly released to the world to very little fanfare, considering the looming Windows 8 launch with WinRT next year, and the world (at least, Microsoft)'s shift to HTML5.

Still, there are a few gems in this version over Silverlight 4, in particular, you can now run trusted mode in browser, and trusted mode now has access to platform invoke.

That's right, repeat after me: Silverlight, in browser, unmanaged code.

And I just happened to have the perfect problem I've been wanting to solve forever.

 

Problem

One thing that has always peeved me when using the Rich HTML control in SharePoint is when it comes to imbedding images.  You can't easily add a picture to your Rich HTML, you need to open a different browser window, upload the picture, then find a link to that picture and insert it back in the HTML.

CTRL-V

Wouldn't it be nice if you could just paste a picture directly to SharePoint, like you could in Word, or Windows Live Writer.  The end user doesn't need to figure out where the picture will go.  SharePoint will do that.  Such a thing isn't possible with mere HTML since it doesn't support access to binary clipboard, but with Silverlight 5 we can now provide a solution.

 

 

Steps

  1. Configure in browser trusted mode
  2. Setting up Silverlight with native p/invoke calls to access the clipboard
  3. Using GDI to convert clipboard bitmap to a temporary PNG image file
  4. Upload PNG to SharePoint, using SharePoint client object model
  5. Insert HTML image reference in Silverlight Rich Text editor
  6. Update SharePoint page content from Silverlight Rich Text editor

 

 

1. Configure In Browser Trusted Mode

The easy step.  Head over to Silverlight project properties in VS.NET

image

Figure: Silverlight 5 specialty, elevated trust running in-browser.

2. Setting up Silverlight with native p/invoke and talk to the clipboard natively.

 

internal class Native
{
    [DllImport("user32.dll", EntryPoint = "CloseClipboard", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool CloseClipboard();

    [DllImport("user32.dll", EntryPoint = "GetClipboardData", SetLastError = true)]
    public static extern IntPtr GetClipboardData(ClipboardFormat uFormat);

    [DllImport("user32.dll", EntryPoint = "IsClipboardFormatAvailable", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool IsClipboardFormatAvailable(ClipboardFormat format);

    [DllImport("user32.dll", EntryPoint = "OpenClipboard", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool OpenClipboard([In] IntPtr hWndNewOwner);

}

 

In my paste function:

private void Paste()
{
    if (!Application.Current.HasElevatedPermissions)
    {
        MessageBox.Show("No Elevated Permissions - can't do p/invoke :'-(");
        return;
    }
    IntPtr p = IntPtr.Zero;

    bool opened = Native.OpenClipboard(p);

    if (!opened) 
    {
        return; //unhappy
    }

    try {

        if (Native.IsClipboardFormatAvailable(ClipboardFormat.CF_BITMAP))
        {
            IntPtr p4 = Native.GetClipboardData(ClipboardFormat.CF_BITMAP);

            // GASP.  We have a pointer to our bitmap!
        }
    }
    finally 
    {
        Native.CloseClipboard();
    }

}

 

3. Using GDI to convert clipboard bitmap to a temporary PNG image file

It's awesome we have a pointer, but what do we do with it?  This next part eluded me for months, I had to stop work, and go on the Internet to ask for help.  3 months later, at the end of 2011 a reply came through.  Use GDI+ to convert the pointer to a file!  Genius!  Bravo!

Note that in the GDI+ GdipSaveImageToFile call, I use the PNG Encoder - so the bitmap is saved in PNG format in my temporary file.

Oh, right, more native p/invoke, different DLL this time.

internal class Native
{

   ... <snip earlier clipboard p/invoke>
    [DllImport("gdiplus.dll", CharSet = CharSet.Unicode)]
    public static extern int GdipCreateBitmapFromHBITMAP(IntPtr hbitmap, IntPtr hpalette, out IntPtr bitmap);
    [DllImport("gdiplus.dll", CharSet = CharSet.Unicode)]
    public static extern int GdipSaveImageToFile(IntPtr image, string filename, ref Guid classId, IntPtr encoderParams);
    [DllImport("gdiplus.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
    public static extern long GdiplusStartup(out IntPtr token, ref GdiplusStartupInput gdiplusStartupInput, out IntPtr gdiplusStartupOutput);
    [DllImport("gdiplus.dll")]
    public static extern void GdiplusShutdown(IntPtr token);
}

 

IntPtr gdipToken = IntPtr.Zero; ;
string fileName = string.Empty;

try
{

    IntPtr gdiplusStartupOutput;
    GdiplusStartupInput input = new GdiplusStartupInput(1);
    long num0 = Native.GdiplusStartup(out gdipToken, ref input, out gdiplusStartupOutput);

    IntPtr zero = IntPtr.Zero;
    IntPtr palette = IntPtr.Zero;

    int num = Native.GdipCreateBitmapFromHBITMAP(p4, palette, out zero);
    if (num != 0)
    {
        return;
    }

    // JPG Encoder {557CF401-1A04-11D3-9A73-0000F81EF32E}
    // PNG Encoder {557CF406-1A04-11D3-9A73-0000F81EF32E}
    Guid classId = Guid.Parse("{557CF406-1A04-11D3-9A73-0000F81EF32E}");

    fileName = System.IO.Path.GetTempFileName();

    int img = Native.GdipSaveImageToFile(zero, fileName, ref classId, palette);
    if (img != 0)
    {
        return;
    }
}
finally
{
    Native.GdiplusShutdown(gdipToken);
}

 

4. Upload PNG to SharePoint, using SharePoint client object model

 

using(FileStream fs = File.OpenRead(fileName))
{
    SP.ClientContext ctx = SP.ClientContext.Current;

    SP.Web web = ctx.Web;
    SP.List library = web.Lists.GetByTitle("Images");

    byte[] content = new byte[fs.Length];
    var newFile = new SP.FileCreationInformation();
    int dummy = fs.Read(content, 0, (int)fs.Length);
    newFile.Content = content;
    newFile.Url = string.Format("paste_{0}.png", DateTime.Now.Ticks);
    var uploadFile = library.RootFolder.Files.Add(newFile);
    ctx.Load(uploadFile);
    ctx.ExecuteQueryAsync(
        delegate {
            this.Dispatcher.BeginInvoke(() =>
            {

// update our rich text editor in step 5!
            });
        },
        delegate {  // our code don't fail!       
        });

}

 

5. Insert HTML image reference in Silverlight HTML Text editor

I'm using the wonderful free VectorLight.NET Liquid HTML Editor control.  Need free registration.  Supports converting between Rich XAML and HTML formats.  Here I'm inserting a <Xaml><Image /></Xaml>

 

ctx.ExecuteQueryAsync(
    delegate {
        this.Dispatcher.BeginInvoke(() =>
        {
            this.listBox1.Items.Add(uploadFile.ServerRelativeUrl);

            InlineUIContainer container = new InlineUIContainer();
            Uri server = new Uri(ctx.Url);
            string path = string.Format("{0}://{1}{2}", server.Scheme, server.Host, uploadFile.ServerRelativeUrl);
            this.richTextBox1.Insert(string.Format("<Xaml><Image Source=\"{0}\" /></Xaml>", path));
           
        });
    },
    delegate {
   
    });

5.1 Pictures - just to prove it works

image

Figure: Pasting picture into HTML Editor within Silverlight.

image

Figure: My SharePoint image library, filled with pasted images :-)

image

Figure: Dumping Editor's HTML to MessageBox - you can see the <img> HTML is inserted properly.

 

6. Update SharePoint page content from Silverlight Rich Text editor

This part is the most ugly bit of the code.  Heavily nested since I keep using anonymous delegates, and it's pretty late so I'm not going to clean it up tonight.

The Save button click.


private void buttonSave_Click(object sender, RoutedEventArgs e)
{
    var ctx = SP.ClientContext.Current;
    var library = ctx.Web.Lists.GetByTitle("Site Pages");
    var items = library.GetItems(SP.CamlQuery.CreateAllItemsQuery());

    var filepath = this.autoCompleteBox1.Text;  // I store a list of pages in the dropdown...
    ctx.Load(items);

    ctx.ExecuteQueryAsync(
        delegate
        {
            // switch back to UI thread
            this.Dispatcher.BeginInvoke(() =>
            {
                SP.ListItem page = null;
                foreach (var item in items)
                {
                    // super ugly code - should filter the files in the CamlQuery above - but too tired to write Caml
                    if (item["FileLeafRef"].ToString() == filepath)
                    {
                        page = item;
                    }
                }
                page["WikiField"] = this.richTextBox1.HTML;
                page.Update();  // update SPListItem, then ExecuteQuery to push the update back through ClientService.svc
                ctx.ExecuteQueryAsync(
                    delegate
                    {
                        // switch back to UI thread

                        this.Dispatcher.BeginInvoke(() =>
                        {
                            // refresh browser
                            HtmlPage.Document.Submit();
                        });
                    },
                    delegate { });
            });
        },
        delegate
        {
        });
}

 

image

Figure: The Silverlight webpart pushing HTML back into a Wikipage

 

 

There are some notes on security, which I leave right at the end, but this is important.

Trusted mode / In Browser

  1. When running under http://localhost/ SL5 skips checking this (easy for debug)
  2. For normal operation, requires Silverlight XAP file to be signed with a code trust certificate.  You can generate one yourself, just make sure you add it to the right store.
    image
    Figure: Yes... Trusted Root Certification Authorities.  Yep sounds about right!
  3. And requires a registry key to be present for Silverlight
    image
    FIgure: OMG #1, Registry, really!?
  4. You will need to deploy this to your uses via a group policy, or a click once application if your user has permissions to write to their own registry. 

This bit I think is the part that makes the solution safe, but also very difficult to deploy.  But if you want the nice editing experience with paste functionality, here you go!

 

 

Downloads

  • XAP file (Contact me for the XAP file - it needs a bit of cleaning up, and I need to test the certificate)
  • SPClip cert

 

And here we go, first big post of the year.  Have a great 2012 everyone!

SharePoint - disguise your long running AJAX calls

I have to confess I haven't had so much laugh in SharePoint for a long time.

OK, here's the problem:

  1. I'm calling a custom REST service that I've developed - the REST service checks a bunch of database records, as well as creating a new site and activate a number of features on that site. 
  2. Basically, it takes a while to run.  May be around 15 seconds.

 

image
Figure: Once you click this link it gets busy on the server.

image
Figure: Once it's clicked, I disable the link

Put up a dialog to tell the user to wait

The first thing we should do is put up a dialog to tell the user hey something's happening.

Waldek Mastykarz has an awesome article on how to do most of this, so I won't type out his code.  http://blog.mastykarz.nl/sharepoint-2010-ui-tip-non-obtrusive-progress-messages/

image 
Figure: Here's my blocking dialog.  No close box.  It spins for about 15 seconds and then disappears when the AJAX call receives a success response.

 

But waiting for 15 seconds really gets boring.

You realize that you must use better messages, and update it as you wait. 

image

image

image

 

Here's the javascript code.

 

    var msgs = [
        "Calculating web paths",
        "Negotiating with site collection",
        "Creating empty site template",
        "Activating Features",
        "Synchronizing template",
        "Setting up form libraries",
        "Copying pages",
        "Configuring webparts",
        "Chasing chickens"];   
   
    var p = function(){
        if (waitDialog) {
            var msg = msgs[Math.floor(Math.random()*msgs.length)];
            waitDialog.get_html().getElementsByTagName('TD')[1].innerHTML = msg;
            setTimeout(p, 1000);
        }
    };
    setTimeout(p,1000);

Create an array of status messages - these (aside from the chicken) are really what the REST service is doing.  I also create a function p, which choses a random message and updates the waitDialog.  Repeat every second.  When the AJAX call completes, it destroys the waitDialog, and set it to null.  This stops the setTimeout loop.

 

Some sort of magic happened

Suddenly, because things are updating on screen, the process doesn't seem long at all.  You click it, a few messages flash past, before you know it the site's created and ready to go.

So there you have it, the trick really is just a clever disguise. 

You show users random messages and distract them from the fact that they have to wait for 15 seconds.

InfoPath - Concat SharePoint list with the Eval function (aka Voodoo)

 

It really can't hurt to play with the crazy XPath capabilities within InfoPath.  This is documented in many places, starting:

http://blogs.msdn.com/b/infopath/archive/2006/04/05/569338.aspx

Which offered possibly the best explanation of how this technique with Eval() actually works.  I prefer to remembered this as PURE VOODOO.

 

1. Create our SharePoint list

image

 

2. Create a secondary data connection to the list

image

image

 

3. Drag the dataFields section into the form, to create a common binding parent

image

This step makes step 4 a lot easier, since the Eval loop is relative and works on the repeating section inside the dataFields section.

 

4. Add expression box within this Section

image

The Expression is:
xdMath:Eval(xdMath:Eval(d:SharePointListItem_RW, 'concat(d:Title, ":")'), "..")

 

5. Result:

image

InfoPath - managing lots of tooltip in your browser form

This is an idea that I've been brooding for a long time.  Finally got a prototype implemented.

 

We have a complicated looking InfoPath form.  We've always wanted to have lots of help (i) tooltips.  The picture below alone has 24 information tips.

image

 

The original plan is to use an Picture button, set the image to the image resource (so that they all share the same resource), and manually add tooltips to each button.

image

This approach works OK, but is very tedious.  Each one of our views are massive, and we have about 10 of them.  Some fields re-appear on different views and need to have the same tooltip.  This is also not very manageable - we can't modify the tooltip easily without republishing the InfoPath form.

 

An idea begin brewing by combining an external XML file along with the Rich HTML control, something that I've experimented recently.

/blog/2011/5/30/infopath-2010-embed-html-for-rich-and-web-forms.html
/blog/2011/10/12/infopath-an-example-of-using-an-xml-file-for-special-charact.html

 

Idea!

  1. Produce an XML file that has all our tooltips.
  2. Store this file in SharePoint
  3. In InfoPath, connect to this XML file as an external datasource, always load it from server
  4. Bind the XML fields to Rich HTML controls

 

1. My tooltip XML file. 

My XML file, with 2 entries in it for "office" and "state". 

Note the content of the two entries is essentially a HTML IMG tag.  With the source pointing to an image stored in SharePoint, and a tooltip.

<?xml version="1.0" encoding="utf-8"?>
<html>
  <office>
   <img xmlns="http://www.w3.org/1999/xhtml" src="/Style Library/Images/info.png" border="0" title="Select the Office that will administer this project" />
  </office>
  <state>
    <img xmlns="http://www.w3.org/1999/xhtml" src="/Style Library/Images/info.png" border="0" title="Select the State that this project will report to" />
  </state>
</html>

 

2. Store this file in SharePoint

I store this in SharePoint, on /Style Library/html-tooltip.xml.

image

 

3. Add secondary data source in InfoPath

Add XML datasource.

image

Select "Access the data from specified location"

image

Always retrieve data

image

Result data connection

image

 

4. Bind to Rich HTML controls

Switch to the secondary data source in the Fields tool pane.
Drag my new entry for "State" with the right click contextual menu.
Select Rich Text Box

image

 

There's quite a bit of clean up to do:
image

  • Remove the label
  • Set the background shade to No Fill
  • Set border to 1px solid white - you must keep 1px border, otherwise when you hover over the picture the Rich Text box will shift as InfoPath adds a focus to the box.
  • Set the height and width to 25px (size of my images).
  • Select Read-Only in the ribbon
    image
  • The result:
    image

 

Extra Note

You must show the web form Ribbon, otherwise the Rich Text is rendered differently in an iFrame, and the IMG tooltip won't show up.  Sorry, this behaviour is so weird, I do have an ugly workaround but I won't publish it - really ugly.

image

 

See it in action:

image

 

And if you need to change the text, open up the XML file in SharePoint designer, change it, and save the XML file again.

image

image

 

Summary

  • A technique to use one XML file in SharePoint to specify many HTML tooltip elements to be used within an InfoPath form
  • This allows tooltips to be updated independently of templates, and multiple elements in the InfoPath form can share and reuse the same tooltip