CJ

The circle of life – ** .Net – Training – MOSS **

  • Past Post

  • Vistor Locations

Developing ASP.Net 2.0 Code Behind pages for SharePoint: Using VSeWSS1.1

Posted by Clayton James on April 13, 2008

This is a guide that will take you through steps in creating a code behind file in Visual Studio for SharePoint development. Full credit to Andrew Connell on his blog entry which demonstrates this process by manually creating files for the deployment process.

The difference with this article is that I wanted to complete the process using Microsoft’s Visual Studio Extensions WSS 1.1 (VSeWSS1.1) tool. Why, because I think this is the tool that should be used when doing any SharePoint development due to its integration with VS.Net, variety of templates, debugging integration, nice wsp viewer, auto generation of features and solutions, and it will continue to evolve over time.

1/ First we need a Content page (.aspx) that will host our ASP.Net controls. Content pages need to conform to SharePoint master pages PlaceHolderContols. So a good place to create one is in SharePoint Designer.

To create a Content page for SharePoint you can open SharePoint Designer and select File –> New –> Create from master page.This will create a blank content page as shown:
clip_image002

This page has no asp Content controls so you can go and add one.
<asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”></asp:Content>

Inside the content control you can add html markup as shown below

clip_image004

3/ Copy the html (ctrl-A) from SharePoint Designer into notepad and save the physical file as CodeBehindDemo.aspx.

4/ Open up Visual Studio and create a new Project and select the Empty SharePoint project and name it accordingly (Note: you need to install VSeWSS1.1 to get these templates).
clip_image006

5/ Once the Project is created right click the project and select Add New Item and select the Module template.
clip_image008

6/ Copy the CodeBehindDemo.aspx to the Module1 folder so it looks like the image below. Then create a new class file called CodeBehindDemo.cs. This will obviously be our code behind file.
clip_image010

7/ Write the following code in the CodeBehindDemo.aspx page. We need to explicitly declare the asp.net controls in the class file as the .aspx and .cs files are not compiled into a single (partial) class.
clip_image012

8/ Back in our .aspx page we need to reference our code behind class with the following page directive.
<%@ Page Language=”C#” masterpagefile=”~masterurl/default.master” title=”|”

inherits=”SharePointCodeBehindPages.CodeBehindDemo, SharePointCodeBehindPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5″ meta:webpartpageexpansion=”full” meta:progid=”SharePoint.WebPartPage.Document” %>

Note: Check your public key token as yours will be different once you sign the assembly.

9/ This is the code inside the Module.xml file.
clip_image014
<?xml version=”1.0″ encoding=”utf-8″?>
<Elements Id=”581c7ebb-03bd-4d7d-ad4a-4e7ff446d2ac” xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<Module Name=”Module1″>
     <File Path=”CodeBehindDemo.aspx” Url=”CodeBehindDemo.aspx” Type=”Ghostable” />
</Module>

<CustomAction Id=”A6DED79F-05A5-4b1a-BD27-10B1A4AAC737″
     Location=”Microsoft.SharePoint.StandardMenu”
     GroupId=”SiteActions”
     Sequence=”99″
     Title=”Code Behind Demo”
     Description=”Code behind example”>
          <UrlAction Url=”~site/CodeBehindDemo.aspx” />
</CustomAction>
</Elements>

10/ This is the code that is inside the Feature.xml file
clip_image016

<?xml version=”1.0″ encoding=”utf-8″?>
<Feature Id=”39fd665e-e168-42fe-ab11-ebea99e0a378″ Title=”Module1″ Scope=”Web” Version=”1.0.0.0″ Hidden=”FALSE” DefaultResourceFile=”core” xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<ElementManifests>
     <ElementManifest Location=”Module1\Module.xml” />
     <ElementFile Location=”Module1\CodeBehindDemo.aspx” />
</ElementManifests>
</Feature>

11/This is the code inside the manifest file
clip_image018

<?xml version=”1.0″ encoding=”utf-8″?>
<Solution SolutionId=”e8fa762e-9f02-4646-9fde-cf17ed7288d6″ xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;
<FeatureManifests>
<FeatureManifest Location=”Module1\feature.xml” />
</FeatureManifests>
<Assemblies>
<Assembly DeploymentTarget=”WebApplication” Location=”SharePointCodeBehindPages.dll”>
<SafeControls>

