Conditional Display in ASPX Pages on Sharepoint - asp.net

I wonder what the best practice for this scenario is:
I have a Sharepoint Site (MOSS2007) with an ASPX Page on it. However, I cannot use any inline source and stuff like Event handlers do not work, because Sharepoint does not allow Server Side Script on ASPX Pages per default.
Two solutions:
Change the PageParserPath in web.config as per this site
<PageParserPaths>
<PageParserPath VirtualPath="/pages/test.aspx"
CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
Create all the controls and Wire them up to Events in the .CS File, thus completely eliminating some of the benefits of ASP.net
I wonder, what the best practice would be? Number one looks like it's the correct choice, but changing the web.config is something I want to use sparingly whenever possible.

So in that case I would wrap it up in a feature and deploy it via a solution. This way I think you will avoid the issue you are seeing. This is especially useful if you plan to use this functionality within other sites too.
You can also embed web parts directly in the page, much like you do a WebControl, thereby avoiding any gallery clutter.

What does the ASPX page do? What functionality does it add? How are you adding the page into the site? By the looks of it this is just a "Web Part Page" in a document library.
I would have to do a little research to be 100%, but my understanding is that inline code is ok, providing it's in a page that remains ghosted, and thereby trusted. Can you add your functionality into the site via a feature?
I would avoide option 1, seems like bad advice to me. Allowing server side code in your page is a security risk as it then becomes possible for someone to inject malicious code. Sure you can secure the page, but we are talking remote execution with likely some pretty serious permissions.

Thanks so far. I've successfully tried Andrew Connel's solution:
http://www.andrewconnell.com/blog/articles/UsingCodeBehindFilesInSharePointSites.aspx
Wrapping it into a solution is part of that, but the main problem was how to get the code into that, and it's more leaning towards Option 2 without having to create the controls in code.
What I was missing:
In the .cs File, it is required to manually add the "protected Button Trigger;" stuff, because there is no automatically generated .designer.cs file when using a class library.

Well, it's a page that hosts user controls. It's a custom .aspx Page that will be created on the site, specially because I do not want to create WebParts.
It's essentially an application running within Sharepoint, utilizing Lists and other functions, but all the functionality is only useful within the application, so flooding the web part gallery with countless web parts that only work in one place is something i'd like to avoid.

Related

Managing/removing unnecessary scripts in live Kentico site

We're building a Kentico 8.2 site using ASPX+portal model. Looking at the rendered HTML on my live site I can see a lot of unnecessary Javascript that Kentico has dumped into my page. What's more this is occurring at the top of my page at the top of the form element.
For example, it's rendering the ASP.NET __doPostBack JS function even though I'm not using any controls that require it. Other scripts are being added as WebResource.axd and ScriptResource.axd includes.
At a glance it would seem these scripts constitute the Microsoft AJAX framework used with UpdatePanel etc. My assumption is that they are there to add portal manager functionality when using the page in the Kentico UI. Presumably they are also used with certain built-in web parts.
However, I am only using custom web parts on my live site so all these scripts are doing nothing and are just slowing down my page and causing poor performance testing results.
I've tried hiding the <ajaxToolkit:ToolkitScriptManager /> and <cms:CMSPortalManager /> controls on my master page when rendering the live site, but this causes templates that have a <cms:CMSWebPartZone /> to break.
Does anyone know how to ensure this bloat is removed when not required? Or at the very least cause these scripts to be rendered at the end of the page so they don't interfere with performance too much?
Unfortunately, building sites within Kentico using ASPX and ASPX+Portal Pages will automatically generate additional markup such as __doPostBack, WebResource.axd and ScriptResource.axd.
I wouldn't recommend removing any of the default code in your Masterpage. This will cause things to break (as you've experienced).
However, having this markup in place shouldn't cause a massive issue in page performance. Understandably, this isn't ideal.
What I do to lessen the hit is the following:
Disable the ViewState wherever possible. For example, either at Page Template or Webpart/User control level.
Move the ViewState to the bottom of the page (in Kentico Settings), so the page is less "top heavy".
Ensure you are caching everything you can. For example, site furniture used by your webparts and templates (images/js etc) at IIS level and at Kentico level using their API.
Reading this article from the Kentico documentation provides some more information in greater depth: Optimizing website performance
If you really want "full control" over the HTML rendered, Kentico does allow you to create templates using MVC. But this won't give you the flexibility to modify Page Templates by moving around web parts within the CMS Administration. I presume you have chosen the Portal Page approach for this very reason.
I hope this helps.
In addition to #sbhomra's great answer I have a few questions, suggestions and comments.
How many seconds or milliseconds are you talking about with performance? If you think you'll gain a few milliseconds back, it's not worth your effort to try to rebuild all the functionality. If you're talking a second or two, there about 15 different things you can change within settings and your code to gain it all back. Think about how much code you're going to write, maintain and upgrade just to gain a second or less back?
The WebResource and SciptResource load resources that are compiled into libraries within the website. So if someone created an external library and that library was loading an image that was compiled into it, you'd get that WebResource.axd reference on your site. You'd have to physically remove those libraries from the Kentico instance.
Although I don't recommend it strictly because you lose so much functionality and have so much extra unnecessary code, MVC will give you the control you're looking for.

