ASP.net Website DataBind to SQL server - asp.net

I've been working on this site on VS Studio for Web 2012. Most of it is HTML and ASP, but I've included a DayPilot calendar that I downloaded from SourceForge. I, apparently, must DataBind the calendar to my SQL server, so that users can login and set aside times for themselves on the calendar. I've used just about every recommended code I can find on the Net, but none seem to work on the Calendar page.
Here is the aspx page and the aspx.vb page codes:
(aspx page)
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="calendarpg.aspx.vb" Inherits="_Default" %>
<%# Register Assembly="DayPilot" Namespace="DayPilot.Web.Ui" TagPrefix="DayPilot" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="<%=ResolveUrl("~/Scripts/DayPilot/calendar.js")%>">
</script>
<style type="text/css">
.auto-style8 {
font-size: large;
}
</style>
<link type="text/css" rel="stylesheet" href="<%=ResolveUrl("~/Themes/themes.css")%>" />
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
dbo.BasicData
<DayPilot:DayPilotNavigator ID="DayPilotNavigator1" runat="server" />
<DayPilot:DayPilotCalendar ID="DayPilotCalendar1" runat="server" Days="7" EventMoveJavaScript="alert('eventMove(e.start(), newEnd')" BackColor="#CCFFFF" DataStartField="null"></DayPilot:DayPilotCalendar>
<DayPilot:DayPilotScheduler ID="DayPilotScheduler1" runat="server">
</DayPilot:DayPilotScheduler>
<br />
<h1><strong>Scheduling</strong></h1>
<span class="auto-style8">Requests are made via the Calendar for each of the respective Sandboxes.
A minimum of 24-hour notice is rquired when making a request to allow
time for preparation of a Sandbox,
<br />
time zone differences, and to resolve any
scheduling conflicts.
<br />
<br />
The process for booking is similar to booking a conference room.
<br />
<br />
Choose a day and time that is open, for the Sandbox you're interested in using,
then choose the open hours that work best for your schedule. </span>
</asp:Content>
(aspx.vb page)
Partial Class _Default
Inherits System.Web.UI.Page
'Declaration
Public Event DataBinding As EventHandler
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DayPilotCalendar1.DataSource = getData()
DataBind()
End Sub
Public Function getData() As Data.DataTable
Dim dt As Data.DataTable
dt = New Data.DataTable
dt.Columns.Add("start", GetType(DateTime))
dt.Columns.Add("end", GetType(DateTime))
dt.Columns.Add("name", GetType(String))
dt.Columns.Add("id", GetType(String))
Dim dr As Data.DataRow = dt.NewRow()
dr("id") = 0
dr("start") = Convert.ToDateTime("15:50")
dr("end") = Convert.ToDateTime("15:55")
dr("name") = "Event 1"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr("id") = 1
dr("start") = Convert.ToDateTime("16:00")
dr("end") = Convert.ToDateTime("17:00")
dr("name") = "Event 2"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr("id") = 2
dr("start") = Convert.ToDateTime("16:15")
dr("end") = Convert.ToDateTime("18:45")
dr("name") = "Event 3"
dt.Rows.Add(dr)
Return dt
End Function
End Class
(this is my Web.Config page as it stands now)
<using System.Web.Configuration; />
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ConnStringDb1" connectionString="DataSource=Win08-SDBX1\SQLExpress;Initial Catalog=aspnetdb;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5">
<assemblies>
<add assembly="Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.VisualC, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.VisualStudio.Tools.Applications.Adapter.v9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.VisualStudio.Tools.Applications.DesignTime.v9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.VisualStudio.Tools.Applications.Hosting.v9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.VisualStudio.Tools.Applications.ProgrammingModel, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.VisualStudio.Tools.Applications.Runtime.v9.0, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
<pages>
<controls>
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
</controls>
</pages>
</system.web>
</configuration>
If any of that makes sense, or you see where I'm going wrong, please share or correct my coding. Thank you!

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DayPilotCalendar1.DataSource = getData()
DataBind()
End Sub
This need to be
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
DayPilotCalendar1.DataSource = getData()
DayPilotCalendar1.DataBind()
End Sub

Can we see the Databind function that is called by PageLoad?
I had an issue similar to this when I was working on a C# asp.net application. I created a method to bind the data from a dataset that contained a table of cards. When loading the table "NullReferenceException was unhandled by user code" was thrown and upon looking at the table I could see that a null value was being held.
When you are debugging and the exception is thrown, what is being shown as the held value of the data table?
If it is null then your table is not referring to an object.

Related

