navigation
a webmaster learning community
     Home    Register     Search      Help      Login    
FrontPage Alternative
Sponsors

Shopping Cart Software
Ecommerce software integrated into Frontpage, Dreamweaver and Golive templates. No monthly fees and available in ASP and PHP versions.

Website Templates
We also have a wide selection of Dreamweaver, Expression Web and Frontpage templates as well as webmaster tools and CSS layouts.

Frontpage website templates
Creative Website Templates for FrontPage, Dreamweaver, Flash, SwishMax

Free FrontPage Templates

Search Forums
 

Advanced search
Recent Posts

 Todays Posts
 Most Active posts
 Posts since last visit
 My Recent Posts
 Mark posts read

 

Two Forms in conflict?

 
View related threads: (in this forum | in all forums)

Logged in as: Guest
Users viewing this topic: none
Printable Version 

All Forums >> Web Development >> ASP and Database >> Two Forms in conflict?
Page: [1]
 
kafka

 

Posts: 12
Joined: 5/9/2006
Status: offline

 
Two Forms in conflict? - 5/17/2006 12:31:13   
I have a submission form and a database editor. Before, everything worked fine. Now, on the database editor i've added a search. Now when I use the submission form (A) everything works fine and it writes to the database. However, once I head to the database editor (B) and try to add a new record, or update a record through that page I get the standard "The operation failed. If this continues, please contact your server administrator." error message and after that I can no longer submit using the original Submission form (A) and then have to restart my IIS Service to once again test the database to write anything to it. Yikes, what can it be? My eyes are bleeding code!!! (It's like it locks out the database...I'm working from the top down on this thing and getting familiar with ASP that way and unfortunately that's the way it has to be at this moment. I appreciate the help. DOES THIS HAVE ANYTHING TO DO WITH PAGE INHERITANCE??

and the code:
<%@ Page Inherits="Microsoft.Office.FrontPage.DBInterface.DBEditor" Src="../../../_fpclass/fpdbnet.cs" Language="c#" Trace="true" Debug="true" SmartNavigation="True"%>
<%@ Register TagPrefix="FPDB" TagName="DBRegion" Src="../../../_fpclass/dbregion.ascx"%>
<%@ Register Tagprefix="FPDB" TagName="DBQuery" Src="../../../_fpclass/dbquery.ascx"%><HTML>
    <HEAD>
        <title>
                               
			Database Editor
        </title>
        
        <META http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <script language="javascript">
        function VerifyDelete()
        {
            var L_ConfirmDelete_Text = "Are you sure you want to delete this record?"; // {StringCategory=TXT}
            if( confirm(L_ConfirmDelete_Text) )
            {
                Page_ValidationActive = false;
                return true;
            }
            return false;
        }

        function CatchReturn( e )
        {
            if( !e || !document.getElementById )
                return;	

            var elmSrc = e.srcElement ? e.srcElement : e.target ? e.target : null;

            if( !elmSrc )
                return;

            var elmSubmit = document.getElementById('SubmitChangeButton');

            if( e.keyCode == 13 && 
                elmSrc.tagName != "TEXTAREA" &&
                elmSubmit )
            {
                if( elmSubmit.click ) 
                    elmSubmit.click();

                e.returnValue = false;
            }
        }
        </script>
        <script language="C#" Runat="server">
        public override void InitEditor()
        {
            FieldNames="FirstName,LastName,Address,City,State,PostalCode,Region,Country,Title,WorkPhone,HomePhone,MobilePhone,EmailName,Notes";
            FieldFriendlyNames="FirstName,LastName,Address,City,State,PostalCode,Region,Country,Title,WorkPhone,HomePhone,MobilePhone,EmailName,Notes";
            FieldTypes="txt,txt,txt,txt,txt,txt,txt,txt,txt,txt,txt,txt,txt,txt";
            FieldDefaults=",,,,,,,,,,,,,";
        
            UseControls();
        }
        </script>
	<script language="C#" runat="server" src="../../../_fpclass/fputil.cs">
	</script>
    <meta name="GENERATOR" content="Microsoft FrontPage 6.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
</HEAD>
    <BODY bgcolor="#7B6CC1">
        <form ID="frmDBEditor" method="post" runat="server">
          <div ID="Region0Fields" Runat="server">
            <table width="100%" align="left" bgcolor="#FFFFFF">
                <tr>
                    <td width="50%"><b>
					<font color="#000080" size="+3" face="Arial Narrow">
                                Database Editor - <I>
                                    Contacts
                                </I></font></b>
                    </td>
                    <td vAlign="middle" align="right" width="50%">
                        <font face="Arial Narrow">
                        <font size="2">  <a href="search_form.aspx">Search 
						Form</a> |
                        <a href="../results_page.aspx" target="_top">Results Page</a> | 
