Custom date validation with ASP.NET MVC / Web-Api server and client-side dutch date example

I live in the Netherlands and we have a different way of writing the date then like in the US. For example: 31 January 2012 is like this: 31-01-2012.

To accomplish this to be validated with MVC and Web-Api add a class that will act as an attribute to your project that has the following code:

    public class DutchDateAttribute : RegularExpressionAttribute {       

        static DutchDateAttribute()
        {
            // necessary to enable client side validation
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DutchDateAttribute), typeof(RegularExpressionAttributeAdapter));
        }

        public DutchDateAttribute() : base(@"^([0-9]{1,2})-([0-9]{1,2})-([0-9]{4,4})$")
        {
        }

        public override bool IsValid(object value)
        {
            return true;
        }
    }

Then apply this to your model/viewmodel that containts the DateTime property:

        [DisplayName("Datum/Date")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
        [DutchDateAttribute(ErrorMessage = "Voer een geldige datum in./Enter a valid date")]
        public DateTime StartDate { get; set; }

That’s it! If you use the default jquery.validate.unobtrusive from Microsoft this will be applied as serverside and client side logic.

The only part that is a somewhat strange for me is the override of the IsValid method that always returns true… Maybe somebody that is reading this can explain that to me? I tried to tamper with the date like 50-07-2012 and it was not validated, so that the server validated is still in place even of the return true code.

Note: The regular expression may no be sufficient enough to exclude every situation and possibly can be enhanced.

Posted in ASP.NET, JavaScript, MVC, Web-Api | Leave a comment

HTML checkbox as boolean values with jQuery (using ASP.NET MVC Web-Api)

I like to have my HTML form data to be send in JSON. When reading values from checkboxes with the default jQuery serializeArray you get the value “on” for checkboxes that are checked. In my viewmodel I have boolean properties so they won’t be validated.

Searching on the internet I found various ways to accomplish it. I didn’t want to use yet another library so I wanted a nice jQuery solution.

I combined two solutions that perfectly suited my situation, the result is this little composite jQuery plugin:

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray({ checkboxesAsBools: true});
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });

    return o;
};

$.fn.serializeArray = function (options) {
    var o = $.extend({
        checkboxesAsBools: false
    }, options || {});

    var rselectTextarea = /select|textarea/i;
    var rinput = /text|hidden|password|search/i;

    return this.map(function () {
        return this.elements ? $.makeArray(this.elements) : this;
    })
    .filter(function () {
        return this.name && !this.disabled &&
            (this.checked
            || (o.checkboxesAsBools && this.type === 'checkbox')
            || rselectTextarea.test(this.nodeName)
            || rinput.test(this.type));
    })
        .map(function (i, elem) {
            var val = $(this).val();
            return val == null ?
            null :
            $.isArray(val) ?
            $.map(val, function (val, i) {
                return { name: elem.name, value: val };
            }) :
            {
                name: elem.name,
                value: (o.checkboxesAsBools && this.type === 'checkbox') ? //moar ternaries!
                    (this.checked ? 'true' : 'false') :
                    val
            };
        }).get();
};

Now when I want to send data to my server all I need to supply jQuery is this data:

var data = JSON.stringify($("#myForm").serializeObject();

//TODO make an AJAX call

Note: JSON.stringify is available in modern browsers, use an library if you want to support older browsers. It converts a Javascript object to a string.

Sources that is used:
http://tdanemar.wordpress.com/2010/08/24/jquery-serialize-method-and-checkboxes/

http://css-tricks.com/snippets/jquery/serialize-form-to-json/

Posted in ASP.NET, HTML, JavaScript, jQuery, JSON, MVC, Web-Api | Tagged , , , , , , , , | 6 Comments

SharePoint 2010 – Create Page Layout based on a custom Content Type in Visual Studio 2010

I will describe how I created a Page Layout based on a custom Content Type with SharePoint 2010 (beta2).

 

Content Type

First thing to do is to define a content type.
I will call my Content Type: PicturePageContentType

To do this:
– Go to: Site Settings –> Site content types
– Next, click Create

In the following screen you insert information about the content type.
An import thing to do is let it inherit from the right parent content type.
This needs to be from the group: Publishing Content Types and the parent needs to be Page.

So far nothing special, next I added some non existing columns.
On the following page click Add from new site column.

Define in the screen the follows up the columns that you would like to add to the your content type (Page Layout in the end).

After you added all the columns you needed you can overview it when you’re looking at you content type. You’ll see that I added Page Content, this was one from the already existing site columns.
 

Note: If you added a from column to your page you cannot delete it:) If you want to get rid of it you need to delete the whole content type.


