Inserting/Updatable XML - asp.net

I have now working updatable news using xml, but whenever i refresh the 1st Page which is the Inserting/Updating Page it's still posting even if i emptied the textboxes.
Code of 1st HTML/ASPX File:
(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmlfile = new XmlDocument();
xmlfile.Load(Server.MapPath("~/TestXML.xml"));
//create element
XmlElement theNewsTag = xmlfile.CreateElement("news");
XmlElement theTitleTag = xmlfile.CreateElement("title");
XmlElement theContentsTag = xmlfile.CreateElement("contents");
//create text node
XmlText theTitleText = xmlfile.CreateTextNode(xmlTitle.Text);
XmlText theContentsText = xmlfile.CreateTextNode(xmlContent.Text);
//append
theTitleTag.AppendChild(theTitleText);
theContentsTag.AppendChild(theContentsText);
theNewsTag.AppendChild(theTitleTag);
theNewsTag.AppendChild(theContentsTag);
//save
xmlfile.DocumentElement.AppendChild(theNewsTag);
xmlfile.Save(Server.MapPath("~/TestXML.xml"));
xmlTitle.Text = "";
xmlContent.Text = "";
Response.Redirect(Server.MapPath("~/Main.aspx"));
}
}
My 1st HTML/ASPX File (For inserting/Updating)
<h2>Title</h2>
<asp:TextBox ID="xmlTitle" runat="server"/>
<h2>Content</h2>
<asp:TextBox ID="xmlContent" runat="server"/>
<h2>Insert XML</h2>
<asp:Button ID="Button1" runat="server" Text="Post News"
onclick="Button1_Click" />
My 2nd HTML/ASPX File (For Viewing the XML File)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="xmlpath.aspx.cs" Inherits="xmlpath" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="ListView1" runat="server" DataSourceID="newDS">
<LayoutTemplate>
<div id="ItemPlaceHolderContainer"></div>
<span id="ItemPlaceHolder" runat="server"></span>
</LayoutTemplate>
<ItemTemplate>
<h2><%#XPath("title") %></h2>
<p><%#XPath("contents") %></p>
</ItemTemplate>
</asp:ListView>
<asp:XmlDataSource ID="newDS" runat="server" DataFile="~/TestXML.xml">
</asp:XmlDataSource>
</div>
</form>
</body>
</html>

When you refresh your page it reposts the data, It also show you a dialog box
Confirm Form Resubmission so actually you are pressing the button again.
In your page load create this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["Key"] = "1";
}
}
and check the session before button click
protected void button_Click(object sender, EventArgs e)
{
if (Session["Key"].ToString() == "1")
{
XmlDocument xmlfile = new XmlDocument();
xmlfile.Load(Server.MapPath("~/TestXML.xml"));
//create element
XmlElement theNewsTag = xmlfile.CreateElement("news");
XmlElement theTitleTag = xmlfile.CreateElement("title");
XmlElement theContentsTag = xmlfile.CreateElement("contents");
//create text node
XmlText theTitleText = xmlfile.CreateTextNode(xmlTitle.Text);
XmlText theContentsText = xmlfile.CreateTextNode(xmlContent.Text);
//append
theTitleTag.AppendChild(theTitleText);
theContentsTag.AppendChild(theContentsText);
theNewsTag.AppendChild(theTitleTag);
theNewsTag.AppendChild(theContentsTag);
//save
xmlfile.DocumentElement.AppendChild(theNewsTag);
xmlfile.Save(Server.MapPath("~/TestXML.xml"));
xmlTitle.Text = "";
xmlContent.Text = "";
Response.Redirect(Server.MapPath("~/Main.aspx"));
Session["Key"] = "0"; // set key = 0
}
}

Related

My ASP.NET login page showing 'TextBox' must be placed inside a form tag with runat=server

Here is the following complete code
1) is the master page aspx
2) is the webform page aspx
3) is the webform C# file
The complete details as i suppose
now this ASP:content is already a form and also when i am adding form tag it is showing the page can have only form tage .Please can anyone help ?
Master page
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="eliblogin" runat="server" Text="Login"></asp:Label>
</form>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</body>
</html>
masterpage.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
Page.LoadComplete += new EventHandler(set_button);
}
protected void eliblogout_Click(object sender, EventArgs e)
{
var user = Context.User.Identity;
//authentication manager
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
//logout
authenticationManager.SignOut();
Response.Redirect("~/Index.aspx");
}
private void set_button(Object sender,EventArgs e)
{
var user = Context.User.Identity;
if (user.Name!=null && user.IsAuthenticated)
{
try
{
//Username.Text = user.Name;
eliblogin.Visible = true;
eliblogin.Text = "yes man you did it";
// eliblogout.Visible = true;
}
catch (Exception ex)
{
//Username.Text = ex.ToString();
}
}
else
{
// Username.Text = "Hello Guest";
eliblogin.Visible = true;
// eliblogout.Visible = false;
}
}
}
Login.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Pages_Account_Login" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label ID="liStatus" runat="server"></asp:Label>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="username"></asp:Label><br />
<br />
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Password"></asp:Label><br />
<br />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"> </asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Login" OnClick="Button1_Click" />
</asp:Content>
login.aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
public partial class Pages_Account_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
//User Store
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["elibraryConnectionString"].ConnectionString;
//User Manager
UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
//Create a new User
var user = manager.Find(txtUsername.Text,txtPassword.Text);
if (user!=null)
{
try
{
//Create user Object
//Database will be created Automatically
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
var userIdentity = manager.CreateIdentity(user,DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent=false
},userIdentity);
}
catch (Exception ex)
{
liStatus.Text = ex.ToString();
}
}
else
{
liStatus.Text = "invalid username or password";
}
}
catch (Exception ex)
{
liStatus.Text = ex.ToString();
}
}
}
You should move
<form id="form1" runat="server">
<asp:Label ID="eliblogin" runat="server" Text="Login"></asp:Label>
</form>
from master page to login.aspx page and place all asp content of login page into this form tag.