<a href="submission_form.aspx" target="_top">Submission Form</a> | 
Database Editor</font>
                    </font>
                    </td>
                </tr>
            </table>
            <p>
                <font face="Arial Narrow">
                <br clear="all">
                </font>
                <hr>
            </P>
            <P></P>
            <P></P>
            <table bgcolor="#FFFFFF">
			<tr>
				<td align="right"><font face="Arial" size="2"><b>FirstName</b></font></td>
				<td><font face="Arial" size="2">
				<asp:TextBox ID="FirstName" Runat="server"></asp:TextBox></font>
				</td>
			</tr>
			<tr>
				<td align="right"><font face="Arial" size="2"><b>LastName</b></font></td>
				<td><font face="Arial" size="2">
				<asp:TextBox ID="LastName" Runat="server"></asp:TextBox></font>
				</td>
			</tr>
			<tr>
				<td align="right"><font face="Arial" size="2"><b>Email</b></font></td>
				<td><font face="Arial" size="2">
				<asp:TextBox ID="EmailName" Runat="server"></asp:TextBox></font>
				</td>
			</tr>
		</table>
	</div>
	<font face="Arial" size="2">
	<FPDB:DBQuery ID="Region0Query" QuerySource="Region0Fields" Runat="server"></FPDB:DBQuery>
	</font>
    <asp:DataGrid ID="Region0" OnItemDataBound="Item_Bound" Runat="server" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#ECE9D8" ItemStyle-BackColor="#C0C0C0" HeaderStyle-Font-Bold="True" BorderColor="Black" CellPadding="3" headerstyle-backcolor="#FFFFFF">
                <Columns>
                    <asp:TemplateColumn>
                        <HeaderTemplate>  Edit
                        </HeaderTemplate>
                        <ItemTemplate>
                            <table>
                                <tr>
                                    <td valign="middle">
                                        <asp:ImageButton ID="Imagebutton" ImageUrl="../../../images/edit.gif" OnCommand="CommandImageEdit" CommandName='<%#DataBinder.Eval(Container, "DataItem.ContactID") %>' runat="server" CausesValidation="False"/></td>
                                </tr>
                            </table>
                        </ItemTemplate>
                    </asp:TemplateColumn>
                    
				<asp:BoundColumn DataField="ContactID" HeaderText="ContactID"/>
				<asp:BoundColumn DataField="FirstName" HeaderText="FirstName"/>
				<asp:BoundColumn DataField="LastName" HeaderText="LastName"/>
				<asp:BoundColumn DataField="Address" HeaderText="Address"/>
				<asp:BoundColumn DataField="City" HeaderText="City"/>
				<asp:BoundColumn DataField="State" HeaderText="State"/>
				<asp:BoundColumn DataField="PostalCode" HeaderText="PostalCode"/>
				<asp:BoundColumn DataField="Region" HeaderText="Region"/>
				<asp:BoundColumn DataField="Country" HeaderText="Country"/>
				<asp:BoundColumn DataField="Title" HeaderText="Title"/>
				<asp:BoundColumn DataField="WorkPhone" HeaderText="WorkPhone"/>
				<asp:BoundColumn DataField="HomePhone" HeaderText="HomePhone"/>
				<asp:BoundColumn DataField="MobilePhone" HeaderText="MobilePhone"/>
				<asp:BoundColumn DataField="EmailName" HeaderText="EmailName"/>
				<asp:BoundColumn DataField="Notes" HeaderText="Notes"/>
                </Columns>
            </asp:DataGrid>
            <asp:Label ID="Region0NoResults" Text="No records returned." Runat="server" Visible="False"></asp:Label>
	<FPDB:DBRegion ID="DBRegion" Target="Region0" DBName="data" TableKey="ContactID" RootPath="../../../" NoResults="Region0NoResults" TableName="Contacts" AllowPaging="True" PageSize="5" Where="(FirstName =  '::FirstName::' OR LastName =  '::LastName::' OR EmailName =  '::EmailName::')" UserFields="Region0Query" OrderBy="LastName ASC" MaxRecords="256" Runat="server"></FPDB:DBRegion>

            <p><font face="Arial Narrow">
            </font></p>
            <hr>
            <font face="Arial Narrow">
            <asp:button ID="AddNewRecordButton" onclick="ClickButtonAddNewRecord" Text="Add new record" Runat="server" CausesValidation="False" /><br>
            <br>
            </font>
            <div ID="EditorPanel" onKeyDown="CatchReturn( event )" Runat="server" style="background-color: #FFFF00">
                <TABLE bgcolor="#C0C0C0">
                    <TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>FirstName:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtFirstName" Columns="50" Runat="server" />
<asp:RequiredFieldValidator ID="reqid3" ControlToValidate="txtFirstName" ErrorMessage="Required!" Display=Dynamic Runat="server"/>
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>LastName:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtLastName" Columns="50" Runat="server" />
<asp:RequiredFieldValidator  ID="reqid2" ControlToValidate="txtLastName" ErrorMessage="Required!" Display=Dynamic Runat="server"/>
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>Address:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtAddress" Columns="64" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>City:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtCity" Columns="50" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>State:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtState" Columns="20" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>PostalCode:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtPostalCode" Columns="20" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>Region:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtRegion" Columns="50" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>Country:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtCountry" Columns="50" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>Title:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtTitle" Columns="50" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>WorkPhone:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtWorkPhone" Columns="30" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>HomePhone:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtHomePhone" Columns="30" Runat="server" />
<asp:RequiredFieldValidator ID="reqid" ControlToValidate="txtHomePhone" ErrorMessage="Required!" Display=Dynamic Runat="server"/>
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>MobilePhone:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtMobilePhone" Columns="30" Runat="server" />
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>EmailName:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtEmailName" Columns="50" Runat="server" />
<asp:RequiredFieldValidator ID="reqid4" ControlToValidate="txtEmailName" ErrorMessage="Required!" Display=Dynamic Runat="server"/>
</font>
</TD>
</TR>
<TR>
<TD vAlign="top" align="right"><font face="Arial Narrow"><B>Notes:</B></font></TD>
<TD>
<font face="Arial Narrow">
<asp:TextBox ID="txtNotes" Columns="64" Runat="server" Rows="4" TextMode="MultiLine" />
</font>
</TD>
</TR>

                </TABLE>
                <font face="Arial Narrow">
                <BR>
                <asp:button id="SubmitChangeButton" onclick="ClickButtonSubmitChange" Text="Apply changes" Runat="server" />
                <asp:button id="CancelChangeButton" onclick="ClickButtonCancelChange" Text="Cancel changes" Runat="server" CausesValidation="False" />
                <asp:button id="ResetRecordButton" onclick="ClickButtonResetRecord" Text="Reset this record" Runat="server" CausesValidation="False" />
                <input type="button" id="DeleteRecordButton" onclick="if(!VerifyDelete()) return false;" onserverclick="ClickButtonDeleteRecord" Value="Delete this record" Runat="server" CausesValidation="False">
            	</font>
            </div>
            <font face="Arial Narrow">
            <br>
            <br>
            <asp:label id="PageErrorTextLabel" Text="[Place holder for page error messages]" Runat="server" />
        	</font>
        </form>
    </BODY>