ASP.NET Webforms Module, context user is null

When a video request is handled by the HTTP Module (code below) such as /website/uploads/Video/M2U00001_2.mp4 the _context.User is null.
When I run this in VS2010 on my local machine using the Visual Studio Development server _context.User is set. After I deploy to IIS 7 (.net 4.0) _context.User is Null.
'_context.User' is not Null when the http module processes an aspx page but it is Null when processing javascript, images, videos or CSS.
Can anyone explain why _context.User is null and possible solutions that will ensure _context.User is not null.
public Class VideoSecurityModule
Implements IHttpModule
Private WithEvents _context As HttpApplication
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Dim myUserManager As UserManager
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
_context = context
myUserManager = New UserManager
End Sub
Public Sub OnAuthorizeRequest(ByVal source As Object, ByVal e As EventArgs) Handles _context.PostAuthenticateRequest
Const networkAuthenticationRequiredStatusCode As Integer = 511
Try
If IsVideoUrl() Then
If _context.User Is Nothing Then
LogManager.WriteMessage("_context.User is nothing:", "")
End If
Dim userId As Integer = myUserManager.GetUserIdByUserName(_context.User.Identity.Name)
If (UserRequiresAuthorization(userId)) Then
If Not UserIsAssignedToCourseContainingVideo(userId) Then
LogAccessDeniedMessage()
_context.Response.StatusCode = networkAuthenticationRequiredStatusCode
_context.Response.ClearContent()
_context.Response.Write("UnAuthorized User")
_context.Response.End()
End If
End If
End If
Catch ex As Exception
LogManager.WriteException(ex, "")
End Try
End Sub
End Class
To ensure that _context.User is set add the runAllManagedModulesForAllRequests="true" to the modules section of the web.config like below.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="ScriptModule" />
<remove name="RadUploadModule" />
<remove name="RadCompression" />
<remove name="VideoSecurityModule" />
<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode,runtimeVersionv2.0" />
<add name="VideoSecurityModule" type="LMS.VideoSecurityModule"/>
</modules>

WebMethod not called (triggered) by PageMethod in Visual Studio 2013

I have the following problem:
The call from a WebMethod is not being done on a project created in Visual Studio 2013 (ASP.NET WebForms Application). If I create a project, for example, in Visual Studio 2008 and migrate to VS 2013 works correctly. The problem only occurs when I create a new project in Visual Studio 2013. There is no error message in the console. The WebMethod is just not being called. Nothing happens. I searched a lot but found nothing about it.
ASPX code:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="TestePageMethods._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
<script type="text/javascript">
function testeClick() {
PageMethods.SayHello("Name");
}
</script>
<input type="button" value="Say Hello" onclick="testeClick();" />
</form>
</body>
</html>
ASPX.VB code:
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
<System.Web.Services.WebMethod(True)> _
Public Shared Function SayHello(ByVal name As String) As String
Return "Hello " & name
End Function
End Class
Has anyone tried this or know of a solution? I have no idea what to do ...
EDIT:
Guys, I discovered one more information now:
Working only in VS2013:
-New project.
-Web - ASP.NET Web Application.
-Select the template "Empty".
-Insert a page "Default.aspx", the WebMethod works normally ...
Now, if you create a new project and select the template "WebForms", does not work ...
Can be cross-referenced? or some different setting?
I found the solution to my problem: What prevented the WebMethod was called was the reference to "System.Web.Optimization". Not sure how he does it, but as I will not use it at the time, decided to remove:
"System.Web.Optimization" and "Microsoft.AspNet.Web.Optimization.WebForms"
It is also necessary to remove the web.config as follows:
<namespaces>
<add namespace="System.Web.Optimization" />
</namespaces>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms"
namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
<dependentAssembly>
<assemblyIdentity name="WebGrease" culture="neutral"
publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
All ok now! Thanks to everyone who helped me with the problem! :)
Add this section in web.config after httpModules.
add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

sending email from contact page in asp.net