Umbraco: Handling In Page Javascript in Uswe Controls

I have quite a number of user controls that I need to embed in Umbraco macros. Each user control has quite a bit of in page javascript that needs loaded into the page.
I have been building up the javascript with StringBuilder.Appendline then registering a startup script with code behind but this stinks and I feel there has to be a better way of going about this.
Has anyone any ideas please?
Thanks,
B
If the javascript isn't dynamic, that is that it changes based on the usercontrol you would probably be best to extract it and put it in either one .js file for the site or in a number of them. Doing so allows it to be cached by the browser.
If it is dynamic then I would personally keep it isolated inside the control rather than try to write it out all at once. I don't believe there is any major performance hit from having several script blocks, although I could be wrong.

Building ASP.NET application - Best Practices

We are building an ASP.NET application and would like to follow the best practices. Some of the best practices are:
Server side Code:
Use catch blocks to trap & log low level errors too.
Use Cache objects to populate dropdowns etc. where we won’t expect the changes in the underlying data/database.
In case of error logging framework, provide emailing alerts along with logging the errors.
HTML code:
- Don’t write inline CSS.
- Place the JavaScript code (If needed by the page) at the end of the page unless the page needs it for load time actions.
Now coming to the point, Would you please share these best practice points if you have a comprehensive list of them already?
Some of the best practices that I've learned over time and written up for use at my company...many are mainly applicable to WebForms and not MVC.
Don't write .NET code directly in
your ASPX markup (unless it is for
databinding, i.e. Evals). If you
have a code behind, this puts code
for a page in more than one place and
makes the code less manageable. Put
all .NET code in your code-behind.
SessionPageStatePersister can be used in conjunction with ViewState
to make ViewState useful without
increasing page sizes. Overriding
the Page's PageStatePersister with a
new SessionPageStatePersister will
store all ViewState data in memory,
and will only store an encrypted key
on the client side.
Create a BasePage that your pages can inherit from in order to
reuse common code between pages.
Create a MasterPage for your pages
for visual inheritance. Pages with
vastly different visual styles should
use a different MasterPage.
Create an enum of page parameter key names on each WebForm
that are passed in via the URL, to
setup strongly-typed page parameters.
This prevents the need for hard-coded
page parameter key strings and their
probable mis-typing, as well as
allowing strongly-typed parameter
access from other pages.
Make use of the ASP.NET Cache in order to cache frequently used
information from your database.
Build (or reuse from another project)
a generic caching layer that will
wrap the ASP.NET Cache.
Wrap ViewState objects with Properties on your Pages to avoid
development mistakes in spelling,
etc. when referencing items from the
ViewState collection.
Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.
Wrap the ASP.NET Session with a SessionManager to avoid development
mistakes in spelling, etc. when
referencing items from Session.
Make extensive use of the applicationSettings key/value
configuration values in the
web.config - wrap the
Configuration.ApplicationSettings
with a class that can be used to
easily retrieve configuration
settings without having to remember
the keys from the web.config.
Avoid the easiness of setting display properties on your UI
controls, instead use CSS styles and
classes - this will make your styles
more manageable.
Create UserControls in your application in order to reuse common
UI functionality throughout your
pages. For example, if a drop down
list containing a collection of
categories will be used in many
places in the site - create a
CategoryPicker control that will data
bind itself when the page is loaded.
Use Properties on your UserControls to setup things like
default values, different displays
between pages, etc. Value type
properties can be defined on your
UserControls and then be set in your
ASP.NET markup by using class level
properties on UserControls.
Make use of the ASP.NET validation controls to perform simple
validations, or use the
CustomValidator to perform complex
validations.
Create an Error handling page that can be redirected to when an
unhandled exception occurs within
your website. The redirection can
occur via the Page_Error event in
your Page, the Application_Error
event in your Global.asax, or within
the section within the
web.config.
When working with pages that use a highly dynamic data driven
display, use the 3rd party (free)
DynamicControlsPlaceholder control to
simplify the code needed to save the
state of dynamically added controls
between postbacks.
Create a base page for all your asp.net pages. This page will derive from System.Web.UI.Page and you may put this in YourApp.Web.UI. Let all your asp.net pages dervice from YourApp.Web.UI.Page class. This can reduce lot of pain.
Use Application_OnError handler to gracefully handle any error or exception. You should log the critical exception and send the details of the exception along with date-time and IP of client to the admin email id. Yes ELMAH is sure way to go.
Use ASP.NET Themes. Many developers don't use it. Do use them - they are a great deal.
Use MembershipProvider and RoleProvider. And Never use inbuilt ProfileProvider - They store everything in plain strings. It will drastically slow-down the performance while performing R/W
Use Firebug for client-side debugging. Try to follow YSlow standards for web-applications. Use YSlow extension for FireBug.
Use jQuery for client-scripting.
Never store User Authentication information in session or don't use sessions to judge if user is logged on. Store only minimum necessary information in sessions.
Have a look at PostSharp. Can improve maintainability of your code and make you more productive.
Never ever Deploy asp.net application under debug configuration on production. Find out here what scottgu has to say about this.
User Web Deployment projects. It can transform web.config sections and replace with production server setings. It will merge all compiled code-behind classes into one single assembly which is a great deal.
Use Cookie-less domains to serve static resources like images, scripts, styles etc. Each client request is sent along with whole bunch of cookies, you don't need cookies while serving pictures or scripts. So host those resources on a cookie-less domain.
Minify scripts, stylesheets and HTML response from the server. Removing unnecessary line-breaks and white-spaces can improve the time-to-load and bandwidth optimization.
Forms:
Set Page.Form.DefaultFocus and Page.Form.DefaultButton to improve user experience
Check Page.IsValid in your Save button handler before proceeding.
General:
Understand and implement the techniques found in the article "TRULY Understanding ViewState"
Use Page.IsPostBack in your page events to stop code from running unnecessarily.
Use hyperlinks instead of posting and using Response.Redirect whenever possible.
a. Understand and use the second parameter of Response.Redirect (it "Indicates whether execution of the current page should terminate")
Use the Page Lifecycle properly.
Use the Per-Request cache (HttpContext.Items) instead of Cache where it makes sense.
Web.Config:
Deploy with <compilation debug="false">
Register your controls at the web.config level instead of the page level (i.e. #Register).
Themes:
When using Themes, put your static images in the Theme as well.
a. Don't link to the images directly from your markup, link to them from a skin file or css file in your Theme instead.
ex: <asp:Image SkinID="MyImage" runat="server" ImageUrl="Images/myImage.gif" />
I don't think try/catch blocks are always appropriate for low-level methods. You want to catch (and log/alert, even better!) any errors before they get to the user, of course. But it is often better for a low-level method to just lets its errors get raised up to a higher level. The problem I have seen with low-level error trapping is that it often lets a larger operation continue, but then a result that is not quite correct gets presented to the user or saved to the database, and in the long run it's much more difficult to fix. It's also just a lot of extra clutter in your code to put a try/catch at every level if you're not going to "do anything" with the error until it's raised up to a higher level.
Here are some similar questions that may help you.
.NET best practices?
Best way to learn .NET/OOP best practices?
This should probably be community wiki as well.
I would recommend a couple of books if you are interested in pursuing a journey to become a better, more productive developer. These books are language agnostic and as you can see by the user reviews, very very helpful.
Code Complete 2
Pragmatic Programmer
If you are looking for a .NET specific book, you may appreciate the following book:
Microsoft Application Architecture Guide [available online for free outside of print format]
ASP.NET
If you don't use Session state, don't
forget to turn off it.
Use Server.Transfer instead of Response.Redirect if possible.
Set expiration parameter in IIS.
Use GZip to compress the text files.
Use Server-Side and Client-Side validation together.
Use Url Rewriter or Routing to make friendly url for SEO.
Design
Write each class and its properties
of your CSS file in the same line. (To decrease the file size)
Use CSS Sprites. (To decrease request)

How do I provide easy editing of ASP .NET master pages for designers?

Scenario:
I have a pretty standard master page for all my pages. It includes the usual login forms and other dynamic lists to be extracted on each page. Webdesigners can already modify the central content place holder of each page. But still, the design and layout for the master page is still in my project and any modification to the design must be made in Visual Studio and the project re-compiled and re-deployed.
What is the best way to provide near-full access to designing the master page through a CMS? Some of the problems I can identify is the inclusion of any dynamic lists or specific controls such as a login form.
Thanks.
Unless you want to host your content within a portal I don't know of a perfect answer to this.
If the bits they design just amount to look and feel for the page then this can be controlled by css and you could allow them to create themes using different css files.
This is indeed an interesting question, and there is no perfect solution. I worked for an ecommerce shop with this issue, and frankly, I just asked the designers in many cases to provide me there html and css, then I would grab the html pieces and css and add them to my project. Yes this was tedious....
Then we we built a cms where the designers could copy and paste their html into html editors, and we would store those pieces of html in a database. My web app would grab those from the database at run time. This solve some issues, but not all, since it did not give them complete control of the design of the web page.
The bottom line is you need to standard as to how the designer will submit their work to you. If you have that, and you can count on the html and css, then you can star to think of possibly building a CMS around that. In this days of RAD, I have found it easier to just work with the html and css delivered to me and simply copy and paste the pieces into my master page and other pages as needed.
While this is not a CMS answer, you do have the ability to allow designers to open the master pages in Expression Web. I will not say it is the greatest tool in the world, but I have had designers work up the master page designs in Expression with good results.
There is a pain point, however. If the entire project is opened, the designer will see the code behind files as separate items, not like the treeview view seen in Visual Studio.
I imagine you could have the master page checked out for use with Expression through a CMS, but there is no built in way to do this, nor do I know of a third party tool to do this. Hopefully Expression Web 3 will make things easier.
If you have a CMS, you may be better to give it full control over page content. If there are things the CMS cannot do, you could look to write extensions or plugin modules for the CMS that your designers can then drop onto the page in the CMS's page editor.
If your CMS doesn't support plugin modules, you may be trying to force both the CMS and master pages to do things they were not intended to do.
If the above doesn't work in your situation, here's another thought: place inline frames on your master page that host pages that are edited in the CMS.
Hope that helps.
Would it be possible for you to put placeholders in the Master Page in place of the areas that designers should be allowed to edit? Since Master Pages are only editable in Visual Studio, it may be your only feasible option at this point in time. One problem with this approach is that the content put in the placeholders is unlikely to be valid, since you would probably have tags left open in one placeholder and closed in another.
<html>
<head>
<title></title>
<asp:PlaceHolder ID="headerContent" runat="server"></asp:PlaceHolder>
</head>
<body>
<asp:PlaceHolder ID="beforeContent" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="centralContent" runat="server"></asp:PlaceHolder>
<asp:PlaceHolder ID="afterContent" runat="server"></asp:PlaceHolder>
</body>
</html>
I know it's ugly, but it might give you the control you need (as long as you don't mind the XHTML validator warning you all the time). What you put in the placeholders could be your user controls or literal content or whatever, but you'd have to load it dynamically.
Thoughts?
EDIT: This won't work. The PlaceHolder is going to render <div> tags that would mess things up. Maybe you could extend PlaceHolder and override how it renders its HTML.
Interesting question,
been dabbling in that area myself a while ago.
How knowledgeable are these web designers when not in the realm of not-inside-Photoshop-or-flash?
If using a DIY-CMS, perhaps you can template the most susceptible objects, e. g. making a generic (as in whatever you feel like, not whatever they feel like ;-)) list and a way of entering design, if applicable.
As long as you have a thorough framework set up, that deals with the attributes available to the designers through the CMS, there shouldn't be any need for recompiling... but of course, I can easily see a developer (read : me) stumbling
into the gap of nitty-pitty-perfection....
I'm afraid the easiest, and only manageable, path is to standardize how the designers express their needs&wants to you...it just won't code itself...
Could you provide some examples?
Well, with a Web Application Project pages are not compiled until accessed (link is 2005 but it still applies). This means that the actual .aspx (and .ascx etc) page is deployed in its original state. A designer can update the format of the page on the server and the updates will be compiled the next time someone requests that content.
It would be relatively trivial to allow designers to download the current pages and upload replacements through your website's UI. However, it isn't very secure (and probably should never be done). It would be better to allow designers access to the virtual directory over the web so they can connect to it using a tool such as Expression Web. This way the designer can open the current website, edit pages, and push the results directly into production (scary tho that thought may be).
As I'm getting downvoted for having a correct answer, let me point out something.
Website projects compile codebehind and pages on demand. If you need to update code regularly, its an okay solution.
Web application projects can be configured to be updatable. All codebehind and classes are compiled into an assembly, and all aspx, ascx, etc pages are deployed and compiled on demand. This means that a designer can connect to the website, update the layout and static content, and see the changes on the next request.
This is my preferred method of deployment. I have a few web application projects out there in the wild, with updatable aspx files deployed alongside my dll. The idea being that users of the website can alter the UI without having to submit updates to me so I can recompile it for them.
a .master is just a text file. They can edit it however they like. There's certainly nothing they'd do to it that would require you to recompile the code just to view it. That's the big win with Master Pages in the first place: designers and other non-programmers can edit them manually without breaking anything.
Give them access to the file under source control and let them go nuts.

Web Parts with a markup file?

I'm an ASP.NET web part novice. I've built a few simple ones using only a class that derived from WebPart and overriding the CreateChildControls method, but nothing really very substantial. My question is whether it's possible to have a web part that also takes advantage of a separate html/asp.net markup file that will help provide some structure to the web part's output. In the past I just created server controls and added them to the controls collection, but this seems like a silly way to try to create a non-trivial layout. Can I do this? Do I have to use an ascx user control or can I bypass that step? There are a lot of hello world tutorials on web parts out there, but none seem to go past the CreateChildControls override. Thanks!
Yes, there is. Go here to learn about templated web parts, and go here to see all of the info he has on WebParts. I used this technique back in 2004/2005 and it worked very well.
The links in the above answer are no longer working, but here is an alternative one:
http://www.a2zdotnet.com/View.aspx?Id=95
In VS 2010 we also have visual web parts, that I think do pretty much the same trick but it's wrapped in a project item. I've only seen this in the context of SharePoint so not sure how it works for ASP.NET projects. Here is an example:
http://msdn.microsoft.com/en-us/library/ff597539.aspx

Resources