Thursday, 30 May 2013

Custom Error page in Event Receivers for Sharepoint 2010

Following steps for Custom Error Page.

1. Update the Event Receiver: ItemAdding Section's Code would be:

public override void ItemAdding(SPItemEventProperties properties)
       {
          base.ItemAdding(properties);

           if (!properties.AfterUrl.EndsWith("pdf"))
           {
               properties.Status=SPEventReceiverStatus.CancelWithRedirectUrl;
               properties.RedirectUrl = "/_Layouts/ERTest/ApplicationPage1.aspx";
           }
       }
2. Add a Application Page to the Project, optionally a Icon to represent Error.


3. Update the Error page: Under the PlaceHolderMain Place some content to give descriptive Error message:



See the Result in action: SharePoint 2010 event receiver custom error page.



Wednesday, 29 May 2013

Restict File Type in Sharepoint Document Library Using Event Receiver.

Creating Event receivers in SharePoint 2010 is very easy With Visual Studio 2010. Here are the steps:

1. Create a New Visual Studio Project, Choose SharePoint >> 2010 >> Event Receiver >> Give it a Name. Say "EventReceiver1"



2. Make it as a Farm solution, choose the event receiver properties as in the below screen.






3. On clicking "Finish" button, Visual Studio will create the project structure as and Now, in the Elements.xml file, change the ListTemplateID="101" (Which means all document Libraries) to ListURL="RelativePathOfDocLibrary" say: "CV".

Change the <Receivers attribute



So, The complete code would be:using System;

using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace ERTest.EventReceiver1
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
           if (!properties.AfterUrl.EndsWith("pdf"))
           {
               properties.ErrorMessage = "You are allowed to upload only jpg Images!";
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.Cancel = true;

              

           }

       }


    }
}

See the the result in action!SharePoint document library restricts file type other than PDF.





Friday, 24 May 2013

SharePoint Designer - Send the URL of the current item with a workflow.


So I opened SharePoint Designer and start creating the workflow associated to the list.
image
image
As there is some Field from source related to current item URL I start using it
  • Encoded Absolute URL – this one should be the one to use
  • Server Relative URL
  • URL Path
image
Unfortunately, none of these options were providing the correct link. Indeed, these options are providing an incorrect path:
Encoded Absolute URL
http://webappurl/Lists/Demo/1_.000
Server Relative URL
/Lists/Demo/1_.000
URL Path
/Lists/Demo/1_.000

As you can see, the item URL is composed by an ID while it should be http://webappurl/Lists/Demo/dispform.aspx?id=[%Current Item:ID%]
So, to obtain the correct item URL, you must use the following Lookup
  • Data source: Workflow Context
  • Field from source: Current Item URL
image

If you want your workflow start automatically when item added in a list.

Note: When using a Document Library IT Give a directly on File(Document) Link.





Tuesday, 7 May 2013

Upload A document to a Document Library through programmatically...


Note: I used Visual Webpart which template in visual studio for sharepoint.

protected void btnUpload_Click(object sender, EventArgs e)
        {
            BindDataInSPList();
        }
        private void BindDataInSPList()
        {
            try
            {
                SPSite oSite = SPContext.Current.Site;
                SPWeb oWeb = oSite.OpenWeb();

                oWeb.AllowUnsafeUpdates = true;
                SPDocumentLibrary mylist = oWeb.Lists["CV"] as SPDocumentLibrary;

                string fileName = System.IO.Path.GetFileName(FileUpLoadDoc.PostedFile.FileName);
                //Get file extension ( *.doc OR *.docx )
                string fileExtension = FileUpLoadDoc.FileName.Substring(FileUpLoadDoc.FileName.IndexOf("."));
                byte[] fileBytes = FileUpLoadDoc.FileBytes;
                string destUrl = mylist.RootFolder.Url + "/" + fileName;
                SPFile destFile = mylist.RootFolder.Files.Add(destUrl, fileBytes, true);
                destFile.Update();
                oWeb.AllowUnsafeUpdates = true;
                //update metadata
                destFile.Item["Name"] = txtSTDFNNAme.Text;
                //destFile.Item["Address"] = txtAddress.Text;

                destFile.Item.Update();
            }
            catch (Exception ex)
            { ; }
        }

Sequential Workflow


In this example we are trying to create a Workflow which on activation updates the null Address column of the Manager list. 

Step 1: Create Sequential Workflow Project
For the time being, we can start with a Sequential Workflow. Start Visual Studio and create a new project from the template SharePoint > Sequential Workflow.


In the next screen select the option Site Workflow as shown below:


In the next screen, leave the default option saying the user manually starts the Workflow. Click the Finish button to create the project.

Note: If user select a List Workflow rather than site workflow it active another option like automatically created a workflow when item created.

You will get the following screen once the project is created.

Step 2: Create Activity
We need to create an Activity to perform our job.

What is an Activity?

A Workflow consists of a series of Activities. We can add Activities using the Toolbox. There are different types of Activities like Code Activity, SendEmail, etc. For our example we are using the more functional Code Activity.

Drag and drop a Code Activity from the toolbox. You can locate this from the v3.0 group inside Toolbox.


Step 3: Add code for the Activity
Now we need to add code for this Activity. Double click on the codeActivity1 item shown above. Place the following code in the appearing code view.
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
    using (SPWeb web = SPContext.Current.Web)
    {
        SPList list = web.Lists["Manager"];
        foreach (SPListItem item in list.Items)
        {
            if (item["Address"] == null)
            {
                item["Address"] = "PLEASE SET THE ADDRESS!";

                item.Update();
            }
        }
    }
}
OR 
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
 try
            {
            SPSite site = new SPSite(@"http://sqlsharep:410/");
            SPWeb web = site.AllWebs["ep"];
            SPList list = web.Lists["Manager"];

                SPSite oSite = new SPSite("http://sqlsharep:410/sites/ep");
                SPWeb oWeb = oSite.OpenWeb();

                oWeb.AllowUnsafeUpdates = true;

                SPList list = oWeb.Lists["Manager"];
                foreach (SPListItem item in list.Items)
                {
                    if (item["Address"] == null)
                    {

                        item["Address"] = "Please set the Address!";
                        item.Update();
                    }
                }

            }
            catch (Exception ex) { }
        
   }
OR
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
 try
            {
            SPSite site = new SPSite(@"http://sqlsharep:410/");
            SPWeb web = site.AllWebs["ep"];
            oWeb.AllowUnsafeUpdates = true;

                SPList list = oWeb.Lists["Manager"];
                foreach (SPListItem item in list.Items)
                {
                    if (item["Address"] == null)
                    {

                        item["Address"] = "Please set the Address!";
                        item.Update();
                    }
                }

            }
            catch (Exception ex) { }
        
   }

Step 4: Build and Deploy the Solution
Now we are ready to build and deploy the solution. Right click on the solution and use the Build and Deploy command.  

Step 5: Execute the Workflow inside SharePoint
Now we are ready to test the Workflow inside SharePoint. As the Workflow was created as a Site Workflow it will be accessible for all the Lists and Libraries. You can click the Lists link inside the site.


Now click on the Site Workflows link. You will get the following screen.


Before executing the Workflow, you need to create a Manager item with Address not assigned.
Click on the highlighted button and your workflow gets executed. Wait for a while and you can see the invalid manager record is updated with the message.


This concludes our article on Workflow using Visual Studio.

Note

For debugging the Workflow, you can set a breakpoint and use the Debug command of Visual Studio. When the Workflow is executed, the breakpoint will get hit.

Wednesday, 1 May 2013

Error occurred in deployment step ‘Activate Features’: Attempted to perform an unauthorized operation.


Anyway, I had this error while trying to deploy the visual web part for Sharepoint 2010 within VS 2010. There are at least 2 reasons why you’re getting this error:
  1. Bear in mind that you can only deploy the solution of the visual web part at a farm level. You will get this error while trying to deploy the solution at a site level. This is related to the correct site url you enter while creating the project. It is recommended that you always click on “Validate”.
  2. It is so obvious from the message that your windows login does not have the right “site collection” permission.
What I’m going to talk about and step through is point #2 (not having the right permission). Reason being is whichever the windows login that you’re using to deploy the solution, Sharepoint will use it to check if you’re authorised to deploy any solutions or not (not just deploying actually).

Step 1

Fire up the Sharepoint 2010 Central Administration.

Step 2

Go to Application Management –> Change site collection administrations

Step 3

Select the correct site collection and type your windows account(Which account you are login in the system i.e: 'Admininstrator') as the secondary site collection administrator
Now try to deploy the solution again and it should work!