Create the Page Layout

In this part I’m using Visual Studio for this. It’s not the most common way to do it but I want to stay in control of my own files without uploading/approving etc. it in the web browser.

You can do it trough the browser by going to Master pages and page layouts in Site Settings.
Then add a new Page Layout based on the content type, but I’m doing it the hard way.

First of all if you going to do this in Visual Studio you’ll need this extension:
http://visualstudiogallery.msdn.microsoft.com/en-us/990bd0c8-a55b-4643-a35d-88136594c3d9

Now create a SharePoint Project in Visual Studio.
In the Server Explorer you’ll see your SharePoint Connections, then browse al the way to your Content Type you just created.
Right click on it –> Create Page Layout

Note: This option will only be available if you installed the extension. This option will be disabled if you didn’t selected Page as parent of your Content Type.

Keep this file open we’ll save it after we created a Module.

Right click on you SharePoint project –> Add –> New Item –> SharePoint 2010 –> Module
I called the Module: PageLayoutModule

Delete the Sample.txt from the module.

Now save the Page Layout file into the Module, this is a bit strange. To save it to the Module you just created navigate in your save window to your project directory on your local disk and then save it in the Module directory. Now it’s not visible yet in your solution so navigate to the directory again but this time in your Windows Explorer. Right click on your pagelayout.aspx file –> Copy. Finally right click on your Module in the Solution Explorer –> Paste.
Note: If someone knows a more handy way to do this please tell me.

 

Elements.xml

To deploy everything right there need to be some information added to the Elements.xml.

First thing is to edit it like this (except the filename):

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="PageLayoutModule" Url="_catalogs/masterpage">
    <File Path="PageLayoutModule\Picturepagecontenttype.aspx" Url="Picturepagecontenttype.aspx" Type="GhostableInLibrary">
      
    </File>
  </Module>
</Elements>

The following step is to add some properties to the File. These properties are:

<Property Name="Title" Value="Page Layout with picture" />
<Property Name="MasterPageDescription" Value="Page Layout with picture" />
<Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" />
<Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/WelcomeSplash.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/WelcomeSplash.png" />
<Property Name="PublishingAssociatedContentType" Value=";#PicturePageContentType;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F200
7948130EC3DB064584E219954237AF3900A2F715DA6BDAD944B8D20AFA28B7980E
;#"
/>

The Property PublishingAssociatedContentType needs special attention.

The first one (bold) is the name of the Content Type in my case: PicturePageContentType
The second one (bold and underlined) is the Content Type ID.

To get the Content Type ID you can right click on the Content Type in the Server Explorer and then click Properties. In the properties window that popups you can find the the Content Type ID.

Now that we have our Content Type ID we can fill it in into the property value. Your Elements.xml should look something like this.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="PageLayoutModule" Url="_catalogs/masterpage">
    <File Path="PageLayoutModule\Picturepagecontenttype.aspx" Url="Picturepagecontenttype.aspx" Type="GhostableInLibrary">
      <Property Name="Title" Value="Page Layout with picture" />
      <Property Name="MasterPageDescription" Value="Page Layout with picture" />
      <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" />
      <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/WelcomeSplash.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/WelcomeSplash.png" />
      <Property Name="PublishingAssociatedContentType" Value=";#PicturePageContentType;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F200
7948130EC3DB064584E219954237AF3900C10F04A5A63B6E40B4347CDDAF7A0585;#"
/> </File> </Module> </Elements>

 

 

Deploy

The only thing left to do is to deploy it.

Closing comments

The purpose in my case to do all this is to have my Page Layout in my own version control software and not using SharePoint Desinger to change the way my Page Layout looks.

If I forgot anything or you’ve got improvements please tell me so I can make the article better.

Posted in Geen categorie | 4 Comments

SharePoint 2010 change page content data through Object Model / API – Console Application

This took me some time on google / msdn sdk to find out, I like to share it. It is supposed to programmatically change content to existing pages.

First make a console application, set it to .NET Framework 3.5 and the build properties to x64.

This is an example that can be used to get some information about pages in the root site.

If somebody has some improvements or suggestions to make it better, I’d like to hear it.

static void ProcesPageData(string pageName, string contentType, string pageData)
{
    using (SPSite site = new SPSite("http://localhost"))
    {
        using (SPWeb web = site.OpenWeb())
        {
            //Create,retreive the publishingweb
            PublishingWeb pw = PublishingWeb.GetPublishingWeb(web);

            //Retreive all the pages
            List<PublishingPage> pages = pw.GetPublishingPages().ToList();

            //Print the page titles
            foreach (PublishingPage item in pages)
            {
                Console.WriteLine(item.Title);
            }

            //Retreive a specific page
            PublishingPage thePage = pages.Find(delegate(PublishingPage pp) { return pp.Title.Equals(pageName); });

            //If the page exists, go on
            if (thePage != null)
            {
                //If the document already is checkout to you for some reason, check it in
                try { thePage.CheckIn("Checked in through object model " + DateTime.Now.ToString()); }
                catch { }

                //Check the page out
                thePage.CheckOut();

                //For the safety check for the correct contenttype
                if (thePage.ContentType.Name.Equals(contentType))
                {
                    //Write the current data, the SiteColumns here are hardcoded: Page_Content and BottomContent in my case
                    Console.WriteLine("Page_Content: " + thePage.ListItem["Page_Content"].ToString());
                    Console.WriteLine("BottomContent: " + thePage.ListItem["BottomContent"].ToString());

                    //Overwrite the existing data
                    thePage.ListItem["Page_Content"] = pageData;

                    //Update and check it in
                    thePage.Update();
                    thePage.CheckIn("Checked in through object model " + DateTime.Now.ToString());

                    //Publish and approve the page
                    SPFile pageFile = thePage.ListItem.File;
                    pageFile.Publish("Published through object model " + DateTime.Now.ToString());
                    pageFile.Approve("Approved through object model " + DateTime.Now.ToString());

                }
            }
           Console.ReadKey();                   
        }
    }
}

Posted in Geen categorie | Leave a comment

SharePoint 2010 user login check

Check if a user is logged in

If you want to know if a user is logged in or not you can check it with the CurrentUser object from the SPWeb.

Here’s how you do it in an example:

using Microsoft.SharePoint;
 
SPWeb web = SPContext.Current.Web;
if (web.CurrentUser == null) 
    //hide something
else
    //don’t hide something
Remember sometimes the using Microsoft.SharePoint isn’t always default given, if not add it.

Posted in Geen categorie | Leave a comment

SharePoint 2010 custom masterpage with code behind file – Part 2

In part 2 I will tell how I eventually got a code-behind file working on the custom master-page that I deployed trough Visual Studio. To be clear I don’t use SharePoint Designer to customize my master pages so I cannot guarantee that those pages will work.

To completely understand this information I recommend you to read Part 1 first.

The story continues….

 

Add Reference…

The next thing to do is adding a Reference to the SharePoint 2010 project.
This can be done by right-click on References in the Solution Explorer and then –> Add Reference

A new Window will popup arise that look like this:

As far as I know there 2 References that there need to be added:

  • Microsoft.SharePoint.Publishing
    • First select the Browse tab
    • then go to following directory: C:\Program Files\Microsoft Office Servers\14.0\Bin
    • Select Microsoft.SharePoint.Publishing.dll
    • Press the OK button
  • System.Web
    • Repeat the Add reference step
    • Now select the .NET tab
    • Find the System.Web
    • Select it and press the OK button

 

 

 

 

 

 

 

 

 

 

 

 

 

Add object(s) for the code-behind file

In this how-to I will add 2 objects that I will manipulate with the code-behind file.

