Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Tuesday, October 10, 2017

SharePoint 2010 - How to check if group exists without exception

The SharePoint Server handles some things differently than you might know from standard C # programs.
I recently stumbled upon that I've tried to determine if a user group exists in SharePoint. I thought no problem and tried it with this code:

string nameOfGroupToCheck = "Test Group";
SPGroup group = spWeb.Groups[nameOfGroupToCheck];
if(group != null) {
   ...
}

I assumed that the variable group is null if the group is not present, but SharePoint throws an exception instead.
This does not happen with the following code snippet:

using System.Linq;
...
string nameOfGroupToCheck = "Test Group";
if (spWeb.Groups.OfType<SPGroup>().Where(g => g.Name == nameOfGroupToCheck).Count() > 0)
{
  ...
}

To get this code work correctly, you need to add the System.Linq namespace into your code.

By the way, this check also works with lists in SharePoint. You would only have to query the lists instead of the groups.


Tuesday, July 5, 2016

SharePoint 2010 - New Feature in already deployed solution does not appear




Yesterday, I have created a new feature in an existing SharePoint 2010 solution.
I wrote my code and added the parts to the feature. When I finished my work, I update the solution as usual with this code:

Update-SPSolution -Identity mysolution.wsp -LiteralPath "C:\C#\_DN\MySolution\MySolution\bin\Debug\mysolution.wsp" -GACDeployment

Next, I went to the site collection features and wanted to activate it, but the feature was not appearing in the site collection feature list. What the ...!?!?

After a short Google search I found a solution for this problem.  We need to execute some commands in the PowerShell (SharePoint 2010 Management Shell):

Install-SPFeature -ScanForFeatures

This command will list all not installed features.
You will find your new feature in this list. Now you can install it with the following command:

Install-SPFeature -AllExistingFeatures

After successful execution of this command your feature will appear.

Friday, June 24, 2016

SharePoint - JavaScript - Get parameter from current URL

Today, just one short code snippet to read out an URL parameter with the SharePoint JavaScript libraries:

GetUrlKeyValue(parameter, noDecode, url) is a JavasSript function which we can use to get a query string parameter either from url in the browser or a url we specify.

parameter (string): Query string parameter from the url. 
noDecode (bool)(optional): Specifies whether the value has to be encoded or not. If false value is decoded, else returned as it is. 
url (string)(optional): the url from which Query string values are to be retrieved.(Optional)

Example:

alert(GetUrlKeyValue('a', false, 'www.abc.com?a=te%20sting'));
The above statement will return the value ‘te sting’ from the url paramter a. Here we are specifying our own url.


alert(GetUrlKeyValue('a', false));
The above statement will look for a query string variable a in the browser url, and returns the decoded value.


alert(GetUrlKeyValue('a'));
The above statement will look for a query string variable a in the browser url.

Wednesday, January 6, 2016

SharePoint 2010 - How to check if SPGroup exists

I've tried to check, if a SPGroup exists this way:

string nameOfGroupToCheck = "My SPGroup";
if(spWeb.Groups[nameOfGroupToCheck] != null)
{
...
}

...but this causes an exception, when the SPGroup is not existing.
Try this one:

string nameOfGroupToCheck = "My SPGroup";
if (spWeb.Groups.OfType<SPGroup>().Where(g => g.Name == nameOfGroupToCheck).Count() > 0)
{
...
}

Tuesday, November 24, 2015

SharePoint 2010 - Tutorial - Hiding Ribbon Items

Today I want to show you, how you can hide items from the ribbon bar.
We start as usual with an empty SharePoint project.
Add a new item to the project: User Control and give it a name (i.e. "RibbonControl.ascx").


Add the "Microsoft.Web.CommandUI.dll" reference from "c:\program files\common files\microsoft shared\web server extensions\14\isapi"-folder to your project.



Then open the code-behind file. In my case it is "RibbonControl.ascx.cs".


Add the following namespaces to your code:

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Web.CommandUI;

Use the ribbon.TrimById() method to hide items in the ribbon bar.
Here are some examples. See a full list of all ribbon items here:

https://msdn.microsoft.com/en-us/library/office/ee537543(v=office.14).aspx