<SafeControl Namespace=”SharePointCodeBehindPages” Safe=”True” Assembly=”SharePointCodeBehindPages” TypeName=”*” />
</SafeControls>
</Assembly>
</Assemblies>
</Solution>

12/ Before we create and deploy the solution first build the project, make sure you don’t receive any errors and then check the new WSP View in Visual Studio to make everything is fine. You made need to click the Refresh button to display the wsp structure. One of the nice features about the extensions is that it is integrated with Visual Studio so if one of the .xml files has an error then it is displayed in the Error List pane and nothing is displayed in the WSP View, it is just blank. Remember to click the refresh button.
clip_image020

13/ Now all that is needed is to deploy the Solution (.wsp) to the farm. Very simple, right click the project and select Deploy.
clip_image022

14/ Make sure everything is successfully built and deployed
clip_image024

15/ Once built successfully you can view the .wsp file which is located in the projects bin/debug folder
16/ Ok, now lets go and test the page in SharePoint. We have a nice Custom Action we can click that will take us to the page.

clip_image026

Enter you name and click the button.

clip_image028

16/ So there you have it. A code behind page built in Visual Studio all wrapped up in a nice solution (.wsp) for deployment across the farm using the new Visual Studio Extensions for WSS 1.1 tool.

Advertisements