Iam developing in visual studio 2010 I would like to send email from the contact page I have my code listed below it executes without errors but the email is not sending
Partial Class _Default
Inherits System.Web.UI.Page
''' <summary>
''' Actions when the Send button is clicked.
''' </summary>
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSend.Click
'Create instance of main mail message class.
Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
'Configure mail mesage
'Set the From address with user input
' mailMessage.From = New System.Net.Mail.MailAddress(txtFromAddress.Text.Trim())
'Get From address in web.config
mailMessage.From = New System.Net.Mail.MailAddress(System.Configuration.ConfigurationManager.AppSettings("fromEmailAddress"))
'Another option is the "from" attirbute in the <smtp> element in the web.config.
'Set additinal addresses
mailMessage.To.Add(New System.Net.Mail.MailAddress(txtToAddress.Text.Trim()))
'mailMessage.CC
'mailMessage.Bcc
'mailMessage.ReplyTo
'Set additional options
mailMessage.Priority = Net.Mail.MailPriority.High
'Text/HTML
mailMessage.IsBodyHtml = False
'Set the subjet and body text
mailMessage.Subject = txtSubject.Text.Trim()
mailMessage.Body = txtBody.Text.Trim()
'Add one to many attachments
'mailMessage.Attachments.Add(New System.Net.Mail.Attachment("c:\temp.txt")
'Create an instance of the SmtpClient class for sending the email
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
'Use a Try/Catch block to trap sending errors
'Especially useful when looping through multiple sends
Try
smtpClient.Send(mailMessage)
Catch smtpExc As System.Net.Mail.SmtpException
'Log error information on which email failed.
Catch ex As Exception
'Log general errors
End Try
End Sub
End Class
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send Email</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
From:<br />
<asp:TextBox ID="txtFromAddress" runat="server" Columns="35" /></p>
<p>
To:<br />
<asp:TextBox ID="txtToAddress" runat="server" Columns="35" /></p>
<p>
Subject:<br />
<asp:TextBox ID="txtSubject" runat="server" Columns="50" /></p>
<p>
Body:<br />
<asp:TextBox ID="txtBody" runat="server" Columns="75" TextMode="MultiLine" Rows="6" /></p>
<p>
<asp:Button ID="btnSend" runat="server" Text="Send Mail" /></p>
</div>
</form>
</body>
</html>
web config
<?xml version="1.0"?>
<!--
-->
<configuration>
<!--Externalize From address-->
<appSettings>
<add key="fromEmailAddress" value="syntaxDon#gmail.com"/>
</appSettings>
<!--Externalize From address-->
<connectionStrings/>
<!--Mail settings-->
<system.net>
<mailSettings>
<smtp>
<network host="\localhost:"/>
</smtp>
</mailSettings>
</system.net>
<!--Mail settings-->
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
Visual Basic options:
Set strict="true" to disallow all data type conversions
where data loss can occur.
Set explicit="true" to force declaration of all variables.
-->
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0">
</compilation>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<namespaces>
<clear/>
<add namespace="System"/>
<add namespace="System.Collections"/>
<add namespace="System.Collections.Generic"/>
<add namespace="System.Collections.Specialized"/>
<add namespace="System.Configuration"/>
<add namespace="System.Text"/>
<add namespace="System.Text.RegularExpressions"/>
<add namespace="System.Linq"/>
<add namespace="System.Xml.Linq"/>
<add namespace="System.Web"/>
<add namespace="System.Web.Caching"/>
<add namespace="System.Web.SessionState"/>
<add namespace="System.Web.Security"/>
<add namespace="System.Web.Profile"/>
<add namespace="System.Web.UI"/>
<add namespace="System.Web.UI.WebControls"/>
<add namespace="System.Web.UI.WebControls.WebParts"/>
<add namespace="System.Web.UI.HtmlControls"/>
</namespaces>
</pages>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
You have to bind btnSend_Click handler to the button:
<asp:Button ID="btnSend" runat="server" Text="Send Mail" OnClick="btnSend_Click" />

How do I impersonate using aspnet_personalization Windows Authentication

Having trouble figuring out how to impersonate another user while using aspnet_personalization with Windows authentication.
I am using asp.net's personalization framework on my page:
<asp:WebPartManager ID="WebPartManager1" runat="server" >
<Personalization Enabled="True" />
</asp:WebPartManager>
My page is in an existing web app that uses AuthenticationMode="Windows" (which I cannot change, and IIS is also set to Windows Authentication). This web app has a page that allows super-users to impersonate any other user. This is accomplished by manipulating a connection string that is built dynamically every time we hit the database.
My problem is that aspnet_personalization still uses windows authentication. When I try to edit the connection string used by aspnet_personalization dynamically, aspnet does not seem to use it - it still uses the username of the current NT account.
I have the following in my web.config's configuration tag:
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="AnotherConnectionString" connectionString="Data Source=serverName;Initial Catalog=dbName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"
applicationName="/"
connectionStringName="AnotherConnectionString" />
</providers>
</membership>
<profile enabled="true" defaultProvider="TableProfileProvider">
<providers>
<clear />
<add name="TableProfileProvider" type="Microsoft.Samples.SqlTableProfileProvider" connectionStringName="AnotherConnectionString" table="aspnet_Profile" applicationName="/" />
</providers>
<!--<properties></properties>-->
</profile>
I tried editing the connection string by adding code as follows whenever we impersonate a user, hoping asp.net would use it, but it does not:
Dim settings = ConfigurationManager.ConnectionStrings("AnotherConnectionString")
Dim fi = GetType(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic)
fi.SetValue(settings, False)
settings.ConnectionString = "data source=serverName;database=dbName;user id=" & login & "; password=" & password
I did confirm on page_load of the page containing the webPartManager that "AnotherConnectionString" does contain the desired username, but asp.net_personalization still calls its stored procs using the NT username.
ANSWER:
Stackoverflow won't let me post an answer. That's ridiculous, so after I post the answer inside the question, I'm deleting my account and will encourage others to do the same.
I solved the problem by extending SqlPersonalizationProvider:
Imports System.Web.UI.WebControls.WebParts
Public Class MySqlPersonalizationProvider
Inherits SqlPersonalizationProvider
Protected Overrides Sub LoadPersonalizationBlobs(ByVal webPartManager As System.Web.UI.WebControls.WebParts.WebPartManager, ByVal path As String, ByVal userName As String, ByRef sharedDataBlob() As Byte, ByRef userDataBlob() As Byte)
Dim impersonatedName As String = MySession.UserLoginName()
path = path & "|" & impersonatedName
userName = impersonatedName
MyBase.LoadPersonalizationBlobs(webPartManager, path, userName, sharedDataBlob, userDataBlob)
End Sub
Protected Overrides Sub SavePersonalizationBlob(ByVal webPartManager As System.Web.UI.WebControls.WebParts.WebPartManager, ByVal path As String, ByVal userName As String, ByVal dataBlob() As Byte)
Dim impersonatedName As String = MySession.UserLoginName()
path = path & "|" & impersonatedName
userName = impersonatedName
MyBase.SavePersonalizationBlob(webPartManager, path, userName, dataBlob)
End Sub
End Class
And then in web.config:
<system.web>
<webParts>
<personalization defaultProvider="AspNetSqlPersonalizationProvider">
<providers>
<remove name="AspNetSqlPersonalizationProvider"/>
<add name="AspNetSqlPersonalizationProvider"
type="MyProject.MySqlPersonalizationProvider"
connectionStringName="MyConnectionString"
applicationName="/"></add>
</providers>
</personalization>
</webParts>
<profile enabled="true" defaultProvider="TableProfileProvider">
<providers>
<clear />
<add name="TableProfileProvider" type="Microsoft.Samples.SqlTableProfileProvider" connectionStringName="iCaseHomepage" table="aspnet_Profile" applicationName="/" />
</providers>
</profile>
</system.web>
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="MyConnectionString" connectionString="Data Source=MyServerName;Initial Catalog=MyDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
and on the page:
<asp:WebPartManager ID="WebPartManager1" runat="server" >
<Personalization Enabled="True" />
</asp:WebPartManager>
Looks like I'm allowed to post an answer now. I guess I won't delete my account after all. But geez, SO isn't very friendly to noobs.
Anyway, I solved the problem by extending SqlPersonalizationProvider:
Imports System.Web.UI.WebControls.WebParts
Public Class MySqlPersonalizationProvider
Inherits SqlPersonalizationProvider
Protected Overrides Sub LoadPersonalizationBlobs(ByVal webPartManager As System.Web.UI.WebControls.WebParts.WebPartManager, ByVal path As String, ByVal userName As String, ByRef sharedDataBlob() As Byte, ByRef userDataBlob() As Byte)
Dim impersonatedName As String = MySession.UserLoginName()
path = path & "|" & impersonatedName
userName = impersonatedName
MyBase.LoadPersonalizationBlobs(webPartManager, path, userName, sharedDataBlob, userDataBlob)
End Sub
Protected Overrides Sub SavePersonalizationBlob(ByVal webPartManager As System.Web.UI.WebControls.WebParts.WebPartManager, ByVal path As String, ByVal userName As String, ByVal dataBlob() As Byte)
Dim impersonatedName As String = MySession.UserLoginName()
path = path & "|" & impersonatedName
userName = impersonatedName
MyBase.SavePersonalizationBlob(webPartManager, path, userName, dataBlob)
End Sub
End Class
And then in web.config:
<system.web>
<webParts>
<personalization defaultProvider="AspNetSqlPersonalizationProvider">
<providers>
<remove name="AspNetSqlPersonalizationProvider"/>
<add name="AspNetSqlPersonalizationProvider"
type="MyProject.MySqlPersonalizationProvider"
connectionStringName="MyConnectionString"
applicationName="/"></add>
</providers>
</personalization>
</webParts>
<profile enabled="true" defaultProvider="TableProfileProvider">
<providers>
<clear />
<add name="TableProfileProvider" type="Microsoft.Samples.SqlTableProfileProvider" connectionStringName="iCaseHomepage" table="aspnet_Profile" applicationName="/" />
</providers>
</profile>
</system.web>
<connectionStrings>
<remove name="LocalSqlServer"/>
<add name="MyConnectionString" connectionString="Data Source=MyServerName;Initial Catalog=MyDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
and on the page:
<asp:WebPartManager ID="WebPartManager1" runat="server" >
<Personalization Enabled="True" />
</asp:WebPartManager>

Registering custom controls fails

I am attempting to register my user controls within the webconfig file because I am receiving the Element does not exist error, but I am receiving the following error when I try to register them in webconfig:
Invalid or missing attributes found in the tagPrefix entry. For user control, you must also specify 'tagName' and 'src'. For custom control, you must also specify 'namespace', and optionally 'assembly'
The following is the code within the webconfig file:
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add tagPrefix="IPAMControl" tagName="contact_us" namespace="IPAM.Website.Controls" src="~/controls/contact_us.ascx" />
<add tagPrefix="IPAMControl" tagName="erh_list" namespace="IPAM.Website.Controls" src="~/controls/erh_list.ascx" />
<add tagPrefix="IPAMControl" tagName="header" namespace="IPAM.Website.Controls" src="~/controls/header.ascx" />
<add tagPrefix="IPAMControl" tagName="footer" namespace="IPAM.Website.Controls" src="~/controls/footer.ascx" />
<add tagPrefix="IPAMControl" tagName="main_tnavbar" namespace="IPAM.Website.Controls" src="~/controls/main_tnavbar.ascx" />
<add tagPrefix="IPAMControl" tagName="program_header" namespace="IPAM.Website.Controls" src="~/controls/program_header.ascx" />
<add tagPrefix="IPAMControl" tagName="program_list" namespace="IPAM.Website.Controls" src="~/controls/program_list.ascx" />
<add tagPrefix="IPAMControl" tagName="signup_section" namespace="IPAM.Website.Controls" src="~/controls/signup_section.ascx" />
<add tagPrefix="IPAMControl" tagName="speaker_list" namespace="IPAM.Website.Controls" src="~/controls/speaker_list.ascx" />
<add tagPrefix="IPAMControl" tagName="track" namespace="IPAM.Website.Controls" src="~/controls/track.ascx" />
</controls>
</pages>
The pages that are having this issue are also referencing MasterPages if that matters at all:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/programs/MasterProgram.master" CodeBehind="~/programs/wim2011/default.aspx" Inherits="IPAM.Website.programs.wim2011._default" %>
and they are each within their own folders.
Please help.
Get rid of the namespace attribute, as it's confusing ASP.NET as to whether you're attempting to register a User Control or a Custom Control.
User Control:
<add tagPrefix="SomeTagPrefix" src="~/Controls/SomeControl.ascx" tagName="SomeTagName"/>
Custom Control:
<add tagPrefix="SomeTagPrefix" namespace="SomeNamespace" assembly="SomeAssembly"/>
So, in your example:
<add tagPrefix="IPAMControl" tagName="track" src="~/controls/track.ascx" />
And on the ASPX/ASCX, you use it like this:
<IPAMControl:track id="ipamTrack" runat="server" />
See here for more info.
EDIT
To prove this works - i did the following:
Create new Web Application
Create new folder called "Controls" in the root of the web application
Added a new "Web User Control" called "MyUserControl.ascx"
Modified web.config to add registration of control
Modified Default.aspx to add the control.
And it all works fine.
Here is the User Control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="WebApplication1.Controls.MyUserControl" %>
<span>Hi, im a user control, how are you?</span>
Here is the portion of the web.config i edited:
<pages>
<controls>
<add tagPrefix="MyControls" tagName="MyUserControl" src="~/Controls/MyUserControl.ascx"/>
</controls>
</pages>
Here is the Default.aspx change i made:
<MyControls:MyUserControl id="myUserControl" runat="server" />
And the page rendered correctly.
Now, unless what i have done here is different to how you have attempting to do it, you must have other code/errors that is interfering with this.
Don't know how much else help i can be.

Resources