Disabled button refreshes - c#

I Have an aspx page that contains 2 buttons "Update" and "Default". I have a dropdown list which contains a few values, say 1 to 10. When I click on Default button, the dropdown is set to a default value, say 4. If I wish to set the dropdown value to 3, I choose 3 and click on Update button and the changes are saved somewhere, maybe a DB.
Initially, Update button is disabled. Only if any changes are made to the dropdown, the Update button is enabled. Assuming that the Update button is initially disabled, I click the Default button to set the dropdown to its initial value. When I do that, a postback happens during which the Update button suddenly becomes enabled and then disabled. How do I avoid this? During page refresh, I don't want the disabled Update button to become enabled and then disabled. ALl this happens in a millisecond but its still visible.
is there any way out of this?
Design code is as follows:
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="LogSettings.aspx.cs" Inherits="Settings_LogSettings" %>
<!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 id="Head1" runat="server">
<title>Diagnostic Server Configuration Tool</title>
<link rel="stylesheet" type="text/css" href="../css/style001.css" />
<style type="text/css">
a.info
{
position: relative; /*this is the key*/
z-index: 24; /*background-color:#ccc;*/
color: #000;
border-width: 0px;
border-style: none;
text-decoration: none;
}
a.info:hover
{
z-index: 25;
background-color: #ff0;
}
a.info span
{
display: none;
}
a.info:hover span
{
/*the span will display just on :hover state*/
display: block;
position: absolute;
bottom: 2em;
right: 2em;
width: 15em;
border: 1px solid #0cf;
background-color: #cff;
color: #000;
text-align: left;
padding: 5px;
}
</style>
<script language="javascript" type="text/javascript">
function setDefaults() {
if (document.getElementById("dlLoggingLevel").value != document.getElementById("dlLoggingLevel_Def").value) {
document.getElementById("dlLoggingLevel").value = document.getElementById("dlLoggingLevel_Def").value;
document.getElementById("imgLoggingLevel").src = "../images/field_ok.png";
document.getElementById("imgLoggingLevelUndo").style.display = "inline";
document.getElementById("btnUpdate").disabled = false;
}
if (document.getElementById("txtMaxFileSize").value != document.getElementById("txtMaxFileSize_Def").value) {
document.getElementById("txtMaxFileSize").value = document.getElementById("txtMaxFileSize_Def").value;
document.getElementById("imgMaxSize").src = "../images/field_ok.png";
document.getElementById("imgMaxSizeUndo").style.display = "inline";
document.getElementById("btnUpdate").disabled = false;
}
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
<script language="javascript" type="text/javascript" src="../Css/wcf_validate.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<div class="divEditHeader" id="EditHeader">
<h1>
Logging Configuration
</h1>
<table width="100%">
<tr>
<td align="left">
<asp:Button CssClass="formEditBtn" runat="server" ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click"
Enabled="false" />
<button class="formEditBtn" onclick="javascript:setDefaults();" causesvalidation="false">
Default</button>
</td>
<td align="right">
</td>
</tr>
</table>
</div>
<br />
<table class="InputTable">
<tr class="Prompt">
<td class="Prompt">
Logging Level
</td>
<td>
<asp:DropDownList runat="server" ID="dlLoggingLevel">
<asp:ListItem Text="NONE" Value="none"></asp:ListItem>
<asp:ListItem Text="FATAL" Value="fatal"></asp:ListItem>
<asp:ListItem Text="ERROR" Value="error"></asp:ListItem>
<asp:ListItem Text="WARNING" Value="warning"></asp:ListItem>
<asp:ListItem Text="INFO" Value="info"></asp:ListItem>
<asp:ListItem Text="DEBUGLOW" Value="debuglow"></asp:ListItem>
<asp:ListItem Text="DEBUGMEDIUM" Value="debugmedium"></asp:ListItem>
<asp:ListItem Text="DEBUGHIGH" Value="debughigh"></asp:ListItem>
<asp:ListItem Text="DEBUGALL" Value="debugall"></asp:ListItem>
</asp:DropDownList>
<img id="imgLoggingLevel" src="../images/blank.png" />
<asp:TextBox runat="server" ID="dlLoggingLevel_Init" Style="display: none"></asp:TextBox>
<asp:TextBox runat="server" ID="dlLoggingLevel_Def" Style="display: none"></asp:TextBox>
<img id="imgLoggingLevelUndo" src="../images/restore.png" style="display: none; cursor: hand"
onmouseover="this.src='../Images/restore_hov.png'" onmouseout="this.src='../Images/restore.png'"
onclick="restoreValue('dlLoggingLevel','dlLoggingLevel_Init','imgLoggingLevel','imgLoggingLevelUndo')" />
</td>
<td>
<a href="javascript: void 0" class="info">
<img src="../images/help.png" border="0">
<span><font size="2">Enter the desired level of diagnostic data logging. Default: INFO.
</font></span></a>
</td>
</tr>
<tr class="Prompt">
<td class="Prompt">
Maximum Log File Size(MB)
</td>
<td>
<asp:TextBox runat="server" ID="txtMaxFileSize" Width="36px" MaxLength="3"></asp:TextBox>
<asp:TextBox runat="server" ID="txtMaxFileSize_Init" Style="display: none"></asp:TextBox>
<asp:TextBox runat="server" ID="txtMaxFileSize_Def" Style="display: none"></asp:TextBox>
<img id="imgMaxSize" src="../images/blank.png" />
<asp:CustomValidator runat="server" ID="valMaxSize" ControlToValidate="txtMaxFileSize"
Display="Dynamic" ErrorMessage="" ClientValidationFunction="MaxSize_Validate"></asp:CustomValidator>
<img id="imgMaxSizeUndo" src="../images/restore.png" style="display: none; cursor: hand"
onmouseover="this.src='../images/restore_hov.png'" onmouseout="this.src='../images/restore.png'"
onclick="restoreValue('txtMaxFileSize','txtMaxFileSize_Init','imgMaxSize','imgMaxSizeUndo')" />
</td>
<td>
<a href="javascript: void 0" class="info">
<img src="../images/help.png" border="0">
<span><font size="2">Enter the maximum log file size in MB. Default: 2 MB. Range: 1
- 100 MB. </font></span></a>
</td>
</tr>
</table>
<br />
<asp:Label runat="server" ID="lblMessage" Font-Bold="true"></asp:Label>
<br />
</div>
</form>
</body>
</html>
Code-Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DiagnosticCommon;
using System.Drawing;
public partial class Settings_LogSettings : System.Web.UI.Page
{
const string EnvVariable = "DIAGNOSTICSERVER";
const string ConfigFileName = "DiagnosticService.exe.config";
protected void Page_Load(object sender, EventArgs e)
{
if (Security.EnforceSecurity())
Response.Redirect("Login.aspx");
if (!IsPostBack)
{
DebugHelper.MaxDebugLevel = DebugHelper.Parse(ConfigReader.GetValue("LoggingLevel"));
DebugHelper.MaxLogFileSize = long.Parse(ConfigReader.GetValue("LogFileSize"));
txtMaxFileSize.Attributes.Add("onchange", "javascript:MaxSize_Validate('',this);");
txtMaxFileSize.Attributes.Add("onkeypress", "return isNumberKey(event)");
dlLoggingLevel.Attributes.Add("onchange", "javascript:Logging_Validate('',this);");
BindData();
BindInitData();
BindDefaults();
}
}
private void BindData()
{
string installPath = Environment.GetEnvironmentVariable(EnvVariable);
try
{
dlLoggingLevel.SelectedValue = ConfigReader.GetValue("LoggingLevel");
txtMaxFileSize.Text = ConfigReader.GetValue("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text += ex.Message + "<br>" + installPath;
lblMessage.ForeColor = Color.Red;
}
}
private void BindInitData()
{
string installPath = Environment.GetEnvironmentVariable(EnvVariable);
try
{
dlLoggingLevel_Init.Text = ConfigReader.GetValue("LoggingLevel");
txtMaxFileSize_Init.Text = ConfigReader.GetValue("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text += ex.Message + "<br>" + installPath;
lblMessage.ForeColor = Color.Red;
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
try
{
lblMessage.Text = "";
ConfigReader.SetValue("LoggingLevel", dlLoggingLevel.SelectedValue);
ConfigReader.SetValue("LogFileSize", txtMaxFileSize.Text);
lblMessage.Text = "Configuration updated.";
lblMessage.ForeColor = Color.Green;
btnUpdate.Enabled = false;
BindInitData();
}
catch (Exception ex)
{
lblMessage.Text += ex.Message;
lblMessage.ForeColor = Color.Red;
}
}
private void BindDefaults()
{
try
{
dlLoggingLevel_Def.Text = ConfigReader.GetDefault("LoggingLevel");
txtMaxFileSize_Def.Text = ConfigReader.GetDefault("LogFileSize");
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
lblMessage.ForeColor = Color.Red;
btnUpdate.Enabled = false;
}
}
}

Since the button has no type defined, the default type is used which is a submit button.
This means that when you click the Default button, the JS code is running but then the form is submitted.
To avoid the submission simply make the button be ordinary button:
<button type="button" class="formEditBtn" onclick="javascript:setDefaults();" causesvalidation="false">Default</button>

Following is the line in setDefaults() method that enables the update button for a while, a post back occurs and update button again disabled.
document.getElementById("btnUpdate").disabled = false;
Either comment this line or set it to true

Related

ASP.NET passing a function return value from a modalpopupextender to the main form

I have looked at a number of solutions to my basic issue, but have not found any solution that I either understand or that would work.
I have a page that takes in two items of information, filename and a store. The user then clicks on a button to execute a function that will update a database and send back a resulting string that I want to display on a textbox on the main form.
However, when they press the button I call a modalpopupextender using an UpdatePanel panel. That gets a value into the modalpopup. If the user validates that the correct store is selected they click an 'okay' button which then call the dbprocessing function that returns a result. The page is small so I'll give the complete aspx and c# code.
The function doProcess() returns a List of values which I convert to String for display. I left the session variables in for that was my last attempt at trying to get this to work.
Where I am confused is that when the first button on the main form (Process) is clicked, there is a postback which obviously hits the page load before the button click. That is when I display the popup. Then when the user clicks on the button Okay, another postback is perform hitting page load before the button click and in that second button I originally tried to set the textbox on the main page because there is no other action after the second click, but no data displayed.
What is strange, if I repeat the process, when I click to display the popup, my data displays. This is not making sense.
This is the aspx page
<%# Page Title="Product Rank Loader" Language="C#" MasterPageFile="~/OMnested.master" AutoEventWireup="true" CodeBehind="ProductRankLoader.aspx.cs" Inherits="OrderManager.ProductRankLoader" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="Scripts/local.js"></script>
<script type="text/javascript">
function callme(thisone)
{
$("#ddlStores").prop('disabled', false);
}
</script>
<div>
<table style="width: 500px">
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:FileUpload ID="fulRanks" runat="server" Width="315px" />
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlStores" runat="server" Height="16px" Width="155px">
<asp:ListItem Value="0">Select Store</asp:ListItem>
<asp:ListItem Value="10101">Parkseed</asp:ListItem>
<asp:ListItem Value="10151">Wayside</asp:ListItem>
<asp:ListItem Value="10201">Jackson (JP)</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td style="height: 20px; padding-top: 15px; padding-bottom: 15px; padding-left: 20px;">
<asp:Button ID="btnProcess" runat="server" Text="Process" Width="89px" OnClick="btnProcess_Click" />
</td>
</tr>
<tr>
<td>
**<asp:TextBox ID="txtResults" runat="server" Height="200px" ReadOnly="True" TextMode="MultiLine"></asp:TextBox>**
</td>
</tr>
</table>
<asp:HiddenField ID="hdnFilename" runat="server" />
</div>
<asp:UpdatePanel id="updVerifyChoice" runat="server">
<ContentTemplate>
<div style="display: none;">
<asp:Button ID="btnDummy" UseSubmitBehavior="true" OnClientClick="ShowModalPopup" OnClick="btnDummy_Click" runat="server" />
<%--Dummy Button added to assign the target controlid of PopupExtender--%>
<asp:Button ID="btnDummyButton" UseSubmitBehavior="true" runat="server" Text="DummyButton" Style="display: none;" />
</div>
<asp:Panel ID="pnlVerifyRequestPopup" runat="server">
<div style="background: #fff; padding-left: 3px; border: 1px solid #989898; border-top: 1px solid #989898 !important;">
<table style="background-color: #F7F5F4; width: 300px;">
<tr>
<td><label>Verify Process Request</label></td>
<td style="text-align: right;">
<label class="lbl_3">
<asp:LinkButton ID="lBtnVerifyRequestClose" CssClass="lnkCloseheaderedit" Text="Cancel"
runat="server" OnClick="lBtnBillUpdPopClose_Click" /></label>
</td>
</tr>
<tr>
<td style="width: 150px;" colspan="2">
<asp:Label ID="lblWarn" runat="server" Text="" Font-Size="Medium" ForeColor="#CC3300"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" class="align_right">
<asp:Button ID="btnPopVerify" runat="server" CssClass="order_searchbtn" Text="Okay"
OnClick="btnPopVerify_Click" />
</td>
</tr>
</table>
<asp:HiddenField ID="hdnReturnData" runat="server" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender ID="extVerifyProcess" runat="server" BehaviorID="extndPopBillUpdBehId"
TargetControlID="btnDummyButton" PopupControlID="pnlVerifyRequestPopup" CancelControlID="lBtnVerifyRequestClose">
</ajax:ModalPopupExtender>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
The field in question that should get the returned values from the function is called txtResults.
Here is the c# code (I cut out unneeded code)
namespace OrderManager
{
public partial class ProductRankLoader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var currentUser = Request.LogonUserIdentity.Name.Split('\\')[1];
// Session.Add("returnText", "");
var header = Master.FindControl("lblpageheading") as Label;
header.Text = "Product Rank Loader";
if (IsPostBack)
{
try
{
//if (Session["Verified"].ToString() != "")
//{
Session["returnText"] = doProcess();
if (Session["returnText"].ToString() != "")
{
txtResults.Text = Session["returnText"].ToString();
lblMessage.Text = "";
}
//}
}
catch { }
} else
{
Session.Add("returnText", "");
Session.Add("Verified", "");
}
}
protected void btnProcess_Click(object sender, EventArgs e)
{
Boolean fileOK = false;
string filename = Path.GetFileName(fulRanks.FileName);
hdnFilename.Value = filename;
if (fulRanks.HasFile)
{
ddlStores.Enabled = true;
String fileExtension =
System.IO.Path.GetExtension(fulRanks.FileName).ToLower();
String[] allowedExtensions = { ".txt", ".log" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOK = true;
fulRanks.SaveAs(#"c:\temp\" + filename);
}
}
}
if (!fileOK || ddlStores.SelectedIndex <= 0)
{
lblMessage.Text = "Either the file name is incorrect or a store has not been selected.";
return;
} else { }
lblWarn.Text = "You are going to update item Ranks for store <br />" + ddlStores.SelectedItem + ".<br /><br />Press 'Okay' to process";
Session.Add("Verified", "true");
extVerifyProcess.Show();
}
protected void lBtnBillUpdPopClose_Click(object sender, EventArgs e)
{
Session["Verified"] = "";
Session["returnText"] = "";
Response.Redirect("ProductRankLoader.aspx");
}
protected void btnPopVerify_Click(object sender, EventArgs e)
{
//Session["returnText"] = doProcess();
Session.Remove("returnText");
Session.Remove("Verified");
}
private string doProcess()
{
string tmpResults = "";
Int32 store = 0;
if (ddlStores.SelectedIndex > 0)
{
Int32.TryParse(ddlStores.SelectedValue.ToString(), out store);
string filename = hdnFilename.Value;
ProductRankLoaderDLL.ProductRankLoaderDLL newRanks = new ProductRankLoaderDLL.ProductRankLoaderDLL(xxx);
List<string> results = newRanks.ProcessRanks();
foreach (string result in results)
{
tmpResults += result + '\r';
}
// txtResults.Text = tmpResults;
lblMessage.Text = "";
}
else
{
lblMessage.Text = "";
}
return tmpResults;
}
protected void btnDummy_Click(object sender, EventArgs e)
{
}
}
}
If I don't misunderstand your request your problem is caused by the postbacks. I think you can handle better your logic with jquery. For example you can use jquery to close the popup without performing postback:
$('#lBtnVerifyRequestClose').click(function (event) {
event.preventDefault();
$('#pnlVerifyRequestPopup').dialog('close');
});
the event.preventDefault() ensure that postback are not executed.
If you need server logic to put data on your popup you can bind a jquery function to the dialog on open event and retrieve there data / perform your logic. In this way your form will be submitted to the server only once at the end of the process.

Ajax SlideShowExtender with variable Image Size

I have a working AjaxToolKit SlideShowExtender in my ASP.net C# website, using Visual Studio Community 2015. The displayed images have varying aspect ratios (width/height) so that most of them are distorted because Image Height and Width are fixed. I am looking for a way of displaying the images without distortion, and without having to edit each image manually before feeding it to the SlideShowExtender. For example, could the Height and Width properties of the Target Image Control be tweaked just before display? If it needs to be done in JavaScript, I would need code help as I have managed to do everything so far just on the server side, and I know very little JavaScript.
Code added upon request
Selected files follow. SlideShowExtender is defined in SlideShow.aspx.
TinyNPm.Master:
<%# Master Language="C#" AutoEventWireup="True" CodeBehind="TinyNPm.Master.cs" Inherits="TinyNP.TinyNPm" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>The TinyNP Project</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<style>
body {font-family:Arial; margin:0;}
.popup {
background-color: #ddd;
margin: 0px auto;
width: 330px;
position: relative;
border: Gray 2px inset;
}
.popup .content {
padding: 20px;
background-color: #ddd;
float: left;
}
.displayUnset{display:unset}
.displayNone {display:none}
a:link {background-color:antiquewhite;}
a:visited {background-color:antiquewhite;}
a:hover {background-color:burlywood;}
a:active {background-color:aqua;}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
li a.active {
background-color:brown;
color: burlywood;
}
li a:hover:not(.active) {
background-color:burlywood;
color: black;
}
table {
border: 0px solid grey; background-color:burlywood; height:auto; width:100%;}
tr {background-color:wheat}
th, td {
border: 0px solid grey;
border-radius: 0px;
font-family: Arial;
padding: 2px;
}
.GvGrid:hover { background-color:burlywood}
</style>
</head>
<body runat="server" id="Body1" style="height:100%">
<form id="form1" runat="server" >
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</div>
<div style="overflow-x:auto; height:100%">
<asp:Table Id="Table1" style="color:sienna; height:100%" runat="server">
<asp:TableRow >
<asp:TableCell ColumnSpan="3" HorizontalAlign="Right">
<%-- In the following CheckBox the 'Checked' attribute is coordinated with the value of NavCheckBoxChecked in Global.asax.cs --%>
<asp:CheckBox ID="NavCheckBox" runat="server" Checked="true"
Text="Nav box in left margin moves up and down when browser window height changes"
OnCheckedChanged="NavCheckBox_CheckedChanged"
AutoPostBack="true" Font-Size="X-Small" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell rowspan="3" style="vertical-align:top; width:110px">
<div style="text-align:center; color:sandybrown"> Site Navigation </div>
<ajaxToolkit:AlwaysVisibleControlExtender ID="AlwaysVisibleControlExtender1" runat="server" TargetControlID="Menu1"
VerticalSide="Middle" HorizontalSide="Left" Enabled="true"/>
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" Orientation="Vertical"
StaticDisplayLevels="4" Font-Size="Small" BorderColor="#dd7711" BorderStyle="Outset" ItemWrap="True"
OnMenuItemClick="Menu1_OnMenuItemClick" >
<DataBindings>
<asp:MenuItemBinding DataMember="SiteMapNode" TextField="Title" />
</DataBindings>
<StaticMenuItemStyle Height="20px" VerticalPadding="0px" Font-Bold="true" ForeColor="Brown"/>
<StaticSelectedStyle BackColor="Yellow"/>
<LevelMenuItemStyles>
<asp:MenuItemStyle Font-Size="Medium" />
<asp:MenuItemStyle Font-Size="Small" />
<asp:MenuItemStyle Font-Size="Smaller" ForeColor="#c25f1d" />
<asp:MenuItemStyle Font-Size="X-Small" ForeColor="#666666" />
<asp:MenuItemStyle Font-Size="X-Small" Forecolor="#808080"/>
</LevelMenuItemStyles>
</asp:Menu>
<br />
<br />
<div style="background-color:rgba(235, 251, 32, 0.64); color:sandybrown">Yellow highlight</div><div style="color:sandybrown"> indicates currently selected menu item</div>
<br />
<br />
<div style="text-align:center; color:sandybrown"> Site Navigation </div>
<br />
<br />
<div style="background-color:rgba(235, 251, 32, 0.64); color:sandybrown">Yellow highlight</div><div style="color:sandybrown"> indicates currently selected menu item</div>
<br />
<br />
<div style="text-align:center; color:sandybrown"> Site Navigation </div>
<br />
<br />
<div style="background-color:rgba(235, 251, 32, 0.64); color:sandybrown">Yellow highlight</div><div style="color:sandybrown"> indicates currently selected menu item</div>
<br />
<br />
<div style="text-align:center; color:sandybrown"> Site Navigation </div>
</asp:TableCell>
<asp:TableCell style="border-right:none" HorizontalAlign="Center" >
<asp:Label id="lblHeaderText" style="text-align:center; font-size:larger; font-weight:bold" runat="server" >
The TinyNP Project Common Header
</asp:Label>
<div style="text-align:center">
<asp:LoginView ID="LoginView1" runat="server" >
<AnonymousTemplate>
You are not logged in
</AnonymousTemplate>
<LoggedInTemplate>
Currently logged in user:&nbsp<asp:LoginName ID="LoginName1" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
⚊
<asp:LoginStatus ID="LoginStatus1" runat="server" LoginText="Log in" LogoutText="Log out" Font-Size="Medium" />
</div>
</asp:TableCell>
<asp:TableHeaderCell style="border-left:none">
<asp:Image ImageUrl="~/i/GenericLogo.jpg" AlternateText="Generic Logo" height="80" width="107" runat="server" />
</asp:TableHeaderCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell style="text-align:center" ColumnSpan="2">
<asp:ContentPlaceHolder ID="body" runat="server" >
</asp:ContentPlaceHolder>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell ColumnSpan="2" HorizontalAlign="Center">
<asp:Label ID="lblFooterText" style="text-align:center; font-weight:bold" runat="server" >
The TinyNP Project Common Footer
</asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</form>
</body>
</html>
TinyNPm.Master.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using AjaxControlToolkit;
namespace TinyNP
{
public partial class TinyNPm : System.Web.UI.MasterPage
{
public double tableWidth
{
get { return Table1.Width.Value; }
set { Table1.Width =new Unit(value,UnitType.Pixel); }
}
protected void Page_Load(object sender, EventArgs e)
{
Body1.Attributes.Add("bgcolor", "burlywood");
if (Global.igMasterPageEntryCount < 1)
{
lblHeaderText.Text = "The " + Global.sgcAppName + " Common Header";
lblFooterText.Text = "The " + Global.sgcAppName + " Common Footer";
NavCheckBox.Checked = Global.NavCheckBoxChecked;
AlwaysVisibleNavChb();
}
else
{
if (!IsPostBack)
{
NavCheckBox.Checked = Global.NavCheckBoxChecked;
AlwaysVisibleNavChb();
}
}
Global.igMasterPageEntryCount++;
}
protected void Menu1_OnMenuItemClick(object sender, MenuEventArgs e)
{
Redirect2detectscreen(e.Item.DataPath);
}
protected void Redirect2detectscreen(string suDataPath)
{
Session["ScreenResolution"] = null;
Global.sgCallingFrom = suDataPath;
Response.Redirect(Global.sgCallingFrom);
}
protected void NavCheckBox_CheckedChanged(object sender, EventArgs e)
{
AlwaysVisibleNavChb();
}
private void AlwaysVisibleNavChb()
{
AlwaysVisibleControlExtender1.Enabled = NavCheckBox.Checked;
Global.NavCheckBoxChecked = NavCheckBox.Checked;
}
}
}
Global.asax.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.SessionState;
using System.Drawing;
using System.IO;
namespace TinyNP
{
public class Global : System.Web.HttpApplication
{
public const string sgcAppName = "TinyNP Project";
private static string sCallingFrom = "~/Default.aspx";
public static string sgCallingFrom { get { return sCallingFrom; } set { sCallingFrom = value; } }
public static string sgHomeDir = "";
public static Boolean NavCheckBoxChecked = true;
public enum enumButtons { NoYes, OkOnly, OkCancel};
//Gallery Support
public static int[] aigPhotoSize = new int[5] { 250, 600, 1000, 1400, 1200 }; // in pixels
public static int igInitialCustomPhotoSize = aigPhotoSize[4];
public enum enumPhotoSizes { Smartphone, Laptop, SmallDesktop, LargeDesktop, Custom };
public static enumPhotoSizes egPhotoSizeIndex = enumPhotoSizes.Laptop;
public static int igSubGalleryEntryCount = 0;
public static Boolean bgCustomDivVisible = false;
public struct SgDynTab
{
public string sFolder; // Name of folder from column sFoldername in database table TNP_FOLDERS
public int iSelFolderIndex; // Index in Folder Dropdown pointing to selected folder
public int iSelMediaTypeIndex; // Index in Media Type Dropdown pointing to selectd media type
public int iSelMediaID; // ID in table dbo.TNP_MEDIADATA for the selected item in the active tab
public string sMediaType; // Name of Media Type from column sMediaType in database table TNP_MEDIATYPES
public override string ToString()
{
return "SgDynTab: sFolder=" + sFolder + ", iSelFolderIndex=" + iSelFolderIndex.ToString() +
", iSelMediaID =" + iSelMediaID.ToString() + ", sMediaType=" + sMediaType;
}
public SgDynTab(string suF, int iuSF, int iuSMT, int iuSMI, string suM)
{
this.sFolder = suF;
this.iSelFolderIndex = iuSF;
this.iSelMediaTypeIndex = iuSMT;
this.iSelMediaID = iuSMI;
this.sMediaType = suM;
}
}
public static SgDynTab SgDyTb = new SgDynTab("",0,0,0,"");
//Default Page support
public static int igMasterPageEntryCount = 0;
public static Size SizegInitWindow = new Size(600, 400);
//Logging
public static Boolean bgLogging = true;
public static StreamWriter wgLog;
public static void oLog(string logMessage)
{
if (bgLogging)
{
DateTime DNow = DateTime.Now;
wgLog.WriteLine(DNow.ToShortDateString() + " " + DNow.ToShortTimeString() + ":"
+ (100 + DNow.Second).ToString().Substring(1) + "."
+ (1000 + DNow.Millisecond).ToString().Substring(1) + "-" + logMessage);
wgLog.Flush();
}
}
protected void Application_Start(object sender, EventArgs e)
{
if (bgLogging)
{
string sPath = Server.MapPath("~") + "/App_Data/TinyNP.log";
wgLog = new StreamWriter(sPath, true);
oLog("******************** Logging started for " + sgcAppName + ", log file path=`" + sPath + "` ********************");
}
}
protected void Application_End(object sender, EventArgs e)
{
if (bgLogging)
{
oLog("******************** Logging ended for " + sgcAppName + " ********************");
wgLog.Close();
}
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// Handle HTTP errors
if (exc.GetType() == typeof(HttpException))
{
// The Complete Error Handling Example generates
// some errors using URLs with "NoCatch" in them;
// ignore these here to simulate what would happen
// if a global.asax handler were not implemented.
if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
return;
//Redirect HTTP errors to HttpError page
Server.Transfer("~/ErrorPages/CustomError.aspx");
return;
}
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>\n");
Response.Write("<p>" + exc.Message + "</p>\n");
Response.Write("Return to the <a href='~/Default.aspx'>" +
"Home Page</a>\n");
// Log the exception and notify system operators
ExceptionUtility.LogException(exc, "DefaultPage");
//ExceptionUtility.NotifySystemOps(exc);
// Clear the error from the server
Server.ClearError();
}
public sealed class ExceptionUtility
{
// All methods are static, so constructor can be private
private ExceptionUtility()
{ }
// Log an Exception
public static void LogException(Exception exc, string source)
{
if (exc.InnerException != null)
{
oLog("Inner Exception Type: ");
oLog(exc.InnerException.GetType().ToString());
oLog("Inner Exception: ");
oLog(exc.InnerException.Message);
oLog("Inner Source: ");
oLog(exc.InnerException.Source);
if (exc.InnerException.StackTrace != null)
{
oLog("Inner Stack Trace: ");
oLog(exc.InnerException.StackTrace);
}
}
oLog("Exception Type: ");
oLog(exc.GetType().ToString());
oLog("Exception: " + exc.Message);
oLog("Source: " + source);
oLog("Stack Trace: ");
if (exc.StackTrace != null)
{
oLog(exc.StackTrace);
oLog(" ");
}
}
// Notify System Operators about an exception
public static void NotifySystemOps(Exception exc)
{
// Include code for notifying IT system operators
}
}
}
}
SlideShow.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/TinyNPm.Master" AutoEventWireup="true" CodeBehind="SlideShow.aspx.cs" Inherits="TinyNP.Media.SlideShow" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="body" runat="server">
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" />
<asp:Table runat="server" BorderWidth="0" cellpadding="0" cellspacing="0">
<asp:TableRow>
<asp:TableCell>
<asp:Button ID="btnPrevious" runat="server" Text="<<" Font-Size="20" />
</asp:TableCell>
<asp:TableCell>
<asp:Image ID="Image1" runat="server" Height="300" Width="300" />
<ajaxToolkit:SlideShowExtender ID="SlideShowExtender1" runat="server" TargetControlID="Image1"
SlideShowServiceMethod="GetImages"
ImageTitleLabelID="lblImageTitle" ImageDescriptionLabelID="lblImageDescription"
AutoPlay="true" PlayInterval="1000" Loop="true" PlayButtonID="btnPlay" StopButtonText="Stop"
PlayButtonText="Play" NextButtonID="btnNext" PreviousButtonID="btnPrevious" >
</ajaxToolkit:SlideShowExtender>
</asp:TableCell>
<asp:TableCell>
<asp:Button ID="btnNext" runat="server" Text=">>" Font-Size="20" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell columnspan="3" HorizontalAlign="center">
<asp:Button ID="btnPlay" runat="server" Text="Play" Font-Size="20" />
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell columnspan="3" HorizontalAlign="center">
<br />
<b>Name:</b>
<asp:Label ID="lblImageTitle" runat="server" Text="Label" /><br />
<b>Description:</b>
<asp:Label ID="lblImageDescription" runat="server" Text="Label" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</asp:Content>
SlideShow.aspx.cs:
using System;
using System.IO;
using AjaxControlToolkit;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
namespace TinyNP.Media
{
public partial class SlideShow : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod]
public static AjaxControlToolkit.Slide[] GetImages()
{
Global.oLog("SlideShow.GetImages entry");
List<Slide> slides = new List<Slide>();
string path = HttpContext.Current.Server.MapPath("~/i/AjaxSlideShow/");
if (path.EndsWith("\\"))
{
path = path.Remove(path.Length - 1);
}
Uri pathUri = new Uri(path, UriKind.Absolute);
string[] files = Directory.GetFiles(path);
foreach (string file in files)
{
Uri filePathUri = new Uri(file, UriKind.Absolute);
Slide slyde =
new Slide {
Name = Path.GetFileNameWithoutExtension(file),
Description = Path.GetFileNameWithoutExtension(file) + " Description.",
ImagePath = "../i/" + pathUri.MakeRelativeUri(filePathUri).ToString()
};
slides.Add(slyde);
Global.oLog("".PadLeft(8) + "Name=" + slyde.Name);
Global.oLog("".PadLeft(12) + "Description=" + slyde.Description);
Global.oLog("".PadLeft(12) + "ImagePath=" + slyde.ImagePath);
}
Global.oLog("SlideShow.GetImages exit (" + slides.Count.ToString() + " slides)");
return slides.ToArray();
}
protected void Page_Load(object sender, EventArgs e)
{
Global.oLog("SlideShow.Page_Load entry");
Global.oLog("SlideShow.Page_Load exit");
}
}
}
The solution is incredibly simple: Simply remove the Height attribute of asp:Image ID="Image1" in file SlideShow.aspx. The image's aspect ratio will be preserved automatically. Alternatively, one could keep the Height attribute and remove the Width attribute. I could kick myself for not running into this earlier.