57 Responses to “Developing ASP.Net 2.0 Code Behind pages for SharePoint: Using VSeWSS1.1”

  1. Pankaj Sharma said

    Nice article.
    But facing some issue with this.
    Following is the error message when implemted.
    An error occurred during the processing of . Could not load the assembly ‘DevSolution, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’. Make sure that it is compiled before accessing the page.

    Please help…

  2. CJ said

    Looks like your assembly could not be found.
    Check your .aspx page references the assembly correctly, your PublicKeyToken, the assembly is actually in the GAC and what public key token it is using.
    cheers

  3. CJ – great article.

    I did this in class the other week and while it works well if *and* only if the page is ‘uncustomised’. (as it runs in direct mode)

    As soon as a student modified the page in SPD (customised) it ran in ‘SafeMode’ and SharePoint errored saying ‘A Click Event Handler’ was not allowed for the button.

    Took me a while to figure this out as all the other student’s worked.

    The dangerous thing about all this is – that there is no indication that the page is running in SafeMode vs Direct mode. So one day the page could work – the business add a webpart to the page using SPD and it fails.

  4. […] a couple good posts that really got me started down the path to answering my question. CJ’s – https://claytonj.wordpress.com/2008/04/13/sharepoint-code-behind-demo-using-vsewss11/ Chris Johnson’s – http://blogs.msdn.com/cjohnson/archive/2006/09/05/740498.aspx (option […]

  5. Pankaj Sharma said

    thanks CJ,

    issue got resolved now. problem was with public key token as sugegsted by you.
    Thanks a ton!

    regards
    pankaj sharma

  6. Manfred said

    Hi,

    I made some Pages using the code behind method. I do have one problem though: my pages are only allowed for site administrators. No user is allowed to view the page? does someone know what i’m missing here?

    i’d appreciate your help

    Manfred

  7. george said

    I tried to implement this with a VB page. I followed all your instructions to the letter, with the exception of the aspx page and the code behind page which are written in vb.

    I am getting the error : An error occurred during the processing of . Could not load type ‘MyTestUPS.codebehinddemo’ from assembly ‘MyTestUPS, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5’.

    I double checked the public key token, and the assembly and type names and the spellings.

    Any idea why this doesnt work? I am beginning to think this has to be done in c#?
    Thanks
    G

  8. CJ said

    Hi George
    You can certainly do this in VB.
    Look at Step 8. In bold there is a Note. This states that you will need to change the public key token to the one you generated for your project. You will need to get this public key token from the GAC once your assembly has been deployed.
    cheers

  9. CJ said

    Mick
    Good point but I don’t think this would occur in this example as the click event is wired up in the assembly, not the .aspx page.

    So you should be able to modify the .aspx page in SPD and check it in and all should be good.
    cheers

  10. Steve said

    thx, I have followed this through but dont get the menu item in the site actions and when i try to visit the page i get a an error occured during the processing of . Could not load the assembly ‘…’ Make sure that is is compiled before accessing the page…

    does anyone have any ideas?

  11. Aman said

    Hi,
    Have you tried Developing Webpart, with ‘Usercontrol and code behind’, in Visual Studio Extension/Webpart Templated?

    Please share!

    Regards
    Pankaj

  12. CJ said

    Steve, look at the Note: in step 8.

    Aman, this should be exactly the same process except you create a .ascx instead.

    cheers
    CJ

  13. peter said

    If you can post or send me the demo code you used here CodeBehindDemo.aspx and CodeBehindDemo.cs that will be great help!

  14. Dave said

    Couple of questions:

    After the code behind is deployed to SharePoint, is it possible to edit the code behind files from SharePoint Designer?

    Can the code behind be used with SharePoint controls such as DataView?

  15. CJ said

    Dave, No it is not possible to edit code behind files using SPD, only Visual Studio.
    Yes, can use a Data View web part in a web page that you created. Just need to put the appropriate references in the right places.
    Cheers
    CJ

  16. Neil said

    Hi CJ

    I’m using VS2008. I was able to follow your instructions up until step 9. In VS2008 there is none of the other xml files?
    my solution tree looks like this:

    Properties
    Assembly.cs
    NewPage.snk
    References
    Module1
    Module1.xml
    NewPage.aspx
    NewPage.cs
    Sample.txt

    When i try building it at this point I get the error: No SharePoint Site exists at the specified URL. I checked my solution and corrected it where ever the url needed to be, no luck.

    Any Ideas? Maybe you can create a similar post for the VS2008 users?

    Thanks,
    Neil

  17. […] https://claytonj.wordpress.com/2008/04/13/sharepoint-code-behind-demo-using-vsewss11/ […]

  18. Neil said

    Hi CJ

    After much trail and error I got the WSP to work in VS2008, previous mentioned problem was due to my own stupidity. It builds fine now, but when I try to deploy the solution, I get an error that says “No sharepoint site exists at the specified URL” have you got any suggestions for me?

    Thanks,
    Neil

  19. CJ said

    Hi Neil
    In VS2008 you need to set the sharepoint site in the VS projects properties. This is the site that the Feature will be activated against.
    HTH
    CJ

  20. Richard Holmes said

    I got stuck at step 8. You need to add in ”~masterurl/default.master” to the page directive but this prevents you building the solution because it doesn’t recognise that master page? So you can’t deploy and therefore the feature.xml and manifest.xml files are not created and no pkg folder is created – they only appear after you deploy in Visual Studio? Then you can’t get to step 10.

  21. CJ said

    Richard…hmmm…I don’t receive this error and everything builds fine.
    CJ

  22. Neil said

    Hi CJ

    Everything builds fine and it deploys(once, there after it mouns, already exists). When I try running the page in SP I get this error:

    An error occurred during the processing of . Could not load the assembly ‘NewPost, Version=12.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5’. Make sure that it is compiled before accessing the page.

    The 5part name is the same in SPD and VS, including the public key, checked and double checked it. I copied the dll to the GAC aswell.

  23. CJ said

    Neil
    Look at step 8 again. It states that your Public Key Token will different to this example. Go into your GAC and retrieve your PK and then copy this to your .aspx page where it references the assembly.
    CJ

  24. Neil said

    Sorry about that, VS put my public key in the properties folder for some reason, moved it and got the new key. The new error, same as last, different public key:

    An error occurred during the processing of . Could not load the assembly ‘NewPost, Version=12.0.0.0, Culture=neutral, PublicKeyToken=679b998e861cf769. Make sure that it is compiled before accessing the page.

    Here is the code of my page in SPD and VS:

    page name: NewPost.aspx
    namespace: NewPost
    class: NewPost
    public key (in GAC): 679b998e861cf769

    See previous post for build and deploy events.
    I access my page differently though, i simply type the url in the address bar, because the page will be the target of a response.redirect() command.

  25. Neil said

    Here is the code of my page in SPD and VS:

    Page Language=”C#” masterpagefile=”~masterurl/custom.master” title=”New Post” inherits=”NewPost.NewPost, NewPost, Version=12.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5″ meta:webpartpageexpansion=”full” meta:progid=”SharePoint.WebPartPage.Document”

  26. Mark Kamoski said

    It is a nice article. Great job. This is good if and only if one has full control of the server. To deploy a Feature, to touch the 12-Hive, to touch the Bin– all that requires one to full control of the server. That is fine when you have such access. However, in a shared hosting environment or the like, one will not be able to touch any of those resources– so, one needs to do something else. Just my 2 cents. HTH. Thank you. — Mark Kamoski

  27. CJ said

    Hi Mark,
    Glad you liked the article.
    That is the benefit of creating a SharePoint solution file (.wsp). You use stsadm to deploy the solution to Central Administration (CA) and CA manages the rest. i.e the deployment of the feature, adding assembly to bin or gac, etc…

    CA completes the deployment to the Web Front End server via a (I think) the OWSTimer.exe service which runs under CAs application pool account. So this is the account that needs the permissions you are outlining.

    If you don’t have access to the production server then all you need to do is give the person that does the .wsp file and they can deploy it to CA.
    SharePoint Solutions also manage the process of deploying the files across multiple Web Front End servers in a load balanced environment.

    Hope this clears up any confusion.
    CJ

  28. CJ said

    Neil
    Your inherits property has Version=12.0.0.0. I am guessing this should be 1.0.0.0 You need to make sure everything is correct.
    The error you are receiving is purley that your .aspx page cannot find the assembly. Everything needs to be exact.
    Cheers
    CJ

  29. Richard Holmes said

    OK I’m just following this along. In step 7 the screenshot has the pkg folder with feature.xml and manifest.xml files are in there. I thought those were not created until you actually deploy the solution? I’m using VS 2005 and VSeWSS 1.1. When I get to step 7, I have no pkg folder or feature.xml or manifest.xml files, not showing in VS (I selected Show All Files) nor in the folder structure in my project files.

  30. Bala said

    Hi..

    As your suggestion i have created the code behind file..
    But the events are not functioned ..

    I dont know why.. If any idea plz suggest me.

  31. SRaj said

    Hi Neil,

    I have completed upto step 16. Right now i can see CodeBehind Demo module in SiteActions. But button click event not fired…..
    Can you help me in this issue????

  32. Sabin said

    Hi Cj,
    I have been doing this to create code behind pages in sharePoint for a while and it has worked for me using C#. Now I need to do it in VB.net and it sucks. The VB code behind files do not recognize that there are controls on the page. Do you know why this would happen? I am explicitly defining my controls so that the code behind is aware of the controls like so
    Protected errorLabel As Label
    Protected resultsLabel As Label

    Any help would be appreciated.

    Thanks,
    Sabin

  33. Markus Bantel said

    Hi Sabin, i have the same problem. If i add a control it’s not added in then classes and double click an element adds inline code instead of add code to the class.

  34. Krupali said

    Hi,

    I used this way. but I got error: An error occurred during the processing of . Value cannot be null.
    Parameter name: key

    Can u pls help me???

  35. Prakash said

    Hi Mr.CJ i have done the steps what you have suggested but when i work my module.xml file does not change it remains same.

    I have not see any tag..

    Please let me know..
    prakash

  36. Giridharan said

    Hi CJ,

    Good article.

    Thanks
    Giri

  37. Erdem said

    Hi,
    I read the article, I’am using a similar method, and I think easier…
    I’m just creating a class library and inherit my class from page class as you do. And after signing I built the solution so in the debug>bin directory my dll is created. I drag the dll file to GAC.
    Next step is adding the dll to safecontrols tag in the web.config file of the sharepoint application.
    The last step is same with yours. Change inherits property of my sharepoint page.
    I can give details, if I’am not clear enough..
    We can discuss if there is something wrong with my method, but it’s working.

  38. Benson said

    How does the Soultion know to use the ‘pkg’ folder? Is this a standard?

  39. Benson said

    How can I test my code against the Sharepoint before deploying the code? Is there a standard for this?

  40. praveen said

    Thanks for the good article.

    I have tried this but end up with the fallowing error,

    Compilation Error
    Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

    Compiler Error Message: CS0122: ‘CodeBehindApplication.CodeBehind’ is inaccessible due to its protection level

    Source Error:

    Line 109:
    Line 110: [System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
    Line 111: public class CODEBEHIND_ASPX__2021982599 : global::CodeBehindApplication.CodeBehind, System.Web.IHttpHandler {
    Line 112:
    Line 113: private static bool @__initialized;

    Source File: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\154a7ddb\4c8e1227\App_Web_codebehind.aspx_-2021982599.alsyhm9i.0.cs Line: 111

    Can you help on this.

    Regards
    Praveen

  41. praveen said

    Ya, got it,

    forgot to specify class as public.

  42. Jane said

    Thank you CJ. It helped me lot and it worked fine in my project yesterday. However, today, when I opened the site, I got the error:

    The resource cannot be found.
    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

    I tried to close all the opened .net applications, close SharePoint designer, rebuild, redeploy, delete and reload the aspx file into SP designer, restart website from IIS, even restart the server, etc. the same stupid error. And all other pages work fine.

    May you help me on this issue.

  43. nagaraju said

    Hi Cj,

    Nice Article,

    iam facing some problem.can u advice me.

    ASP.NET runtime error: Only Content controls are allowed directly in a content page that contains Content controls.

    raju.

  44. Tareq said

    Hi,

    I read Andrews post on this and your as well. I am just learning sharepoint so have a question. I want to use a GridView Control that will connect to a database to extract some data’s. So what is the right way to handle the database connection string? Can it be passed in the dll or can it call SharePoint configured connection if so how?

    Thanks a lot.

  45. Mina Samy said

    Hi CJ
    I was wondering if the feature.xml and the manifest file are created automatically or I have to implement them
    thanks

  46. Ashok said

    Hi There, I will try this out asap, but the screen-shot images are very small, when you click on the, the image displayed is exactly the same size as the original. Have you got larger images at all?

    Thanks – I hope you can make this nice article more readable.

    Regards, Ashok J (UK)

  47. Ashok said

    Hi CJ,

    I initially had the same Public Key Token problem, which I sorted. But then after successfully building and deploying, I got this error:
    ======================================================================================
    Object reference not set to an instance of an object.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

    Stack Trace:

    [NullReferenceException: Object reference not set to an instance of an object.]
    SharePointCodeBehindPages.CodeBehindDemo.OnInit(EventArgs e) +62
    System.Web.UI.Control.InitRecursive(Control namingContainer) +321
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +834
    ===============================================================================

    Any ideas? I am using VS2008, would that be a problem?

    Thanks, Ash

  48. Ken said

    Hi CJ,

    I did what you showed and it works perfectly. I want to ask if it is possible from the code behind to access List library or even create or update List item. I tried and have exception throw out about SharePoint Security Permission. I looked around and some options are to modify config file or install in GAC or create custom policy. I tried install in GAC but it doesn’t work. I could not modify config file. The custom policy also look like require to make change of config file. Do you have other suggestion on this?

    Thanks
    Ken

  49. When i deploy the project i got the following error:
    Error 1 Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

    please help to resolve this issue…

  50. Hi,

    Error occurs when i open the deployed site

    “An error occurred during the processing of . Could not load the assembly ‘Sharepoint2007, Version=12.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5’. Make sure that it is compiled before accessing the page”

    Thanks,
    Manikandan Muthuraj

  51. zeeshan said

    hi

    nice article but the same thing stated more elaborately at this link

    http://blogs.msdn.com/cjohnson/archive/2008/06/07/updated-building-a-simple-asp-net-page-based-sharepoint-application-in-visual-studio-with-the-visual-studio-extensions-for-wss-1-2-with-visual-studio-2008.aspx

  52. […] https://claytonj.wordpress.com/2008/04/13/sharepoint-code-behind-demo-using-vsewss11/ […]

  53. Andrews Pelt said

    Hi,this is really a great jeans,I like the classic jeans.

  54. aatokirsa said

    helicopter tours new york

  55. bug mic said

    public key token priovate key token . regrserister depoly, all are junk from micorsoft. stupid micorsfot. nothing can be perfect

  56. Arlie said

    This design is incredible! You obviously know how to keep a
    reader amused. Between your wit and your videos, I was almost moved to start my own blog
    (well, almost…HaHa!) Great job. I really loved what you had to say,
    and more than that, how you presented it.
    Too cool!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: