Display Code Error - asp.net

When I try to view the source code by using asp.net, I got this error.
Access to the path 'C:\Users\user\Desktop\Website1' is denied.
Anyone idea how to fix this?
The display code is as follow. I do not know how to fix this.
<%# Page Language="C#" runat="server" Debug="true" %>
<%# Import Namespace="System.IO" %>
<script language="C#" runat="server">
void Page_Load()
{
string filePath =
Server.MapPath(Request.QueryString["filename"]);
FileName.Text = Request.QueryString["filename"];
FileInfo file = new FileInfo(filePath);
if (file.Extension != ".mdb"
&& file.Extension != ".xml"
&& file.Extension != ".exe")
{
Code.Text = ReadFile(filePath);
}
else
{
Code.Text = "Sorry you can't read a file with an extension of " + file.Extension;
}
}
private string ReadFile(string filepath)
{
string fileOutput = "";
try
{
StreamReader FileReader = new StreamReader(filepath);
//The returned value is -1 if no more characters are
//currently available.
while (FileReader.Peek() > -1)
{
//ReadLine() Reads a line of characters from the
//current stream and returns the data as a string.
fileOutput += FileReader.ReadLine().Replace("<", "<").
Replace(" ", " ")
+ "<br />";
}
FileReader.Close();
}
catch (FileNotFoundException e)
{
fileOutput = e.Message;
}
return fileOutput;
}
</script>
<html>
<head>
<title>code</title>
<link rel="stylesheet" href="style1.css" type="text/css">
</head>
<body>
<h1 class="pageHeader">Source Code</h1>
<asp:label id="FileName"
CssClass="codeheader" Runat="server"/>
<asp:Panel id="pnlCode" CssClass="code"
runat="server" Width="80%">
<asp:label id="Code" Runat="server" />
</asp:Panel>
</body>
</html>

right click on your Website1, click on properties , goto security , click on edit and then add network service and see if it solves your problem.

Related

PageLoad not working as expected in asp.Net Framework