Inconsistent behaviour for captcha

One of my forms has a captcha.
I am forced to use this captcha since there's a lot of code already written before me.
This way is simple:
There is an ashx file. An image will be created using that file. At the same time, that file will create a session with the same value from the image.
Upon submission, the code will check whether they are the same. If so, continue. if not, return.
Upon page refresh, the captcha will update.
Then I need to add in ajax update panel as the requirement.
Then the captcha is still working fine in chrome and safari but it is not refreshing when the page loads again in IE and firefox.
I created a simple page just for captcha
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs" Inherits="Default7" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<img height="30" alt="" src="Handler.ashx" width="80"><br>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
<div>
</div>
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default7 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
}
}
handler.ashx
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
public class Handler : IHttpHandler,System.Web.SessionState.IRequiresSessionState {
public void ProcessRequest(HttpContext context)
{
Bitmap objBMP = new System.Drawing.Bitmap(60, 20);
Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
//objGraphics.Clear(Color.Blue);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//' Configure font to use for text
Font objFont = new Font("Arial", 8, FontStyle.Bold);
string randomStr = "";
int[] myIntArray = new int[5];
int x;
//That is to create the random # and add it to our string
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9));
randomStr += (myIntArray[x].ToString());
}
randomStr = GetRandomString();
//This is to add the string to session cookie, to be compared later
context.Session.Add("randomStr", randomStr);
//' Write out the text
objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
//' Set the content type and return the image
context.Response.ContentType = "image/GIF";
objBMP.Save(context.Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
public bool IsReusable
{
get
{
return false;
}
}
private string GetRandomString()
{
string[] arrStr = "A,B,C,D,1,2,3,4,5,6,7,8,9,0".Split(",".ToCharArray());
string strDraw = string.Empty;
Random r = new Random();
for (int i = 0; i < 5; i++)
{
strDraw += arrStr[r.Next(0, arrStr.Length - 1)];
}
return strDraw;
}
}
Any idea?
I got the answer now.
change image control to server control.
and in code behind change the image source with current date time
<img height="30" alt="" src="/Handler.ashx" width="80" runat="server" id="imgCaptcha">
imgCaptcha.Src = "Handler.ashx?dt=" + DateTime.Now.ToString();
change image control to server control.
and in code behind change the image source with current date time
<img height="30" alt="" src="/Handler.ashx" width="80" runat="server" id="imgCaptcha">
imgCaptcha.Src = "Handler.ashx?dt=" + DateTime.Now.ToString();

how to retrieve TextBox control's ClientID within the ListView's ItemDataBound event?

I am having trouble retrieving a TextBox control's ClientID value from a ListView control.
I thought this syntax would return me the ClientID fine(very strange):
((TextBox)e.Item.FindControl("amount")).ClientID;
but it keeps throwing this exception:
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
Any help is greatly appreciated.
Below is my code:
aspx:
<asp:ListView ID="categories" runat="server"
ClientIDRowSuffix="ID"
ItemPlaceholderID="categoryItem"
DataKeyNames="ID" onitemdatabound="categories_ItemDataBound">
<ItemTemplate>
<div class="category">
<asp:TextBox ID="amount" runat="server" />
</div>
</ItemTemplate>
</asp:ListView>
codebehind:
public string AmountTextBoxClientID { get; set; }
protected string GetAmountTextBoxClientID()
{
return this.AmountTextBoxClientID;
}
protected void categories_ItemDataBound(object sender, ListViewItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListViewItemType.DataItem:
TextBox amountTextBox = (TextBox)e.Item.FindControl("amount");//this line excutes without any error
amountTextBox.Text = categoryAmount.ToString("C");
amountTextBox.Attributes.Add("readonly", "readonly");
this.AmountTextBoxClientID = amountTextBox.ClientID; //this line keeps throwing the OutOfRange exception
break;
}
}
Im afraid I cant pinpoint your problem but i drew up a page based on what you've given and pasted it below. It does NOT error.
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public string AmountTextBoxClientID { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("column1");
DataRow dr = dt.NewRow();
dr[0] = "some data";
dt.Rows.Add(dr);
ListView1.DataSource = dt;
ListView1.DataBind();
}
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
TextBox tbAmount = (TextBox)e.Item.FindControl("amount");
this.AmountTextBoxClientID = tbAmount.ClientID;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="ListView1" runat="server" onitemdatabound="ListView1_ItemDataBound">
<ItemTemplate>
<asp:TextBox ID="amount" runat="server" />
</ItemTemplate>
</asp:ListView>
</div>
</form>
</body>
</html>