multi-tab/panel control does not always respond correctly

I have tabs that open and close panels. Multiple tabs/panels can be open at a time. Followed is my current solution:
protected static int[] tabControls = { 0, 0 };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
storyPanel.Visible = true;
hoursPanel.Visible = false;
}
}
/* ===== TAB CONTROLS ===== */
protected void Tab1_Click(object sender, EventArgs e)
{
if (tabControls[0] == 1)
{
storyPanel.Visible = true;
Tab1.CssClass = "Clicked";
tabControls[0] = 0;
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#storyPostBack';", true);
}
else
{
storyPanel.Visible = false;
Tab1.CssClass = "Initial";
tabControls[0] = 1;
}
}
protected void Tab2_Click(object sender, EventArgs e)
{
if (tabControls[1] == 1)
{
hoursPanel.Visible = true;
Tab2.CssClass = "Clicked";
tabControls[1] = 0;
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#hoursPostBack';", true);
}
else
{
hoursPanel.Visible = false;
Tab2.CssClass = "Initial";
tabControls[1] = 1;
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#storyPostBack';", true);
}
}
Sometimes the tab needs to be pressed twice for it to respond and open the panel as well as receive the css changes to itself. I cant figure out why. Additionally, is there a better approach.
EDIT:
It's actually not tabs, sorry for not being clear. It's the illusion of tabs using buttons/panels/css:
Server controls:
<table width="80%" align="center">
<tr>
<td>
<asp:Button Text="Tab 1" BorderStyle="None" ID="Tab1" CssClass="Initial" runat="server"
OnClick="Tab1_Click" />
<asp:Button Text="Tab 2" BorderStyle="None" ID="Tab2" CssClass="Initial" runat="server"
OnClick="Tab2_Click" />
<asp:Panel ID="storyPanel" runat="server">
<table style="width: 100%; border-width: 1px; border-color: #666; border-style: solid">
<tr>
<td>
<h3>
<span>tab content here </span>
</h3>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel ID="hoursPanel" runat="server">
<table style="width: 100%; border-width: 1px; border-color: #666; border-style: solid">
<tr>
<td>
<h3>
tab 2 content here
</h3>
</td>
</tr>
</table>
</asp:Panel>
</table>
It looks to me like the initial state of all tabs is visible:
protected static int[] tabControls = { 0, 0 };
But in fact, only one tab would actually be visible right? Or are all the panels supposed to be visible at the same time? If your tabControls variable is out of sync with the actual visibility of the panels, it may require clicking twice. Once to change the tabControls to invisible, and then one to change it back to visible again. To fix, just do:
protected static int[] tabControls = { 0, 1 };