I have seen many posts on this but I still cannot find out why my code is still doing this.
I have 1 aspx page with 2 buttons on. In the pageload I check if it is the first time it loads using (!IsPostBack) and set a few variables I then go on to use in this page.
For some reason that I cannot explain this was working as expected and perfectly, but all of a sudden this section of the code is now being hit every time the page reloads after a button click. Meaning the variables are being newed up again and again and I lose the data every button click now, which is not what I want.
Here is the web form
<!DOCTYPE html>
<%-- --%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="BrowserTalking.js"></script>
<link href="LandingPage.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="#"/>
<title>Home Page</title>
</head>
<body onload="speaking();">
<form id="form1" runat="server" class="wholeScreenDiv">
<div class="mainColumn">
<asp:Label ID="questionLabel" runat="server" CssClass="questionText"></asp:Label>
<div class="answerRow">
<asp:Button ID="Button1" runat="server" Text="Yes" CssClass="myButton1" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="No" CssClass="myButton2" OnClick="Button2_Click" />
</div>
</div>
<asp:HiddenField runat="server" ID="questionNumber" />
<asp:HiddenField runat="server" ID="SpeechSynthNeeded" />
</form>
</body>
</html>
The JavaScript Method called onload is just using a speech synthesis API and again this was the same before when it was working perfectly.
function speaking() {
var questionNum = document.getElementById("questionNumber").value;
var actualQuestion = "";
var utterance = new SpeechSynthesisUtterance();
utterance.rate = 0.7;
if (document.getElementById("SpeechSynthNeeded").value == "1") {
if (questionNum == 0) {
actualQuestion = 'Can you read and understand this text clearly';
} else if (questionNum == 1) {
actualQuestion = 'Would you still like the information spoken to you?';
} else if (questionNum == 2) {
actualQuestion = "Do you suffer from Aphasia?";
} else if (questionNum == 3) {
actualQuestion = "Do you suffer from Hemianopia";
} else if (questionNum == 4) {
actualQuestion = "Would you like to setup an account?";
}
utterance.text = actualQuestion;
speechSynthesis.speak(utterance);
}
}
and the code behind looks like this
public partial class WebForm1 : System.Web.UI.Page
{
public ApplicationQuestion _Question;
public ApplicationUser _User;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Do all of this on the first time this page lods
{
_User = new ApplicationUser();
_Question = new ApplicationQuestion();
questionLabel.Text = _Question.GenerateQuestion(0);
Session["Question"] = _Question;
Session["User"] = _User;
questionNumber.Value = "0";
SpeechSynthNeeded.Value = "1";
}
else // Do all within this else every time a question is answered
{
_Question = (ApplicationQuestion)Session["Question"];
_User = (ApplicationUser)Session["User"];
if (int.TryParse(questionNumber.Value, out int number))
{
number++;
questionNumber.Value = number.ToString();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(int.TryParse(questionNumber.Value, out int number))
{
//Generate Next Question
questionLabel.Text = _Question.GenerateQuestion(number);
}
// Add 1 to the questions results list meaning the user answered Yes
_User._QuestionResults.Add(1);
if (int.TryParse(questionNumber.Value, out int number2))
{
// if it is on the first question and they answer yes then set SpeechSynthe Value to 0 so it isnt used in javascript for next question
if (number2 == 1)
{
SpeechSynthNeeded.Value = "0";
}
// if it is on the second question and they answer yes then set SpeechSynthe Value will be set back to 1 so its reactivated
if (number2 == 2)
{
SpeechSynthNeeded.Value = "1";
}
// After Final question redirect to User login page
if (number2 == 5)
{
Response.Redirect("UserLogin.aspx?synthNeeded=" + SpeechSynthNeeded.Value);
}
}
}
When debugging through the issue I get now is when I first click the button it goes into the pageLoad and goes into the Else (Which is what i want), but then the button click method is called and once this is finished it comes back into the page load and goes into the first part of the If/Else, and therefore sets up all the variables again and I lose the data I need.
I don't know if this is something tiny I have changed or I have just lost my mind from looking at it too long, but all Im trying to do is set up an object in the page load, then every button click I add a value to that object and then use that value later down the line. I am putting this object in the session to pull it back down when I need it.
Can anyone tell me why Im hitting the "First" page load again and again even with the use of (!IsPostBack) even after a button click?
Solved,
One of the weirdest and most annoying things that has happened to me yet.
The removal of the line from the aspx page stopped the double page loading and now it works as normal.
Thanks to https://forums.asp.net/t/1004939.aspx?Page_Load+called+twice+ I found someone else had solved the issue from playing around with src="" image tags.
I had added this for a speech recognition API and did not consider this to be making this happen and I still don't know why it does.

Calling the DirectMethod by passing the String Values as parameters in ConfirmMessage Box Handler

I am trying to pass the string values to Direct Method by using the following code.
<html>
<head runat="server">
<script runat="server">
protected void btnSubmit_DirectClick(object sender, Ext.Net.DirectEventArgs e)
{
string Name = "Lewis Bland";
string Address = "Las Angels";
X.Msg.Confirm("Confirmation", "Do you want to submit the Details", new MessageBoxButtonsConfig
{
Yes = new MessageBoxButtonConfig
{
Handler = "#{DirectMethods}.fnSaveNameAndAdress(" + Name + "," + Address + ")",
Text = "Yes"
},
No = new MessageBoxButtonConfig
{
Text = "No"
}
}).Show();
}
[DirectMethod(Namespace = "TestAlias")]
public void fnSaveNameAndAdress(string Name, string Address)
{
X.Msg.Alert("Conformed", "Name and Address Submitted Successfully").Show();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ext:ResourceManager runat="server" ID="resource" SourceFormatting="true" />
<ext:Button ID="btnSubmit" runat="server" Text="Submit" OnDirectClick="btnSubmit_DirectClick" />
</form>
</body>
</html>
The above code working fine with out any parameters but when i pass
string parameters it didn't fire the Method. To fire this method i
have used "Alias" Concept by reading the posts by adding the following
lines
[DirectMethod(Namespace = "TestAlias")]
and In CodeBehind i have added the the following line above the
Class.
[DirectMethodProxyID(IDMode = DirectMethodProxyIDMode.Alias, Alias = "TestAlias")]
Even though i added these, it does fired any Event. How to overcome
this scenario.
Thank you.
Yes = new MessageBoxButtonConfig
{
Handler = "#{DirectMethods}.fnSaveNameAndAdress(" + Name + "," + Address + ")",
Text = "Yes"
inside your code handler should be like this I guess,
Handler = "TestAlias.fnSaveNameAndAdress(" + Name + "," + Address + ")",

Need to reference Usercontrol(ascx) in ASPX page in more than one place with different results

Scenario :
Default.aspx is as below.
<%# Page MasterPageFile="~/StandardLayout.master" Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register src= "~/Controls/Us.ascx" tagname="AboutUs" tagprefix="site" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<div id="large">
<site:AboutUs ID="AboutUsControl" runat="server" />
</div>
<div id="small">
<site:AboutUs ID="AboutUsControl" runat="server" />
</div>
</asp:Content>
AboutUs.ascx.cs assigns some value to a label control. In the above scenario, I want to re-use AboutUs within "div id=small" as the logic is same but only value change.
My question is within AboutUs.ascx.cs, I need some way to find out if it belongs within "", assign Label1 = "I am here". Otherwise Label1 = "I am everywhere"
I am trying to pass parameters but do I need to anything in the code-behind in default.aspx.cs? or any other suggestions.
Please suggest.
Make sure both user controls have unique ID's. I'll use AboutUsControl1 and AboutUsControl2. Declare a name property for your user control:
private string _doWhat;
public string doWhat
{
get { return _doWhat; }
set { _doWhat = value; }
}
//Execute the check somewhere in your code to set the text you want.
private void Do_Something()
{
if (_doWhat == "Large")
{
//display "I am here"
}
else
{
//display "I am everywhere"
}
}
And in the code behind on the page using the user controls, just pass the value by calling the public variable:
AboutUsControl1.doWhat = "Large";
AboutUsControl2.doWhat = "Small";
or just set doWhat in the control itself:
<site:AboutUs ID="AboutUsControl1" runat="server" doWhat="Large" />
<site:AboutUs ID="AboutUsControl2" runat="server" doWhat="Small" />

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control

I am getting the following error
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
but all I am trying to do is inside a ASP.NET REPEATER Control
<% if ( Eval("Message").ToString() == HttpContext.Current.Profile.UserName) %>
<% { %>
<asp:ImageButton runat="server" etc.... />
<% } %>
The syntax is
<%# Eval("...") %>
You could do something like
<asp:ImageButton Visible='<%# ShowImg(Eval(Container.DataItem,"Message")) %>' />
and in your codebehind:
boolean ShowImg(string msg)
{
return (msg == HttpContext.Current.Profile.UserName);
}
An alternative is this:
<asp:ImageButton runat="server" Visible='<%# Eval("Message").ToString() == HttpContext.Current.Profile.UserName %>' />
Then there is no need for code behind.
Its too late but i would like to answer it in my way, what i used to achieve it:
<%# Eval("Message").toString()== HttpContext.Current.Profile.UserName)?"<asp:ImageButton runat="server" etc.... />" :""%>
Now this will only show image button if Message is equal to username.
This might help any one else in same situation.
In my situation i needed to check null and empty string...so i implemented like this below:
<%# Eval("DateString")!= null && Eval("DateString")!= ""? "<span class='date'>"+Eval("DateString") + "</span>":"" %>
Thanks
Another way to implement it:
public string nonImage() {
string imgTag = "", Article_OwnerID = "", Article_ID = "", Article_OwnerType = "", imgSrc = "";
DataTable DtArticles = SE_Article.GetArticlesList(UserID, UserID, ProfileType, CounterOfPage, CountPerPage, (short) SE_Action.OwnerType.user, SE_Security.CheckInjection(TxtSearch.Text.Trim()), CategoryID, "all_articles", DrpOrderBy.SelectedValue, DrpSort.SelectedValue);
if (DtArticles != null && DtArticles.Rows.Count > 0) {
Article_OwnerID = DtArticles.Rows[0]["Article_OwnerID"].ToString();
Article_ID = DtArticles.Rows[0]["Article_ID"].ToString();
Article_OwnerType = DtArticles.Rows[0]["Article_OwnerType"].ToString();
}
if (SE_Article.GetArticleCover(Convert.ToInt32(Article_OwnerID), Convert.ToInt32(Article_ID), Convert.ToInt16(Article_OwnerType)) != System.Configuration.ConfigurationManager.AppSettings["NoPhotoArticleThumb"]) {
imgSrc = SE_Article.GetArticleCover(Convert.ToInt32(Article_OwnerID), Convert.ToInt32(Article_ID), Convert.ToInt16(Article_OwnerType));
imgTag = "<img class='img_article_cover' src='" + imgSrc + "' alt='مقاله" + Article_ID + "' />";
}
return imgTag;
}
<% nonImage(); %>

need to get the context value in top of page, where the context value will be set only at the bottom of the page?

<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Page Load:");
}
public string setContext(string sName, string sVal)
{
HttpContext.Current.Items[sName] = sVal;
return sVal;
}
public string getContext(string sName)
{
string sVal = "default";
if (HttpContext.Current.Items[sName] != null)
sVal = HttpContext.Current.Items[sName].ToString();
else
sVal = "empty";
return sVal;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Context in TOP ???</title>
</head>
<body>
<div>
<div id="divDest" name="divDest">
Top Content:
Get1 :<%= getContext("topcontent") %> // returns "empty", BUT I Need "value to set"
</div>
<br />
Set1 : <%= setContext("topcontent", "value to set")%> <br /> // set the value
<br />
Get2 : <%= getContext("topcontent") %><br /> // returns "value to set"
<br />
<script language="javascript">
var elval = getElementVal("divTest");
document.getElementById("divDest").innerHTML = elval;
//alert(elval);
function getElementVal(elemid) {
var elemval = document.getElementById(elemid);
return elemval.innerHTML;
}
</script>
</body>
</html>
I need to get the context value in top of page,
where the context value will be set at the bottom of the page.
Get context value ==> "empty", BUT need "something"
Set context value to "something"
Get context value ==> "something"
I may use JS/AJAX, where the page source the value won't be present.
BUT I need the TEXT in the View Source of the page too.
Is there a way to wait for the context to set and then get,
I have tried with User Control, prerender and render methods too.
But I can't able to get it right.
Any idea?
Your code executes in the order that it appears.
Therefore, your getContext call is run before the call to setContext.
What are you trying to do?

Resources