</HTML>


< Message edited by Spooky -- 5/17/2006 16:19:47 >
yb2

 

Posts: 653
Joined: 1/30/2006
Status: offline

 
RE: Two Forms in conflict? - 5/18/2006 5:03:18   
Hello Kafka,

It looks as if you are using asp.net with C#, and you're putting the search results into a dataset and then into a datagrid - is that right?

Could you post the code behind file for us to look at??

_____________________________

it is natural for people not to see one's own faults, and to exaggerate other people's faults and failings.
Currently listening to: L'Enfer Des Formes by Stereolab

(in reply to kafka)
kafka

 

Posts: 12
Joined: 5/9/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 11:39:14   
Sure Thanks here goes! I'm stumped, and because i just don't know enough, i spent yesterday all day on C# and Java tutorials/research. Here is the standard _fpdbnet.cs code that the previous code accesses. Once again i appreciate the help. oh BTW, if i rotate between forms A,B,C sometimes they write to the database sometimes they don't. It depends which forms follow which forms and in what order. There has to be a clue there but i can't figure it out.
and just so you know, THIS FORUM ROCKS. you guys really are on top of it!

_fpdbnet.cs code:
using System;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace Microsoft.Office.FrontPage.DBInterface
{
/* This class implements the basic functionality of connecting to a database, providing DataSets
* and DataViews on the connection, and managing the cached version of the DataSet.
*/
public class DBConnection
{
private OleDbConnection _dBConn = null;
private OleDbDataAdapter _dataAdpater = null;
private HttpServerUtility _server = null;
private Page fpPage = null;
private Cache _cache;
private int _maxRecordCount;
private string _cacheKey;
private string _dBName;
private string _tableName;
private string _tableKey;
private string _rootPath;
private string _searchQuery;
private ArrayList _paramList;

public string CacheName
{
get{
if(_cacheKey == null)
_cacheKey = DBName;
return _cacheKey;
}
set{
_cacheKey = value;
}
}

public string DBName
{
get{
if(_dBName == null)
_dBName = ConfigurationSettings.AppSettings["DBName"];
return _dBName;
}
set{
_dBName = value;
}
}

public int MaxRecordCount
{
get{
return _maxRecordCount;
}
set{
_maxRecordCount = value;
}
}

public string RootPath
{
get{
if(_rootPath == null)
_rootPath = ConfigurationSettings.AppSettings["RootPath"];
return _rootPath;
}
set{
_rootPath = value;
}
}

public string SearchQuery
{
get{
if(_searchQuery == null)
BuildSearchQuery();
return _searchQuery;
}
set{
_searchQuery = value;
}
}

public string TableName
{
get{
if(_tableName == null )
_tableName = ConfigurationSettings.AppSettings["TableName"];
if(_tableName == null || _tableName.Length == 0)
_tableName = "Table";
return _tableName;
}
set{
_tableName = value;
}
}

public string TableKey
{
get{
if(_tableKey == null)
_tableKey = ConfigurationSettings.AppSettings["TableKey"];
if(_tableKey == null || _tableKey.Length == 0)
SetTableKeyFromDataSet();
return _tableKey;
}
set{
_tableKey = value;
}
}



public DBConnection(Page parentPage)
{
CacheName = "WorkingDataSet";
fpPage = parentPage;
}


private HttpServerUtility GetServer()
{
if(_server == null)
{
_server = fpPage.Server;
}

return _server;
}

private Cache GetCache()
{
if(_cache == null)
{
_cache = fpPage.Cache;
}
return _cache;
}



public virtual DataSet GetDataSet(bool useCache)
{
if(useCache && HasCache())
{
return (DataSet)GetCache()[CacheName];
}
else
{
DataSet theDataSet = new DataSet();
theDataSet.Locale = CultureInfo.InvariantCulture;

if(_dataAdpater == null)
GetConnection();

ApplyParameters();
if(MaxRecordCount > 0)
{
_dataAdpater.Fill(theDataSet, 0, MaxRecordCount, TableName);
}
else
{
_dataAdpater.Fill( theDataSet );
}

if(useCache)
GetCache()[CacheName] = theDataSet;

return theDataSet;
}
}

private void SetTableKeyFromDataSet()
{
if( TableKey == null )
{
TableKey = GetDataSet(true).Tables[0].Columns[0].ColumnName;
}
}

public void RefreshCache()
{
GetCache()[CacheName] = GetDataSet(false);
}

public bool HasCache()
{
return (GetCache()[CacheName] != null && GetCache()[CacheName] is DataSet);
}

public DataView GetDataView( )
{
return GetDataSet( true ).Tables[0].DefaultView;
}

public DataView GetDataView( string rowFilter, string sortFilter )
{
return new DataView( GetDataSet( true ).Tables[ 0 ], rowFilter, sortFilter, DataViewRowState.Unchanged );
}

public virtual bool SaveChangesToDatabase()
{
if(_dataAdpater == null)
GetConnection();

try{
_dataAdpater.Update(GetDataSet(true));
}
catch( System.Exception ex){
throw new ApplicationException(ex.Message);
}
return true;
}

protected void BuildSearchQuery()
{
StringBuilder sb = new StringBuilder("SELECT * FROM ");

sb.Append("[");
sb.Append(TableName);
sb.Append("]");

SearchQuery = sb.ToString();
}

protected virtual void GetConnection()
{
if( DBName == null )
throw new ApplicationException( "FPDB: Database region must given the name of a database connection" );

String strProvider = ConfigurationSettings.AppSettings[ DBName + "_Provider" ];
String strDataSource;
String strDatabase = null;
String strUsername = ConfigurationSettings.AppSettings[ DBName + "_RuntimeUsername" ];
String strPassword = ConfigurationSettings.AppSettings[ DBName + "_RuntimePassword" ];
String strAddition = ConfigurationSettings.AppSettings[ DBName + "_AdditionalParams" ];

if(strProvider == null)
throw new
ApplicationException( "FPDB: Unable to find connection information for database connection '" + DBName + "'");

if(strProvider.Equals("Microsoft.Jet.OLEDB.4.0"))
{
strDataSource = GetServer().MapPath( RootPath + ConfigurationSettings.AppSettings[DBName + "_DataSource"] );
}
else
{
strDataSource = ConfigurationSettings.AppSettings[DBName + "_DataSource"];
strDatabase = ConfigurationSettings.AppSettings[DBName + "_Database"];
}

StringBuilder strConString = new StringBuilder("Provider=");
strConString.Append( strProvider );
strConString.Append( ";Data Source=" );
strConString.Append( strDataSource );
if( strDatabase != null && strDatabase.Length != 0 )
{
strConString.Append("; Database=" );
strConString.Append( strDatabase);
}
if( strUsername != null && strUsername.Length != 0 )
{
strConString.Append( "; User ID=" );
strConString.Append( strUsername);
}
if( strPassword != null && strPassword.Length != 0 )
{
strConString.Append( "; Password=" );
strConString.Append( strPassword );
}
if( strAddition != null && strAddition.Length != 0 )
{
strConString.Append( "; " );
strConString.Append( strAddition );
}

_dBConn = new OleDbConnection(strConString.ToString());
_dataAdpater = new OleDbDataAdapter(SearchQuery, _dBConn);
OleDbCommandBuilder OdcbCommand = new OleDbCommandBuilder(_dataAdpater);

try{
_dBConn.Open();
DataTable literalInfo = _dBConn.GetOleDbSchemaTable(OleDbSchemaGuid.DbInfoLiterals, null);
OdcbCommand.QuotePrefix = (String)literalInfo.Select("LiteralName='Quote_Prefix'")[0]["LiteralValue"];
OdcbCommand.QuoteSuffix = (String)literalInfo.Select("LiteralName='Quote_Suffix'")[0]["LiteralValue"];
}
catch( OleDbException ex ){
throw new ApplicationException( "FPDB: Failed to create database connection", ex );
}
finally{
_dBConn.Close();
}
}


public void SetConnectionParameters(ArrayList parameterList)
{
_paramList = parameterList;
}

protected void ApplyParameters()
{
if(_paramList == null)
return;
if(_dataAdpater == null)
return;
OleDbParameterCollection CommandParams = _dataAdpater.SelectCommand.Parameters;
CommandParams.Clear();
int i;
for(i=0;i<_paramList.Count;i++)
{
CommandParams.Add(new OleDbParameter("@P"+i, _paramList));
}
}
}

/* This class provides a basic level of interaction between a page designed to work against a database
* and the database itself. It has the ability to read data from controls found in the page and place them
* in a DataRow for insertion into the database.
*/
public abstract class DBInterfacePage : System.Web.UI.Page
{
private DBConnection _connection;
private System.Web.UI.WebControls.Label _pageErrorLabel;
private DBRegionBase _dBRegion;

private StringCollection _fieldDefaultsCollection;
private StringCollection _fieldFriendlyNamesCollection;
private StringCollection _fieldNamesCollection;
private StringCollection _fieldTypesCollection;
private bool DebugOn = false;
private string DefaultFieldValues;
private string FriendlyNamesOfFields;
private string NamesOfFields;
private string TypesOfFields;

public DBConnection Connection
{
get{
return _connection;
}
}

public DBRegionBase DBRegion
{
get{
return _dBRegion;
}
set{
_dBRegion = value;
}
}
public string FieldDefaults
{
get{
return DefaultFieldValues;
}
set{
DefaultFieldValues = value;
}
}
public string FieldNames
{
get{
return NamesOfFields;
}
set{
NamesOfFields = value;
}
}

public string FieldFriendlyNames
{
get{
return FriendlyNamesOfFields;
}
set{
FriendlyNamesOfFields = value;
}
}

public string FieldTypes
{
get{
return TypesOfFields;
}
set{
TypesOfFields = value;
}
}

public System.Web.UI.WebControls.Label PageErrorTextLabel
{
get{
return _pageErrorLabel;
}
set{
_pageErrorLabel = value;
}
}

public DBInterfacePage()
{
_connection = new DBConnection(this);
}



protected override void OnInit( EventArgs e )
{
base.OnInit(e);
if( DBRegion != null )
DBRegion.SetConnection( _connection );
}

protected void BindData()
{
if( DBRegion != null )
{
DBRegion.DataBind();
}
}

public void ErrorMessage(string errorText)
{
if(PageErrorTextLabel == null)
{
return;
}


if(DebugOn)
{
if(PageErrorTextLabel.Text.Length == 0)
{
PageErrorTextLabel.Text = "<B>Debug messages:</B><br>";
}
PageErrorTextLabel.Text += errorText + "<br>";
}
else
{
PageErrorTextLabel.Text =
"The operation failed. If this continues, please contact your server administrator.<br>";
}
}

public void ResetErrorMessages()
{
if(PageErrorTextLabel != null)
{
PageErrorTextLabel.Text = "";
}
}

public virtual void UseControls()
{
_fieldNamesCollection = (StringCollection)Session["FieldNames"];
_fieldFriendlyNamesCollection = (StringCollection)Session["FieldFriendlyNames"];
_fieldTypesCollection = (StringCollection)Session["FieldTypes"];
_fieldDefaultsCollection = (StringCollection)Session["FieldDefaults"];

if(_fieldNamesCollection == null || _fieldTypesCollection == null || _fieldFriendlyNamesCollection == null)
{
GetFieldData();
}
}

protected virtual void GetFieldData()
{
string sFieldNameList;
string sFieldFriendList;
string sFieldTypeList;
string sFieldDefaultsList;
if( FieldNames != null )
{
sFieldNameList = FieldNames;
}
else
{
sFieldNameList = ConfigurationSettings.AppSettings["FieldNames"];
}
if( FieldFriendlyNames != null)
{
sFieldFriendList = FieldFriendlyNames;
}
else
{
sFieldFriendList = ConfigurationSettings.AppSettings["FieldFriendlyNames"];
}
if( FieldTypes != null )
{
sFieldTypeList = FieldTypes;
}
else
{
sFieldTypeList = ConfigurationSettings.AppSettings["FieldTypes"];
}
if( FieldDefaults != null )
{
sFieldDefaultsList = FieldDefaults;
}
else
{
sFieldDefaultsList = ConfigurationSettings.AppSettings["FieldDefaults"];
}


int nNameComma, nFriendComma, nTypeComma, nDefaultComma;

_fieldNamesCollection = new StringCollection();
_fieldFriendlyNamesCollection = new StringCollection();
_fieldTypesCollection = new StringCollection();

if(sFieldDefaultsList != null)
{
_fieldDefaultsCollection = new StringCollection();
}

while((nNameComma=sFieldNameList.IndexOf(",")) != -1
&& (nFriendComma = sFieldFriendList.IndexOf(",")) != -1
&& (nTypeComma=sFieldTypeList.IndexOf(",")) != -1 )
{
if(_fieldDefaultsCollection != null)
{
if((nDefaultComma=sFieldDefaultsList.IndexOf(",")) == -1)
{
break;
}

_fieldDefaultsCollection.Add(sFieldDefaultsList.Substring(0,nDefaultComma));
sFieldDefaultsList = sFieldDefaultsList.Substring(nDefaultComma+1);
if(sFieldDefaultsList == null)
{
sFieldDefaultsList = string.Empty;
}
}
_fieldNamesCollection.Add(sFieldNameList.Substring(0,nNameComma));
sFieldNameList = sFieldNameList.Substring(nNameComma+1);
_fieldFriendlyNamesCollection.Add(sFieldFriendList.Substring(0,nFriendComma));
sFieldFriendList = sFieldFriendList.Substring(nFriendComma+1);
_fieldTypesCollection.Add(sFieldTypeList.Substring(0,nTypeComma));
sFieldTypeList = sFieldTypeList.Substring(nTypeComma+1);
}
_fieldNamesCollection.Add(sFieldNameList);
_fieldFriendlyNamesCollection.Add(sFieldFriendList);
_fieldTypesCollection.Add(sFieldTypeList);

if(_fieldDefaultsCollection != null)
_fieldDefaultsCollection.Add(sFieldDefaultsList);

Session["FieldNames"] = _fieldNamesCollection;
Session["FieldFriendNames"] = _fieldFriendlyNamesCollection;
Session["FieldTypes"] = _fieldTypesCollection;
Session["FieldDefaults"] = _fieldDefaultsCollection;

if( sFieldNameList.IndexOf(",") != -1 &&
sFieldFriendList.IndexOf(",") != -1 &&
sFieldTypeList.IndexOf(",") != -1 &&
( _fieldDefaultsCollection!=null && sFieldDefaultsList.IndexOf(",") != -1 ) )
{
ErrorMessage("Mismatch in number of field names, types, and defaults in web.config");
}
}

private string GetControlValue( Control controlParent, int index )
{
Control ctl = controlParent.FindControl( _fieldTypesCollection[index] + _fieldFriendlyNamesCollection[index] );
if( ctl == null && (_fieldTypesCollection[index] + _fieldFriendlyNamesCollection[index]).Length != 0 )
{
ErrorMessage( "No control found for '" + _fieldNamesCollection[index] + "'" );
return string.Empty;
}
if(_fieldTypesCollection[index].Equals("txt"))
{
return ((TextBox)ctl).Text;
}
else if(_fieldTypesCollection[index].Equals("rdo"))
{
ListItem item = ((RadioButtonList)ctl).SelectedItem;
if(item != null)
{
return item.Value;
}
else
{
return null;
}
}
else if(_fieldTypesCollection[index].Equals("ddl"))
{
ListItem item = ((DropDownList)ctl).SelectedItem;
if(item != null)
{
return item.Value;
}
else
{
return null;
}
}
else if(_fieldTypesCollection[index].Equals("chk"))
{
return ((CheckBox)ctl).Checked ? "True" : "False" ;
}

return string.Empty;
}

private void SetControlValue( Control parent, int index, string sValue )
{
Control control = parent.FindControl( _fieldTypesCollection[index] + _fieldFriendlyNamesCollection[index] );
if( control == null && (_fieldTypesCollection[index] + _fieldFriendlyNamesCollection[index]).Length == 0 )
{
ErrorMessage( "No control found for '" + _fieldNamesCollection[index] + "'" );
return;
}

if(_fieldTypesCollection[index].Equals("txt"))
((TextBox)control).Text = sValue;
else if(_fieldTypesCollection[index].Equals("rdo"))
{
if(((RadioButtonList)control).SelectedIndex != -1)
{
((RadioButtonList)control).Items[((RadioButtonList)control).SelectedIndex].Selected = false;
}

if( sValue.Length == 0 )
{
((RadioButtonList)control).SelectedIndex = -1;
return;
}
ListItem item = ((RadioButtonList)control).Items.FindByValue( sValue );
if(item != null)
{
item.Selected = true;
}
else
{
ErrorMessage( "" + sValue + " is not an option given for " + _fieldNamesCollection[index] + "");
}
}
else if(_fieldTypesCollection[index].Equals("ddl"))
{
if( sValue.Length == 0 )
{
((DropDownList)control).SelectedIndex = -1;
return;
}
ListItem item = ((DropDownList)control).Items.FindByValue( sValue );
if(item != null)
{
item.Selected = true;
}
else
{
ErrorMessage("" + sValue + " is not an option given for " + _fieldNamesCollection[index] + "");
}
}
else if(_fieldTypesCollection[index].Equals("chk"))
{

((CheckBox)control).Checked = Convert.ToBoolean( sValue, CultureInfo.InvariantCulture );
}
}

public void FillRowWithControls(DataRow row, Control controlParent)
{
FillRowWithControls( row, controlParent, false );
}

public bool FillRowWithControls(DataRow row, Control parent, bool checkUniqueKey)
{
if(_fieldNamesCollection == null || _fieldTypesCollection == null)
return false;

if(checkUniqueKey)
{
for( int i = 0; i < _fieldNamesCollection.Count; i++ )
if( _fieldNamesCollection.Equals( _connection.TableKey ) )
{
string sKeySearch = "[" + _connection.TableKey + "]='"
+ GetControlValue( parent, i ) + "'";
if( _connection.GetDataSet(true).Tables[0].Select( sKeySearch ).GetLength( 0 ) != 0 )
{
return false;
}
else
{
break;
}
}
}

for(int i=0; i<_fieldNamesCollection.Count; i++)
{
try{
if( _fieldNamesCollection.Length == 0 )
continue;

string curString = GetControlValue( parent, i );
if( ( curString != null ) && ( curString.Length != 0 ) )
{
row[_fieldNamesCollection] = curString;
}
else
{
row[_fieldNamesCollection] = DBNull.Value;
}
}
catch( FormatException ex ){
ErrorMessage("While writing field '" + _fieldNamesCollection + "' : " + ex.Message + "");
}
}

return true;
}

public void FillControlsWithRow(Control controlParent, DataRow row)
{
if(_fieldNamesCollection == null || _fieldTypesCollection == null)
return;

int i=0;

try{
for(; i<_fieldNamesCollection.Count; i++)
{
if( _fieldNamesCollection.Length == 0 )
continue;

SetControlValue( controlParent, i, row[_fieldNamesCollection].ToString() );
}
}
catch( FormatException ex ){
ErrorMessage( "While reading '" + _fieldNamesCollection + "' into control: " + ex.Message + "" );
}
}

public void FillControlsWithDefaults(Control controlParent)
{
if(_fieldNamesCollection == null || _fieldTypesCollection == null)
{
return;
}

int i = 0;
if(_fieldDefaultsCollection == null)
{
ErrorMessage("No defaults found");
_fieldDefaultsCollection = new StringCollection();
for(i = 0; i<_fieldNamesCollection.Count; i++)
_fieldDefaultsCollection.Add("");
}

try{
for(i = 0; i<_fieldNamesCollection.Count; i++)
{
if( _fieldNamesCollection.Length == 0 )
{
continue;
}

SetControlValue( controlParent, i, _fieldDefaultsCollection );
}
}
catch( FormatException ex ){
ErrorMessage( "While reading '" + _fieldNamesCollection + "' into control: " + ex.Message + "");
}
}
}

/* This class provides additional functionality over DBInterfacePage in order to enable the user to do full
* edits and deletes of data as well as
*/
public abstract class DBEditor : DBInterfacePage
{

private Button _addNewRecordButton;
private Button _cancelChangeButton;
private Button _resetRecordButton;
private Button _submitChangeButton;
private DataGrid _resultsGrid;

private HtmlInputButton _deleteRecordButton;
private HtmlGenericControl _editorPanel;
private HtmlGenericControl _keyEditPanel;



public Button AddNewRecordButton
{
get{
return _addNewRecordButton;
}
set{
_addNewRecordButton = value;
}
}

public Button CancelChangeButton
{
get{
return _cancelChangeButton;
}
set{
_cancelChangeButton = value;
}
}

public Button ResetRecordButton
{
get{
return _resetRecordButton;
}
set{
_resetRecordButton = value;
}
}
public Button SubmitChangeButton
{
get{
return _submitChangeButton;
}
set{
_submitChangeButton = value;
}
}


public DataGrid ResultsGrid
{
get{
return _resultsGrid;
}
set{
_resultsGrid = value;
}
}

public HtmlInputButton DeleteRecordButton
{
get{
return _deleteRecordButton;
}
set{
_deleteRecordButton = value;
}
}
public HtmlGenericControl EditorPanel
{
get{
return _editorPanel;
}
set{
_editorPanel = value;
}
}
public HtmlGenericControl KeyEditPanel
{
get{
return _keyEditPanel;
}
set{
_keyEditPanel = value;
}
}


private void OnLoadPage(object sender, System.EventArgs e)
{
InitEditor();

if(!IsPostBack)
{
BindData();
SetEditorState(false, false);
}
else if(!Connection.HasCache())
Response.Redirect("session_expired.aspx");

ResetErrorMessages();
}

public abstract void InitEditor();

//Sets the enabled/disabled state of the detail and editing view of the
//editor.
//Params:
// isEnabled determines whether or not the view should be visible and enabled
// isAdding determine whether or not the view is adding a new record, or updating
// an existing record.
protected void SetEditorState(bool isEnabled, bool isAdding)
{
EditorPanel.Visible = isEnabled;
AddNewRecordButton.Enabled = !isEnabled;

if( KeyEditPanel != null )
KeyEditPanel.Visible = isAdding;
DeleteRecordButton.Visible = !isAdding;

if(isAdding)
InitialValues(null);
}

//Sets the values of all controls to their starting value.
//Params:
// row - determines what row to base the starting values on.
// If it's null, use FieldDefaults.
// If it's non-null, use
protected void InitialValues(DataRow row)
{
if(row == null)
FillControlsWithDefaults(EditorPanel);
else
FillControlsWithRow(EditorPanel, row);
}

protected DataRow CurrentRow()
{

DataView theDataView = new DataView(Connection.GetDataSet(true).Tables[0]);
theDataView.RowFilter = (String)Session["WorkingDataRow"];
return theDataView[0].Row;
}

protected void ClickButtonAddNewRecord(Object sender, EventArgs e)
{
InitialValues(null);

Session["AddingDataRow"] = "true";

SetEditorState(true, true);
}

protected void ClickButtonResetRecord(Object sender, EventArgs e)
{
try{
if(Session["AddingDataRow"] != null)
{
InitialValues(null);
}
else
{
InitialValues(CurrentRow());
}
}
catch(RowNotInTableException notInTable){
ErrorMessage(notInTable.Message);
SetEditorState(false, false);
}
}


protected void ClickButtonCancelChange(Object sender, EventArgs e)
{
Session["WorkingDataRow"] = null;
SetEditorState(false, false);
}

protected void ClickButtonDeleteRecord(Object sender, EventArgs e)
{
try{
DataRow row = CurrentRow();

if(row != null)
row.Delete();

Session["WorkingDataRow"] = null;
Connection.SaveChangesToDatabase();
BindData();

SetEditorState(false, false);
}
catch(ApplicationException dbi){
ErrorMessage (dbi.Message);
}
}

protected void ClickButtonSubmitChange(Object sender, EventArgs e)
{
try{
DataRow row;
bool isAdding = Session["AddingDataRow"] != null;
if(isAdding)
{
row = Connection.GetDataSet(true).Tables[0].NewRow();
}
else
{
row = CurrentRow();
}
if(row == null)
{
ErrorMessage(
"Error: Your session data has been damaged.<br>No changes were made to this record but your other changes are still available.");
ClickButtonCancelChange(sender,e);
}
else
{
row.BeginEdit();

if( FillRowWithControls(row, EditorPanel, isAdding ) )
{
row.EndEdit();
if(isAdding)
{
Connection.GetDataSet(true).Tables[0].Rows.Add(row);
}
Connection.SaveChangesToDatabase();
Connection.RefreshCache();
BindData();

Session["WorkingDataRow"] = null;
Session["AddingDataRow"] = null;
SetEditorState(false, false);
}
else
{
row.CancelEdit();
ErrorMessage("'" + Connection.TableKey + "' must be unique.");
}
}
}
catch(ApplicationException dbi){
ErrorMessage (dbi.Message);
}
}

protected void CommandImageEdit(Object sender, CommandEventArgs e)
{
DataView theDataView = new DataView(Connection.GetDataSet(true).Tables[0]);
StringBuilder sb = new StringBuilder("[");
sb.Append( Connection.TableKey );
sb.Append( "]='");
sb.Append( e.CommandName );
sb.Append( "'" );
theDataView.RowFilter = sb.ToString();


if(theDataView.Count == 0)
{
ErrorMessage("Row not found in Cache.");
Connection.RefreshCache();
BindData();
}
else
{
InitialValues(theDataView[0].Row);
Session["WorkingDataRow"] = sb.ToString();
Session["AddingDataRow"] = null;
SetEditorState(true, false);
}
}

override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.OnLoadPage);
}
}

public abstract class DBRegionBase : System.Web.UI.UserControl
{
public abstract override void DataBind();
public abstract void SetConnection( DBConnection theConnection );
}
}


(in reply to yb2)
yb2

 

Posts: 653
Joined: 1/30/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 11:41:04   
and what database are you using?

_____________________________

it is natural for people not to see one's own faults, and to exaggerate other people's faults and failings.
Currently listening to: L'Enfer Des Formes by Stereolab

(in reply to kafka)
kafka

 

Posts: 12
Joined: 5/9/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 12:22:09   
an Imported Access Databse.

(in reply to yb2)
yb2

 

Posts: 653
Joined: 1/30/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 13:28:54   
Ok, a couple of things come to mind.

Firstly, stop using Access. I know you can use dotNet to connect to it, but that's not the point. DotNet is optimized for SQL Server, you can get SQL Server free either as MSDE or Express, and it will work faster and better. It's a bit like pimping your ride with a huge sound system, when your wheels are a bicycle.

Did you write this code, or was it taken from somewhere else? I don't see any obvious flaws in it, and since you say the problem is intermitent and it all started after you added a search facility, I'd say it was all down the the strain that Access is being put under - which leads back again to the SQL Server thing.

I think it's more likely that (pick any or all of below)

a) the SQL statements being fed to the database are not optimized - the BuildSearchQuery method begins with a SQL statement of "Select *" for a start, and it's likely you run several of the same queries over and over but I don't see much more stored, you could use conditional statements to select parts of common queries to stick together.