protected void Page_Load(object sender, EventArgs e)
{
            try
            {
                SPRibbon ribbon = SPRibbon.GetCurrent(this.Page);
                using (SPSite site = SPContext.Current.Site)
                {
                    //"Documents"-tab
                    ribbon.TrimById("Ribbon.Documents.Copies");
                    ribbon.TrimById("Ribbon.Documents.Workflow");
                    ribbon.TrimById("Ribbon.Documents.Share");
                    ribbon.TrimById("Ribbon.Documents.Manage.ManagePermissions");
                    ribbon.TrimById("Ribbon.Documents.TagsAndNotes");

                    //"Library"-tab
                    ribbon.TrimById("Ribbon.Library.ViewFormat");
                    ribbon.TrimById("Ribbon.Library.Share");
                    ribbon.TrimById("Ribbon.Library.Datasheet");
                    ribbon.TrimById("Ribbon.Library.Actions");
                    ribbon.TrimById("Ribbon.Library.CustomizeLibrary");
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
}

Then your user control is ready now.
The next step is to add your user control whereever you need it, i.e. to your master page, page, web parts etc..
To deploy a custom master page, see my blog post http://me-and-my-sharepoint.blogspot.de/2015/11/sharepoint-2010-tutorial-deploying.html
You can also use SharePoint Designer to modify a page.

I deployed a custom master page to hide ribbon items in all document libraries in a site collection.
Register the user control at the top of the page:

<%@ Register TagPrefix="custom" TagName="RibbonBarControl" src="~/_controltemplates/TestRibbonsHideProject/RibbonControl.ascx" %>




We've created user control for SharePoint 2010, registered it on the page. Now, the final step is to  include the user control in the page itself:


<custom:RibbonControl id="RibbonControl1" runat="server"></custom:RibbonControl>



Then we are ready to deploy the solution.

See the ribbon bar before activating our user control:



Then afterwards:



Hope you enjoyed it. Feel free to leave a comment, if you like (or not) ;-)

Friday, November 20, 2015

SharePoint 2010 - Tutorial - Deploying a custom master page

Please feel free to comment my new tutorial "Deploying a custom master page" in a SharePoint 2010 enviroment. Enjoy.

The first step is to add feature to your project, if you have not already one. 
I created an empty SharePoint project for this tutorial.


Ensure, that the feature scope is set to "Site" to apply the master page to all webs in this site collection.


Then add a "Module" to the project. You can give any name:


After the module is created it contains an "elements.xml" and "sample.txt" file. The "sample.txt" file can be renamed to "sample.master".

Your project then should cotain these elements:


Best practice: Open the SharePoint Designer, navigate to the current master file and edit it.
Note: In SharePoint 2010 the default master page is "v4.master" and NOT "default.master"



Copy the contents of "v4.master" in your "sample.master" and do your changes on the code.

Then make sure, that your "elements.xml" of the module looks like this:



<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="Module1" List="116" Url="_catalogs/masterpage">
  <File Path="Module1\sample.master" Url="sample.master" Type="GhostableInLibrary" IgnoreIfAlreadyExists="FALSE" />
</Module>
</Elements>
You could stop here and this solution will deploy your "sample.master" master page to the master page gallery of your site collection. 
This will not apply the master page to the site collection when the feature gets activated though. It will only make it available for selection.

If you want to apply your "sample.master" file, when the feature gets activated, add an event receiver to your feature via right-click on the feature and selection "Add Event Receiver".


Open "Feature1.EventReceiver.cs" and comment in "FeatureActivated" and "FeatureDeactivating" methods. Then paste the following code in it:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
            try
            {
                using (SPSite site = (SPSite)properties.Feature.Parent)
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        // Create full master url
                        Uri masterUri = new Uri(web.Url + "/_catalogs/masterpage/sample.master");

                        // Master page used by all forms and pages on the site that are NOT publishing pages
                        web.MasterUrl = masterUri.AbsolutePath;

                        // Master page used by all publishing pages on the site
                        web.CustomMasterUrl = masterUri.AbsolutePath;
                        web.Update();
                    }
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
            try
            {
                using (SPSite site = (SPSite)properties.Feature.Parent)
                {
                    using (SPWeb web = site.RootWeb)
                    {
                        // Create full master url
                        Uri masterUri = new Uri(web.Url + "/_catalogs/masterpage/v4.master");

                        // Master page used by all forms and pages on the site that are NOT publishing pages
                        web.MasterUrl = masterUri.AbsolutePath;

                        // Master page used by all publishing pages on the site
                        web.CustomMasterUrl = masterUri.AbsolutePath;
                        web.Update();
                    }
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
}



If you activate the feature, the code in the feature receiver will be executed and will apply "sample.master" to the site collection. As you can see we change both the MasterUrl and the CustomMasterUrl. The MasterUrl is used on all pages that are not publishing pages. This means it is used on the pages in the sitepages library and on the pages in the _layouts directory like the settings page for instance. The CustomMasterUrl is only used on pages that are stored in the Pages library. This library is created when the SharePoint Server Publishing Infrastructure features is activated on the site collection and the SharePoint Server Publishing feature is activated on the site.

Tuesday, July 22, 2014

SharePoint 2010 - JavaScript Client - Updating items with visual feedback to user

I had created a custom action for a document library in SharePoint 2010.
When the user presses the custom action button in the ribbon bar, the selected documents should be updated in a special field ("Document Status").
I noticed, that the procedure to update the selected documents takes long time. During the update process the user cannot see what is happening, because of the asynchronous update request via JavaScript.
I thought, this is not very user-friendly, so I created a screen, where the user can see what the system is doing in this moment.
Here is my code with some screenshots.

function ApproveDocuments() {
    var ApprovalProcess = this;
    ApprovalProcess.SiteCollectionUrl = '';
    var counter = 0;
    var fileItems = [], item, docsSentToApproval = [];

    var ClientContext = SP.ClientContext.get_current();
    var LibraryID = SP.ListOperation.Selection.getSelectedList();
    var Library = ClientContext.get_web().get_lists().getById(LibraryID); //Gets the current Library
    var SelectedDocuments = SP.ListOperation.Selection.getSelectedItems(ClientContext);
    var SiteCollection = ClientContext.get_site();
    ClientContext.load(SiteCollection);
    ClientContext.executeQueryAsync(function (s, a) {
        jQuery('#myCloseInfoDivButton').click(function () {
            window.location.href = SiteCollection.get_url() + '/Lists/Document Center';
            ApprovalProcess.SiteCollectionUrl = SiteCollection.get_url();
        });
    });

    var newDiv = '<div id="myCoverAll" style="background-color:#182738;width:100%;height:100%;position:fixed;top:0px;left:0px;display:block;z-index:1000;filter:alpha(opacity=70);-ms-filter:alpha(opacity=70);opacity:0.7;"></div>';
    newDiv += '<DIV id="myInfoDivContainer" class="ms-dlgBorder" style="background-color:#ffffff;HEIGHT: 345px; WIDTH: 609px; position:absolute; left:50%; margin-left:-304px; top:50%; margin-top:-172px;z-index:1001;">';
    newDiv += ' <DIV class="ms-dlgTitle" style="CURSOR: default; WIDTH: 609px">';
    newDiv += ' <SPAN class="ms-dlgTitleText" id="dialogTitleSpan" style="WIDTH: 545px">Approve Documents</SPAN>';
    newDiv += '</DIV>';
    newDiv += '<DIV id="myInfoDivData" class="ms-dlgFrameContainer" style="background-color:#ffffff;padding-top:20px;"></DIV>';
    newDiv += '<div id="myButtonCloseDiv" style="position:relative;width:100px;left:50%;margin-left:-50px;background-color:#ffffff;padding-top:20px;"><input class="ms-toolbar" type="button" name="myCloseInfoDivButton" id="myCloseInfoDivButton" value=" Close " /></DIV>';
    newDiv += '</DIV>';
    jQuery("#aspnetForm").after(newDiv);
    if (SelectedDocuments.length > 0) {
        jQuery('#myCloseInfoDivButton').attr('disabled', 'disabled');
    }

    for (var currentItem in SelectedDocuments) {
        item = Library.getItemById(SelectedDocuments[currentItem].id);
        fileItems.push(item);
        ClientContext.load(item, 'FileLeafRef','Id','DocumentStatus');
    }

    var newElementHtmlHeader;
    newElementHtmlHeader = '<div style="position:relative;width:100px;left:50%;margin-left:-50px;display:block;vertical-align:middle; text-align:center;" id="myLoadingBar"><img src="' + ApprovalProcess.SiteCollectionUrl + '_layouts/images/mySPProject/busy.gif" /><br />Loading...</div>';
    newElementHtmlHeader += '<div style="font-weight:bold;float:left;padding:3px;width:50px;display:table-cell; vertical-align:middle; text-align:center;">Approval Status</div>';
    newElementHtmlHeader += '<div style="font-weight:bold;float:left;padding:3px;">Document</div>';
    newElementHtmlHeader += '<div style="font-weight:bold;float:left;padding:3px;"></div>';
    newElementHtmlHeader += '<div style="clear:both;"></div>';
    jQuery("#myInfoDivData").append(newElementHtmlHeader);

    ClientContext.executeQueryAsync(Function.createDelegate(this, function () {
        var newElementHtml;
        for (var i = 0; i < fileItems.length; i++) {
            newElementHtml = '<div style="float:left;padding:3px;width:50px;display:table-cell; vertical-align:middle; text-align:right;" id="item' + fileItems[i].get_id() + '">';
            if (fileItems[i].get_item('DocumentStatus') != 'Waiting for Approval') {
                newElementHtml += '<img src="' + ApprovalProcess.SiteCollectionUrl + '_layouts/images/mySPProject/docError.png" style="border:0px;width:15px;height:12px;" alt="Document approval error"></img>';
            }
            newElementHtml += '</div>';
            newElementHtml += '<div style="float:left;padding:3px;">' + fileItems[i].get_item('FileLeafRef') + '</div>';

            if (fileItems[i].get_item('DocumentStatus') == 'Waiting for Approval') {
                newElementHtml += '<div style="float:left;padding:3px;" id="approvalStatus' + fileItems[i].get_id() + '">';
                newElementHtml += '</div>';
            }
            else {
                newElementHtml += '<div style="float:left;padding:3px;color:#F60000;" id="approvalStatus' + fileItems[i].get_id() + '">';
                newElementHtml += 'Error: Document not in "Waiting for Approval"-State';
                newElementHtml += '</div>';
            }
            newElementHtml += '<div style="clear:both;"></div>';
            jQuery("#myInfoDivData").append(newElementHtml);
            if (fileItems[i].get_item('DocumentStatus') == 'Waiting for Approval') {
                fileItems[i].set_item('DocumentStatus', 'Approved');
                fileItems[i].update();
                docsSentToApproval[counter] = fileItems[i];
                counter++;
            }
        }
        ClientContext.executeQueryAsync(Function.createDelegate(this, function () {
            for (var i = 0; i < docsSentToApproval.length; i++) {
                jQuery('#item' + docsSentToApproval[i].get_id()).html('<img src="' + ApprovalProcess.SiteCollectionUrl + '_layouts/images/mySPProject/docApproved2.png" style="border:0px;width:15px;height:12px;" alt="Document approved"></img>');
                jQuery('#approvalStatus' + docsSentToApproval[i].get_id()).css('color', '#368131');
                jQuery('#approvalStatus' + docsSentToApproval[i].get_id()).html('Success');
                if(i == (docsSentToApproval.length - 1))
                {
                 jQuery('#myCloseInfoDivButton').removeAttr("disabled");
                 jQuery('#myLoadingBar').css('display','none');
                }
            }
        }), Function.createDelegate(this, function (sender, args) {
            // handle error somehow
        }));
    }), Function.createDelegate(this, this.onLoadItemFailure));
}

and here how it looks like:

Full Screen Layer with "PopUp"


After updating the properties of the selected documents

Maybe this is useful for someone.

Friday, June 13, 2014

SharePoint 2010 - Building Custom Actions in Visual Studio

Today I will show how you can add custom actions to the ribbon bar and the edit control block in SharePoint.

We have to start with creating an empty element in the project. Then replace the text in the xml file with this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
  Description="Approve Documents"
  Title="Approve Documents"
  Id="RibbonDocumentsManageApproveDocuments"
  Location="CommandUI.Ribbon"
  RegistrationId="10000"
  RegistrationType="List"
  Sequence="0"
  xmlns="http://schemas.microsoft.com/sharepoint/">
    <CommandUIExtension xmlns="http://schemas.microsoft.com/sharepoint/">
      <!-- Define the (UI) button to be used for this custom action -->
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
          <Button Id="Ribbon.Documents.Manage.ApproveDocuments"
          Command="{4E2F5DC0-FE2C-4466-BB2D-3ED0D1917763}"
          Image32by32="~site/_layouts/Images/SharePoint-Z-Drive-Project/approve_document_32x32.png"
          Image16by16="~site/_layouts/Images/SharePoint-Z-Drive-Project/approve_document_16x16.png"
          Sequence="0"
          LabelText="Approve Documents"
          Description="Approve Documents"
          TemplateAlias="o1" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <!-- Define the action expected on the button click -->
        <CommandUIHandler Command="{4E2F5DC0-FE2C-4466-BB2D-3ED0D1917763}" CommandAction="javascript:window.open('http://www.bing.com/search?q='.concat(escape(document.title)))" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

  <CustomAction
  Description="Approve Document"
  Title="Approve Document"
  Id="EditControlBlockApproveDocument"
  Location="EditControlBlock"
  RegistrationId="10000"
  RegistrationType="List"
  ImageUrl="~site/_layouts/Images/SharePoint-Z-Drive-Project/approve_document_16x16.png"
  Sequence="1101"
  xmlns="http://schemas.microsoft.com/sharepoint/">
    <CommandUIExtension xmlns="http://schemas.microsoft.com/sharepoint/">
      <!-- Define the (UI) button to be used for this custom action -->
      <CommandUIDefinitions>
        <CommandUIDefinition Location="EditControlBlock">
          <Button Id="EditControlBlock.ApproveDocument"
          Command="{F8C45D3A-A00D-4412-91BB-C49D75A36F3A}"
          Sequence="1101"
          LabelText="Approve Document"
          Description="Approve Document"
          TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <!-- Define the action expected on the button click -->
        <CommandUIHandler Command="{F8C45D3A-A00D-4412-91BB-C49D75A36F3A}" CommandAction="javascript:window.open('http://www.bing.com/')" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>

The first custom action is to add the button to ribbon bar in the document library. 
The second custom action will add the button to the edit control block of an item.

Wednesday, June 11, 2014

SharePoint 2010 - Tutorial - Create an event receiver with custom error message on redirect url while item updating

Today I would like to show you, how you can use event receivers to check documents / items in a list and give the user immediately a feeback about an error, while he is still in the edit form of the item / document.
That can be useful for users, because they don't leave the edit form and can correct the error immediately without opening the edit mask again.
We start with an empty SharePoint Project in Visual Studio 2010.


Set a project name ("SPProject"), then provide the url and set the trust level ("Farm solution").


The first step is to add the list definition with list instance to our project. That will be our list, where the event receiver will be listen on. Right-click the project name in the project explorer and choose "Add" -> "New Item".


From the list select "List Defintion" and set a name for it ("ListDefinition"), then press "Add".


On the next screen you have to enter a name for the list definition ("SPProject - ListDefinition"). Also you have to choose, which type the list should be. In my case it was a document library, but you can use other types as well. Ensure that the box "Add a list instance for the list definition" is ticked.


After we have added the list defintion, we can add our event receiver. The event receiver will check our doucment and return an error to the edit form, when the item / document is not ok. So we right-click again on the project name in the project explorer and choose "Add" -> "New Item" again.


Now we choose "Event Receiver" from the list and set again a name ("EventReceiver").


On the next screen, we have to decide, which type of event receiver we would like to have. We want the event receiver to check the items of a list - so our choice is "List Item Events".
Then we have to tell SharePoint on which list the event receiver should listen. That is our created list instance from our list definition ("SPProject - ListDefinition").
The last point we have to decide, when the event receiver should start its work. We select "An item is being added".


In the file "EventReceiver.cs" we can add now our code, our logic to check the item / document.
I keep it simple for this example. I will only check if the title property starts with the word "SharePoint", otherwise I want to give an error message to the user. You can put in there more complex logic according to your needs.
Open the "EventReceiver.cs" and search for the method "ItemUpdating". Overwrite the method with your code:

/// <summary>
/// An item is being updated.
/// </summary>
public override void ItemUpdating(SPItemEventProperties properties)
{
  try
  {
    base.ItemUpdating(properties);
    // ensure that the code will be executed only once
    if ((properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null) || (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] == null))
    {
      // check title property
      if (properties.AfterProperties["vti_title"].ToString().StartsWith("SharePoint") == false)
      {
        // redirect
        properties.RedirectUrl = @"EditForm.aspx?"
                                 + "Mode=Upload"
                                 + "&CheckInComment="
                                 + "&ID=" + properties.ListItem.ID
                                 + "&RootFolder=%2Fsites%2FIT%2FLists%2FSPProject-ListInstance1"
                                 + "&IsDlg=1"
                                 + "&ContentTypeId=" + properties.ListItem.ContentType.Id
                                 + "&IsDlg=1";
        properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
       }
      }
     }
     catch (Exception exp)
     {
       throw exp;
     }
 
}
I use the property "vti_sourcecontrolcheckedoutby" to ensure that the code is executed once and nor multiple times. If you have enabled versioning in your list, the event will be fired muliple.
Then I use the AfterProperties to check the title. If the check fails, SharePoint should redirect the user to a specific url. We set the url to our editform.aspx of the list. 
Note: You have to check the bold marked area in the code (RootFolder parameter). You have to change this to your list url!

Now we can start the solution. Navigate to the list, add an item and edit the properties afterwards. You will see that the title have to start with the word "SharePoint", otherwise the popup comes up again when saving.


But we still have no error displayed to the user. The user would be confused now, because he don't knows what is wrong and why he cannot save the properties.

To display an error on the editform.aspx of the list, we create a simple visual webpart.
We add another item to our project via right-click on the project name in the project explorer.


Select "Visual WebPart" from the list and set a name ("VisualWebPart").


To the visual webpart we add just a label ("Label1") from the toolbox ("VisualWebPartUserControl.ascx").


In my solution I did some small changes to the label, like red color, another font, cleared the text property of the label etc, but this is up to you, how you design the label.

Now we open the code-behind file "VisualWebPartUserControl.ascx.cs" and modify the Page_Load method.

protected void Page_Load(object sender, EventArgs e)
{
  string ErrorMessage = System.Web.HttpUtility.ParseQueryString(System.Web.HttpContext.Current.Request.Url.Query).Get("error");
  this.Label1.Text = ErrorMessage;
}

Explanation:
We use the HttpUtility class to get the parameter "error" from the current url. The paramter "error" we will use later for our custom error message.
The content of the error parameter we put in our label text property.

Now we have our webpart for displaying the error message, but we still have to put in the editform.aspx of our list.
Therefore we open the file "schema.xml" of our list definition and search for the "<Forms>" section in it.
It should similar look like this:


Now we create our custom editform.aspx by creating a new <Form> from type "EditForm". Give a own name ("MyEditForm.aspx") and set default = true:


Code:
      <Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>
          <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="0">
            <![CDATA[
            ]]>
          </AllUsersWebPart>
        </WebParts>
      </Form>

Now we have a custom editform.aspx, but we still have to put our webpart in it. Actually we have the same editform as the standard one. Open the file "VisualWebPart.webpart" from the project explorer.


Copy the complete code except the first line ("<?xml version....>) and paste it in the CDATA area in the schema.xml.
Your form code in your schema.xml should look like this now:


Code:
 <Form Type="EditForm"
            SetupPath="pages\form.aspx"
            WebPartZoneID="Main"
            Url="Forms/MyEditForm.aspx"
            Default="TRUE">
        <WebParts>
          <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="0">
            <![CDATA[
            <webParts>
            <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
              <metaData>
                <type name="SPProject.VisualWebPart.VisualWebPart, $SharePoint.Project.AssemblyFullName$" />
                <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
              </metaData>
              <data>
                <properties>
                  <property name="Title" type="string">VisualWebPart</property>
                  <property name="Description" type="string">My Visual WebPart</property>
                </properties>
              </data>
            </webPart>
          </webParts>
            ]]>
          </AllUsersWebPart>
        </WebParts>
      </Form>

Now we have embedded the webpart in our custom editform.aspx.
We have to tell the event receiver, that it should redirect to our new custom editform.aspx ("MyEditForm.aspx") and we have to add the error parameter to our url.
Navigate back to the event receiver code file ("EventReceiver.cs") and modify the redirect url:

properties.RedirectUrl = @"MyEditForm.aspx?"
                         + "Mode=Upload"
                         + "&CheckInComment="
                         + "&ID=" + properties.ListItem.ID
                         + "&RootFolder=%2Fsites%2FIT%2FLists%2FSPProject-ListInstance1"
                         + "&IsDlg=1"
                         + "&ContentTypeId=" + properties.ListItem.ContentType.Id
                         + "&IsDlg=1"
                         + "&error=Error in Title - Must start with SharePoint";

Changes in code are marked in bold.
We changed the aspx file from "EditForm.aspx" to "MyEditForm.aspx" and added the parameter "error" with a custom error message.


Let's start the solution now. Navigate to the list, add an item and edit the properties afterwards. Click "Save" with an empty title. Now you should get the error message:


If you enter a text beginning with the word "SharePoint" in the title property the popup will disappear.
Hope you enjoyed this lesson. :-)