WebForms

From eBabel wiki
Jump to: navigation, search

Web Forms

Create a library of server controls

  1. In the solution, add a new project of type ASP.NET Server Control, for example AdventureServerControls
  2. In the main ASP.Net web app project where the controls will be used, add a Reference to the ServerControls project AdventureServerControls.
  3. In the main ASP.Net web.config, add the following bold xml in the relevant location:
<configuration>
   <system.web>
     <pages>
       <controls>
         <add tagPrefix="adventure" assembly="AdventureServerControls" namespace="AdventureServerControls" />

The tag prefix can be called anything. It will be used to include any of the controls from the AdventureServerControls library of server controls.

The controls can now be used on any web form with a tag starting with <adventure:controllerName. For example:

<adventure:HolidayDestinations runat="server" />

Dino Esposito article on creating your own web form controls.

Avoid impossibly long client side IDs in HTML

To render much shorter ID, at the risk of having the same ID generated by different controls, it's possible to set pages in web.config like so:

<configuration>
   <system.web>
     <pages clientIDMode="Static" />

Minimize the reliance on ViewState

To prevent the ViewState becoming too large, it's best to disable it everywhere and then only enable it when it's truly required.

Set ViewState enabled or disabled for a whole web app

In web.config:

<configuration>
  <system.web>
    <pages enableViewState="false" />

Other settings that affect the size of ViewState

  • enableEventValidation
  • enableSessionState
  • enableViewStateMac
<configuration>
  <system.web>
    <pages enableViewState="false" enableEventValidation="false" enableSessionState="false" enableViewStateMac="false" />

Set ViewState enabled or disabled per page or control

Several web form elements can set ViewState to be disabled or enabled. ViewState won't completely disappear but it won't be as big.

In Master page:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="AdventureHolidays.SiteMaster" EnableViewState="false" ViewStateMode="Disabled" %>

In an aspx page:

<%@ Page Title="Home" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
   CodeBehind="Default.aspx.cs" Inherits="AdventureHolidays._Default"  EnableViewState="false" ViewStateMode="Disabled" %>

In a form:

<form runat="server" ViewStateMode="Disabled" EnableViewState="False">

In a server control:

<adventure:HolidayDestinations runat="server" ViewStateMode="Disabled" EnableViewState="False" />

A small view state can be as little as just one short string of encrypted data:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/KEPDwUKMTE5MTYyMjM5OFMkybOdbIoHkS02QD4CLGdyN/QRCV1CP/vnGDEKLLndM35=" />


SQL Server

Backup to a folder other than the default SQL Server folder

If you get a permission error when trying to backup a database in SQL Server management studio, change the target folder permission to allow NETWORK SERVICE to have full access.

Connection string in web.config

One possible way to have a connection string to a local SQL Express AdventureWorks database:

<configuration>
  <connectionStrings >
     <add name="ApplicationServices" connectionString="Server=.\SQLEXPRESS;Database=AdventureWorks1;User ID=yourusername;Password=yourpassword;Trusted_Connection=False;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

More connection strings

What does Trusted_Connection mean in a web.config connection string?

Trusted_Connection, when true, means that Windows credentials of the current user are used to connect to the database, instead of the connection string own User ID.

If any of these two settings is present (Trusted_Connection=true or Integrated Security=true/SSPI), then the Windows credentials of the current user are used to authenticate against SQL Server and any user ID settings will be ignored and not used.

Source: http://stackoverflow.com/questions/1642483/when-using-trusted-connection-true-and-sql-server-authentication-will-this-effe

Setup Membership default tables in a database

Run:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regsql.exe

Follow the wizard, use an account that can create tables in the target database.

For example:

Server .\SQLEXPRESS
SQL Server authentication
Username yourusername
Password yourpassword

http://www.asp.net/web-forms/tutorials/security/membership/creating-the-membership-schema-in-sql-server-cs

Configure default Membership in web.config

<configuration>
 <connectionStrings >
   <add name="ApplicationServices" connectionString="Server=.\SQLEXPRESS;Database=AdventureWorks1;User ID=username;Password=password;Trusted_Connection=False;" providerName="System.Data.SqlClient"/>
 </connectionStrings>
  
 <system.web>
   <membership>
     <providers>
       <clear/>
       <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
            enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
            maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
            applicationName="/" />
     </providers>
   </membership>

   <profile>
     <providers>
       <clear/>
       <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
     </providers>
   </profile>

   <roleManager enabled="false">
     <providers>
       <clear/>
       <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
       <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
     </providers>
   </roleManager>


Deployment

Remove pdb files from published web apps

  1. Check the Properties of the ASP.Net web app project that is to be published.
  2. Switch to the tab Package/Publish Web
  3. In th Configuration dropdown, select Release
  4. Check the box "Exclude generated debug symbols"

When the web app is published under Release mode, it should now not include the .pdb files.


Globalization

Populate lang attribute of html tag in master page

In Site.Master, include the following namespace in the view (not in code-behind)

<%@ Import Namespace="System.Threading" %>

And in the html tag, place the lang attribute:

<html lang="<%= Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName %>">

The content and ui culture should be set in the current thread at the web form aspx page level, not at the master page, in code-behind this time.

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var culture = new CultureInfo("nl");
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
    }
}

Example above is for the code-behind of Default.aspx


WCF web services

How to output Json by default in a WCF REST service

The web.config needs to be modified.

Location:

<configuration>
 <system.serviceModel>
   <standardEndpoints>
     <webHttpEndpoint>

XML settings to update: set the "automaticFormatSelectionEnabled" to false and the "defaultOutgoingResponseFormat" to "Json"

     <webHttpEndpoint>
       <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json" />
     </webHttpEndpoint>


Links