b) You're using Access so you don't get
i) caching of repeatedly used queries
ii) Access isn't really a database, it's a reporting tool, hence the lack of performance.

c) There aren't enough of or the right indexes in place to quicken up the search queries.

d) The size of the datasets being stored in the IIS memory are too large - datasets and datagrids are really only for intranets, not internet. If you are running a public website then forget about datagrids and datasets and think instead about OleDb/SqlDataReaders and html with hyperlinks. If it is an intranet then you might want to make this into a distibuted application that runs on the user's computer, then they will bear the burden of the dataset.

This isn't to do with page inheritance, and I don't think it's because of open connections not being closed because the data adapter will automatically close it.

That's just my guess. Here is a useful article on .Net performance that gives some good pointers.
http://msdn.microsoft.com/msdnmag/issues/05/01/ASPNETPerformance/

_____________________________

it is natural for people not to see one's own faults, and to exaggerate other people's faults and failings.
Currently listening to: L'Enfer Des Formes by Stereolab

(in reply to kafka)
kafka

 

Posts: 12
Joined: 5/9/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 14:18:57   
OK. I am looking into this option. Thanks for the reply. What is the learning curve on this type of database (SQL)? I did not write that code (though I altered it), it is standard Front Page 2003 Wizard. Damn it Jim, I'm a Pianist not a coder! Seriously though, I need to get somewhere pretty fast on this project and yes, in every JOB i've ever had that used an Access database, it always seemed so quirky, jenky, and moody, like a colicky baby... so if i can do this then GREAT!