asp:Label
First I added an asp:Label to the masterpage. I put this above the ribbon section so it will be noticed when it works.

<asp:Label ID="Label1" runat="server" Text=""></asp:Label>

div
I put a simple div around the ribbon so that I can disable the complete ribbon.

<div id="divRibbonContainer" runat="server">
<!-- =====  Begin Ribbon ============================================================ -->

<!-- =====  End Ribbon and other Top Content ============================================================ -->
</div>

The id’s of these objects will be needed for the code-behind file.

The code-behind file

To create a code behind file right-click on the Module in the solution, –> Add –> New Item…

In the following window select on the left Code –> Class and I called the file _starter.master.cs, just like a normal code-behind file.

There are some things that need to be added

  • Add using statements of:
    • System.Web;
    • System.Web.UI;
    • System.Web.UI.WebControls;
  • Make the class public and let it inherit from Masterpage
  • Declare protected objects from the masterpage
  • Add a page_load method

If you’ve done all that your class should look something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MasterPageWithCodeBehind.MasterPageModule
{
    public class _starter : MasterPage
    {
        protected System.Web.UI.HtmlControls.HtmlGenericControl divRibbonContainer;
        protected Label Label1;

        protected void Page_Load(object sender, EventArgs e)
        {
            divRibbonContainer.Visible = false;
            Label1.Text = "Hello World!";
        }
    }
}

 

Retrieving Public Key Token/PublicKeyToken

This is a little bit tricky, this token is needed in the next step when we need to apply the Inherits attribute.

  • First build the project
  • Right-click on the SharePoint 2010 project in the Solution Explorer
    • Click –> Open Folder in Windows Explorer
    • Next open: bin
    • Open: Debug
    • Copy the directory path and paste it into a text editor or something like that
    • Next copy the filename of the <Projectname>.dll file en past it behind the path you just pasted in the text editor
    • The result should be something like this:
      D:\administrator\documents\visual studio 2010\Projects\MasterPageWithCodeBehind\MasterPageWithCodeBehind\bin\Debug\MasterPageWithCodeBehind.dll
  • Next go to Start (Windows start menu)
    • Programs/All programs
      • Microsoft Visual Studio 2010
        • Visual Studio Tools
          • Visual Studio Command Prompt (2010)

You’ll get a dos prompt.
Do the following things:

  • Enter the following command: cd\
  • Next copy your complete directory path including the *.dll from your texteditor
  • Type the following:
    – sn.exe –Tp “<paste your directory + filename in here>”
    Don’t forget the quotes around the directory and filename
    It should look something like this:
    sn.exe -Tp "D:\administrator\documents\visual studio 2010\Projects\MasterPageWithCodeBehind\MasterPageWithCodeBehind\bin\Debug\MasterPageWithCodeBehind.dll"

The output should be something like this:

Copy the Public key token.

Inherits

To combine the code-behind file with the masterpage there need to be an attribute added to the masterpage directive.
The following data is needed:

  • Namespace of the class & Type/Class name (these need to be seperated by a dot) (MasterPageWithCodeBehind.MasterPageModule._starter)
  • Strongname/Assembly in my case was this the same as the projectname (MasterPageWithCodeBehind)
  • Version (Version=1.0.0.0)
  • Culture (Culture=neutral)
  • PublicKeyToken (PublicKeyToken=f8a88530fbc7b81b)In the masterpage navigate to the following:
    <%@ Master language="C#" %>

Add the following Inherits attribute:
<%@ Master language="C#" Inherits="" %>

Now the 5 dots above need to be combined, in my situation it looks like this:
MasterPageWithCodeBehind.MasterPageModule._starter, MasterPageWithCodeBehind, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f8a88530fbc7b81b

Place this as value from the Inherits attribute.

Result

Deploy your SharePoint 2010 project and load the default site.
Your ribbon should be gone and a text like Hello World! should be visible.

The left top corner of my SharePoint 2010 looks like this now:

Posted in Geen categorie | 29 Comments

SharePoint 2010 custom masterpage with code behind file – Part 1

Part 1 – Deploy a custom masterpage on SharePoint 2010 trough Visual Studio 2010

Introduction

Why the creators of SharePoint made it so hard to have an codebehind file for your master I really don’t get, but gladly there’s a way to do it.

This first part will describe how to deploy your own custom masterpage with Visual Studio. I’m not using SharePoint Designer and I like to code everything myself. With SharePoint 2010 and their masterpage uploading system I cannot easily use my own version-control system like subversion. With this work around it is possible

I will tell the steps I needed to do to get a codebehind file for my SharePoint 2010 masterpage.



Getting started

First of all, you need to get SharePoint 2010 installed and Visual Studio 2010.

Next open Visual Studio 2010 and create a new Project.
I choose the language Visual C# on the left, then selected SharePoint –> 2010 and then create an Empty SharePoint Project.
I named the project: MasterPageWithCodeBehind.


After clicking the OK button, you will be asked how and where you want to deploy it, I choose to Deploy it as a farm solution.

 

Module


Right-click on the SharePoint Project in your Solution Explorer on the right then –> Add –> New Item.


You’ll get a new window where you can choose multiple items. I created a module and called it MasterPageModule.


You’ll see that the module is added to your project with a sample file called Sample.txt. There’s also an Elements.xml file in the module, in this file the other files will be registered. I deleted the Sample.txt in my Solution Explorer and Visual Studio automatically removed it from the Elements.xml file.

The next step I did was copying my custom masterpage into the module. This can be done by copying the file from Windows Explorer en then right-click on your Module in the Solution Explorer. I used the masterpage from Randy Drisgill. You can get his minimal masterpage here: Starter Master Page. His blog with very useful tips is: Randy Drisgill SharePoint Branding and Design

After I paste it into my Module my Elements.xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule">
  <File Path="MasterPageModule\_starter.master" Url="MasterPageModule/_starter.master" />
</Module>
</Elements>

In Module this attribute needs to be added: Url="_catalogs/sharepoint".
In File the Url attribute needs to be changed as follows: "_starter.master"
In File also this attribute needs to be added: Type="GhostableInLibrary".
This will make sure that the file will be cached. More info here.


My Element.xml looks like this now:
 

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="MasterPageModule" Url="_catalogs/masterpage">
    <File Path="MasterPageModule\_starter.master" Url="_starter.master" Type="GhostableInLibrary"/>
  </Module>
</Elements>


Feature

In this beta of Visual Studio 2010 a feature is automatically created when I added a Module into the solution. If not you have to create a feature yourself, here’s how you do it: (if there’s automatically added a feature you can skip it and move to the next part)

———-
The final step to do is creating a feature that will configure the masterpage.
Right-click on Features in your Solution Explorer and click Add Feature.


Now a new Feature is created, and the properties window of that Feature has popped up. Underneath the Title, Description and Scope there are 2 large fields. On the left you’ll see the created Module, add this to the left and it should look like this:


———–

 

Next I right-clicked on the Feature1 and then –> Add Event Receiver.

A new window will be open with the content of Feature1.EventReceiver.cs.
Uncomment these methods:

  • FeatureActivated
  • FeatureDeactivating

The code underneath will overwrite the MasterPage variables.
When it is deactivated it will restore the values back to a default SharePoint masterpage.

The code:

—————–

// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb currentWeb = (SPWeb)properties.Feature.Parent;

    currentWeb.MasterUrl = "/_catalogs/masterpage/_starter.master";
    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/_starter.master";
    currentWeb.Update();
}

// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    SPWeb currentWeb = (SPWeb)properties.Feature.Parent;

    currentWeb.MasterUrl = "/_catalogs/masterpage/nightandday.master";
    currentWeb.CustomMasterUrl = "/_catalogs/masterpage/nightandday.master";
    currentWeb.Update();
}

——————-

End of part 1


When this will be deployed, the custom masterpage is loaded instead of the default without uploading/publishing a masterpage trough the web interface, pretty neat huh.

Your SharePoint 2010 site should look something like this now (if you used the same masterpage as I did):

 

This is the first part of how to create a code-behind file and this part is focused on how getting the fundamentals right. The result of following part 1 is a alternative manner to deploy a masterpage.

Here’s Part 2

Posted in Sharepoint 2010 | 29 Comments