changing themes with buttons, how?

I have 2 themes that i want to use on site, and they are settled in Themes Folder-> theme1 and theme2 , in theme1 and theme2 i have one .css file.
So how will I connect these .css files to two buttons and when i click on button1 i want to theme1.css activates and for theme2.
If you need more informations about problem ask.
thanks
In the Page_PreInit or before insert the code
{
this.Theme = "myTheme"
}
I have created a sample application in asp.net check out this,and let me know if there is some doubt.
Updated
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ProfilePage.aspx.cs" Inherits="ProfilePage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="test" Text="Stackoverflow" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Theme1" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Theme2" OnClick="Button2_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ProfilePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreInit(object sender, EventArgs e)
{
switch (Request.QueryString["theme"])
{
case "Blue":
Page.Theme = "Blue";
break;
case "Red":
Page.Theme = "Red";
break;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("ProfilePage.aspx?theme=Red");
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("ProfilePage.aspx?theme=Blue");
}
}

How do I bind an ASP.net ajax AccordionPane to an XMLDatasource?

I've got an angry boss that will beat me down if I waste another day on this :-P Many karma points to the ajax guru who can solve my dilemma.
But more detail: I want to have an AccordionPane that grabs a bunch of links from an XML source and populate itself from said source.
There might be a sexier way, but this works. Populate your data source however you wish. This was just for demo purposes. Ditto for PrettyTitle() Key is to remember there are two item types in the accordion.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Accordion Binding</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="AjaxScriptManager" runat="server">
</asp:ScriptManager>
<div>
<cc1:Accordion ID="AccordionControl" runat="server"
onitemdatabound="AccordionControl_ItemDataBound">
<Panes></Panes>
<HeaderTemplate>
<asp:Label ID="HeaderLabel" runat="server" />
</HeaderTemplate>
<ContentTemplate>
<asp:Literal ID="ContentLiteral" runat="server" />
<asp:HyperLink ID="ContentLink" runat="server" />
</ContentTemplate>
</cc1:Accordion><asp:xmldatasource runat="server" ID="RockNUGTwitter" ></asp:xmldatasource>
</div>
</form>
</body>
</html>
And codebehind is :
Using System;
using System.Web.UI.WebControls;
using System.Xml;
namespace Ajaxy
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Fill();
}
private void Fill()
{
PopulateDataSource();
AccordionControl.DataSource = RockNUGTwitter.GetXmlDocument().SelectNodes("//item");
AccordionControl.DataBind();
}
private void PopulateDataSource()
{
XmlDocument RockNugTwitterRSSDocument = new XmlDocument();
RockNugTwitterRSSDocument.Load("http://twitter.com/statuses/user_timeline/15912811.rss");
RockNUGTwitter.Data = RockNugTwitterRSSDocument.OuterXml;
}
protected void AccordionControl_ItemDataBound(object sender, AjaxControlToolkit.AccordionItemEventArgs e)
{
XmlNode ItemNode = (XmlNode)e.AccordionItem.DataItem;
if(e.AccordionItem.ItemType == AjaxControlToolkit.AccordionItemType.Content)
{
HyperLink ContentLink = (HyperLink)e.AccordionItem.FindControl("ContentLink");
ContentLink.NavigateUrl = ItemNode.SelectSingleNode("link").InnerText;
Literal ContentLiteral = (Literal)e.AccordionItem.FindControl("ContentLiteral");
ContentLiteral.Text = ItemNode.SelectSingleNode("title").InnerText;
ContentLink.Text = "Link";
}
else if(e.AccordionItem.ItemType == AjaxControlToolkit.AccordionItemType.Header)
{
Label HeaderLabel = (Label) e.AccordionItem.FindControl("HeaderLabel");
HeaderLabel.Text = PrettyTitle(ItemNode.SelectSingleNode("title").InnerText);
}
}
private string PrettyTitle(string FullItem)
{
string PrettyString = FullItem.Replace("RockNUG: ", "");
string[] Words = PrettyString.Split(' ');
const int MAX_WORDS_TOSHOW = 4;
int WordsToShow = MAX_WORDS_TOSHOW;
if(Words.Length < MAX_WORDS_TOSHOW)
{
WordsToShow = Words.Length;
}
PrettyString = String.Join(" ", Words, 0, WordsToShow);
if (Words.Length > WordsToShow)
{
PrettyString += "...";
}
return PrettyString;
}
}
}

Resources