(in reply to yb2)
yb2

 

Posts: 653
Joined: 1/30/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 14:25:44   
Access 2003 has an upsizing wizard (in the Data menu?) that you can use to push it all onto SQL Server. You don't need to change anything, but you should check it over as the wizard is just a wizard after all.

you can find everything here that you'll need to know about the SQL Server Express edition
http://www.microsoft.com/sql/editions/express/default.mspx


Your app will connect in a very similar way, but replace OleDb with Sql classes. Do you have a copy of Visual Studio too?

_____________________________

it is natural for people not to see one's own faults, and to exaggerate other people's faults and failings.
Currently listening to: L'Enfer Des Formes by Stereolab

(in reply to kafka)
kafka

 

Posts: 12
Joined: 5/9/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 15:02:35   
Hmm. I'll have to check with the Boss on Monday regarding Visual Studio. As far as the Express version of VS I see there are a few different ones, for C# J# etc etc. What would you say I need?

(in reply to yb2)
yb2

 

Posts: 653
Joined: 1/30/2006
Status: offline

 
RE: Two Forms in conflict? - 5/19/2006 15:49:06   
You'd be using VB.Net, but you can't use the VS Express with the FP code as the FP code is version 1.1 and VS Express only does version 2.0

You don't have to use Visual Studio, it just makes some things easier. There may be some free dev tools out there for .Net but I don't know them.

_____________________________

it is natural for people not to see one's own faults, and to exaggerate other people's faults and failings.
Currently listening to: L'Enfer Des Formes by Stereolab

(in reply to kafka)
Page:   [1]

All Forums >> Web Development >> ASP and Database >> Two Forms in conflict?
Page: [1]
Jump to: 1





New Messages No New Messages
Hot Topic w/ New Messages Hot Topic w/o New Messages
Locked w/ New Messages Locked w/o New Messages
 Post New Thread
 Reply to Message
 Post New Poll
 Submit Vote
 Delete My Own Post
 Delete My Own Thread
 Rate Posts