Button not changing the Label on Clicking

I have this Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Calendar1.SelectedDate = DateTime.Today;
info.Visible = false;
meeting.Visible = true;
member.Visible = true;
label.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
DateTime Now = DateTime.Today;
DateTime wed1 = getFirstWednesdayOfMonth(Now);
DateTime wed3 = getThirdWednesdayOfMonth(Now);
if (Now < wed1)
{
Label5.Text = "The next meeting is on" + "\n" + wed1.ToShortDateString() + "\nat 7 pm in room S242";
}
else if (Now < wed3)
{
Label5.Text = "The next meeting is on" + "\n" + wed3.ToShortDateString() + "\nat 7 pm in room S242";
}
}
protected DateTime getFirstWednesdayOfMonth(DateTime seedDate)
{
DateTime wed1 = new DateTime(seedDate.Year, seedDate.Month, 1);
while (wed1.DayOfWeek != DayOfWeek.Wednesday)
{
wed1 = wed1.AddDays(1);
}
return wed1;
}
protected DateTime getThirdWednesdayOfMonth(DateTime seedDate)
{
DateTime wed3 = new DateTime(seedDate.Year, seedDate.Month, 15);
while (wed3.DayOfWeek != DayOfWeek.Wednesday)
{
wed3 = wed3.AddDays(1);
}
return wed3;
}
protected void btnInfo_Click(object sender, EventArgs e)
{
btnInfo.Visible = false;
info.Visible = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
if (validateFirst.IsValid && validateLast.IsValid && validatePhone.IsValid && validateEmail.IsValid)
{
lblThanks.Text = "Thanks! you will contacted in 2 business days!";
info.Visible = false;
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedValue == "analyst")
{
}
}
}
and Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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 id="Head1" runat="server">
<title></title>
<style type="text/css">
.heading
{
text-align: center;
border-style: double;
background-color:#F2A988;
font-family:Sans-Serif;
font-weight:bold;
}
#wrapper {
margin: 0 auto;
width: 400px;
text-align:left;
}
.style1
{
text-align: center;
font-family:Sans-Serif;
}
.style2
{
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body style="height: 642px; width: 911px; " id="wrapper">
<form id="form1" runat="server">
<div class="heading">
ABC Computer Club - Inquiry Form</div>
<br />
<asp:Calendar ID="Calendar1" runat="server" Font-Names="Arial"></asp:Calendar>
<br />
<asp:Label ID="lblThanks" runat="server"
style="font-family: Arial, Helvetica, sans-serif; font-weight: 700"></asp:Label>
<br />
<br />
<asp:Button ID="btnInfo" runat="server" Font-Names="Arial"
style="font-weight: 700"
Text="I'd like to receive more information!" Width="261px"
onclick="btnInfo_Click" />
<div runat="server" id="info"
style="position:relative; top: -1px; left: 7px; width: 463px; height: 415px;">
<span class="style2">If you would like to join the club or receive more
information about the club, fill in the form below and click the submit button.</span><br />
<br />
<asp:Label ID="Label1" runat="server"
style="font-weight: 700; font-family: Arial, Helvetica, sans-serif"
Text="First Name:"></asp:Label>
<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label2" runat="server"
style="font-weight: 700; font-family: Arial, Helvetica, sans-serif"
Text="Last Name:"></asp:Label>
<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label3" runat="server"
style="font-weight: 700; font-family: Arial, Helvetica, sans-serif"
Text="Phone #:"></asp:Label>
<asp:TextBox ID="txtPhone" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label4" runat="server"
style="font-weight: 700; font-family: Arial, Helvetica, sans-serif"
Text="Email:"></asp:Label>
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Submit" />
<br />
<br />
<asp:RequiredFieldValidator ID="validateFirst" runat="server"
ControlToValidate="txtFName" ErrorMessage="First Name is Required"
style="font-family: Arial, Helvetica, sans-serif"></asp:RequiredFieldValidator>
<br />
<br />
<asp:RequiredFieldValidator ID="validateLast" runat="server"
ControlToValidate="txtLName" ErrorMessage="Last Name is Required"
style="font-family: Arial, Helvetica, sans-serif"></asp:RequiredFieldValidator>
<br />
<br />
<asp:RegularExpressionValidator ID="validatePhone" runat="server"
ControlToValidate="txtPhone" ErrorMessage="Phone Number is invalid"
style="font-family: Arial, Helvetica, sans-serif"
ValidationExpression="^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$"></asp:RegularExpressionValidator>
<br />
<br />
<asp:RegularExpressionValidator ID="validateEmail" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Invalid Email"
style="font-family: Arial, Helvetica, sans-serif"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
</div>
<div runat="server" id="meeting"
style="position:absolute; top: 150px; left: 580px; width: 232px; height: 64px; text-align: center; margin-top: 0px; font-family: Arial; font-weight:bold;">
<br />
<asp:Label ID="Label5" runat="server" Text="Test"></asp:Label>
<br />
</div>
<div runat="server" id="label" style="width: 308px; position:absolute; top: 45px; left: 550px; margin-top: 0px;"
class="style1">
Click Below to find out when
<br />
the club meets next</div>
<div runat="server" id="member"
style="position:absolute; top: 28px; left:880px; width: 274px; height: 441px; font-family:Sans-Serif;">
<b>View Members by Program:<br />
<asp:ListBox ID="ListBox1" runat="server" Height="175px" Width="213px"
onselectedindexchanged="ListBox1_SelectedIndexChanged">
<asp:ListItem Value="all">All</asp:ListItem>
<asp:ListItem Value="programmer">Computer Programmer</asp:ListItem>
<asp:ListItem Value="itss">Information Technologies Support Services</asp:ListItem>
<asp:ListItem Value="analyst">Systems Analyst</asp:ListItem>
</asp:ListBox>
<br />
<br />
</b></div>
<div style="position:absolute; top: 99px; left: 600px; width: 192px; text-align: center; margin-top: 0px;">
<asp:Button ID="Button3" runat="server" onclick="Button3_Click"
Text="Next Meeting" />
</div>
</form>
</body>
</html>
The problem is whenever I click "Next Meeting" nothing happens whereas it should set the label text to Next Available first or third wednesday of the month. It did worked before but since when I copied the whole code to a new website it is not working. What may be the problem?
That code has never worked correctly. Maybe it has worked seemingly before 18. Jul 2012 which was the third wednesday in this month, because then (Now < wed3) == true.
Now neither Now < wed1 nor Now < wed3 can be true which is the only way to change the label's text property.
if (Now < wed1)
{
Label5.Text = "The next meeting is on" + "\n" + wed1.ToShortDateString() + "\nat 7 pm in room S242";
}
else if (Now < wed3)
{
Label5.Text = "The next meeting is on" + "\n" + wed3.ToShortDateString() + "\nat 7 pm in room S242";
}
Maybe you need to tell us your real requirement. What should your program do?
You might also want to put the default settings in page_load in a if(!IsPostback) check, otherwise the Calendar.SelectedDate always is overwritten.
if(!Page.IsPostBack)
{
// not on postbacks, f.e. when the user selected a date
Calendar1.SelectedDate = DateTime.Today;
// ....
}
But one thing, if there's no First or Third Wednesday is available, it
should show the first wednesday of next month. Right?
That's the missing requirement i've asked for. Since the third wednesday is already in the past, you want to return the third wednesday of the nex month:
public static DateTime getNextWeekDay(DateTime date, DayOfWeek dayOfWeek, int weekNum)
{
if (weekNum < 1 || weekNum > 4)
throw new ArgumentException("Number of week must be between 1 and 4.", "weekNum");
int inWeekNum = date.Date.Day / 7;
if (inWeekNum >= weekNum)
{
var nextMonth = date.AddMonths(1);
date = new DateTime(nextMonth.Year, nextMonth.Month, 1);
}
DateTime currentDate = date;
int currentWeekNum = 0;
while (currentWeekNum < weekNum)
{
if (currentDate.DayOfWeek == dayOfWeek)
currentWeekNum++;
if (currentWeekNum == weekNum)
break;
else
currentDate = currentDate.AddDays(1);
}
return currentDate;
}
Yiou can use it this way:
DateTime wed1 = getNextWeekDay(Now, DayOfWeek.Wednesday, 1);
DateTime wed3 = getNextWeekDay(Now, DayOfWeek.Wednesday, 3);
You need a third case
DateTime getFirstWednesdayOfNextMonth(DateTime seedDate)
{
int year = seedDate.Year;
int month = seedDate.Month+1;
if (month > 12)
{
month = 1;
year = year + 1;
}
DateTime wed1 = new DateTime(year, month, 1);
while (wed1.DayOfWeek != DayOfWeek.Wednesday)
{
wed1 = wed1.AddDays(1);
}
return wed1;
}
and add an ending else to your Button3_Click
protected void Button3_Click(object sender, EventArgs e)
{
DateTime Now = DateTime.Today;
DateTime wed1 = getFirstWednesdayOfMonth(Now);
DateTime wed3 = getThirdWednesdayOfMonth(Now);
DateTime wedNext = getFirstWednesdayOfNextMonth(Now);
if (Now < wed1)
{
Label5.Text = "The next meeting is on" + "\n" + wed1.ToShortDateString() + "\nat 7 pm in room S242";
}
else if (Now < wed3)
{
Label5.Text = "The next meeting is on" + "\n" + wed3.ToShortDateString() + "\nat 7 pm in room S242";
}
else
{
Label5.Text = "The next meeting is on" + "\n" + wedNextMonth.ToShortDateString() + "\nat 7 pm in room S242";
}
}
By the way, when you know the first wednesday of the month, calculating the other two is simple a matter of adding 14 to the first one.
DateTime wed1 = getFirstWednesdayOfMonth(Now);
DateTime wed3 = wed.AddDays(14);
DateTime wedNext = wed3.AddDays(14);
// But it could be in the same month (1,8,15,22,29)
if(wedNext.Month == wed3.Month)
wedNext = wedNext.AddDays(7);

Address bar is showing the address of previous page

I am having Default.aspx Page for Login. After Successful Login it shows the ItemValuation.aspx Page but in the address bar the link shown is Default.aspx. The problem started after I implimented the jquery in my Project. If I remove the jquery
references and Code then link shown is correct after login i.e. ItemValuation.aspx
Can any one tell me how can I solve this Problem? After successful Login on Default.aspx the link shown in address bar should be ItemValuation.aspx For your reference I am posting the Default Page aspx code.
Thanks in Advance.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Item_Valuation.Default" %>
<!DOCTYPE html >
<html >
<head runat="server">
<link rel="shortcut icon" href="~/Images/ACME.ico">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0;"/>
<link href="css/jquery.mobile-1.1.0.min.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.8.18.custom_mini.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.1.0.min.js" type="text/javascript"></script>
</head>
<body >
<div data-role="page" id ="loginpage" data-theme="c" >
<form id="formLogin" runat="server" >
<div id ="DivHeader" data-role="header" data-position="fixed" data-theme="c" >
<div style="text-align:center;top:4px;">
<asp:Image ID="Image1" runat="server"
ImageUrl="Images/ItmVlun.jpg" />
</div>
</div>
<div data-role="content" style=" margin-top: 2px;">
<table style="text-align:right;width:100%">
<tr>
<td style="width:80%" >
<table style="border-color: #FFCC00;width:100%;left:5%; text-align:left;">
<tr>
<td style="width:50%;"><asp:Label ID="lblLogin" runat="server" Text="Login:"
Font-Bold="False" Font-Names="Copperplate Gothic Light" Font-Size="Large"></asp:Label>
</td>
<td style="width:50%;"><input id="txtUserName" type="text" runat="server" style="width:100%;font-size:large;" /></td>
<td><ASP:RequiredFieldValidator ControlToValidate="txtUserName"
Display="Static" ErrorMessage="*" runat="server"
ID="vUserName" /></td>
</tr>
<tr>
<td >
<asp:Label ID="lblPassword" runat="server" Text="Password:" Font-Bold="False"
Font-Names="Copperplate Gothic Light" Font-Size="Large"></asp:Label>
</td>
<td ><input id="txtUserPass" type="password" runat="server" style="width:100%;font-size:large;" /></td>
</tr>
<tr>
<td >
<asp:Label ID="lblRememberMe" runat="server" Text="Remember Me:"
Visible="False" Font-Names="Copperplate Gothic Light"></asp:Label>
</td>
<td >
<asp:CheckBox ID="chkPersistCookie" runat="server" autopostback="false"
Visible="False" />
</td>
<td ></td>
</tr>
</table>
</td>
<td style="width:20%;">
<asp:Image ImageAlign=Right ID="Image2" runat="server"
ImageUrl="~/Images/LogInimg.jpg" Width="100%" Height=60% />
</td>
</tr>
</table>
</div>
<div data-role="footer" data-position="fixed" data-theme="c">
<asp:Button ID="btnLogIn" runat="server" OnClick="LogMe_Click"
Text="Log in" data-theme="a" CausesValidation="False" data-role="button" data-inline="true" style=" float : left;" />
<input type="button" ID="CloseButton" value="Close" onclick ="window.close();" />
<asp:Label ID="lblMsg" runat="server" ForeColor="#FF0066" style=" float : Right;" ></asp:Label>
</div>
</form>
</div>
</body>
</html>
//Default.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
//using System.Web.UI.MobileControls;
using System.Runtime.InteropServices;
namespace Item_Valuation
{
public partial class Default : System.Web.UI.Page
{
// internal static extern int lineGetGeneralInfo(IntPtr hLine, byte[] bCache);
//public static string IMEI;
Item_Valuation.User usr;
public static string message="";
public string AuthorisationMsg;
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
if (Request.QueryString["TCPServer"] != null)
{
AuthorisationMsg = Request.QueryString["TCPServer"].ToString();
GlobalData.SetSettings();
lblMsg.Text = "Error: TCP Server IP " + GlobalData.TCPServer + " " + AuthorisationMsg;
}
else if (Request.QueryString["Message"] != null)
{
lblMsg.Text = Request.QueryString["Message"].ToString();
}
}
txtUserName.Focus();
}
catch (Exception ee)
{
lblMsg.Text = ee.Message;
}
}
private bool ValidateUser(string userName, string passWord)
{
if ((null == userName) || (0 == userName.Length))
{
return false;
}
try
{
string msg = "";
Item_Valuation.User Usr = Item_Valuation.User.CheckLogin(userName, passWord, ref msg);
if (msg.Length > 0)
{
lblMsg.Text = msg;
Response.Write("<script>'alert("+lblMsg.Text +"')</script>");
return false;
}
if (Usr != null)
{
}
else
{
lblMsg.Text = "Invalid Login id or Password";
Response.Write("<script>'alert(" + lblMsg.Text + "')</script>");
return false;
}
}
catch (Exception ex)
{
// AcmePayRollBusiness.PayRollError.PostError(this.GetType(), ex, "Error while validating User");
return false;
}
return true;
}
public void LogMe_Click(object sender, EventArgs e)
{
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);
string strRedirect=null;
//strRedirect = Request["ReturnUrl"];
usr = (Item_Valuation.User)HttpContext.Current.Session["User"];
int roleLevel = usr.RoleLevel;
if (roleLevel != 1)
{
if (strRedirect == null)
strRedirect = "ItemValuation.aspx";
}
else
{
if (strRedirect == null)
strRedirect ="PrinterAssignment.aspx";
}
Response.Redirect(strRedirect);
//Server.Transfer(strRedirect);
}
}
}
}
jQuery Mobile is the one that's doing that. By default, it changes all links and form submissions through AJAX.
To disable this... interesting... functionality, you need to add a handler to the mobileinit event, and set ajaxEnabled to false.
Docs here on how exactly to do this: http://jquerymobile.com/demos/1.1.0/docs/api/globalconfig.html

Categories