Имя "sb" не существует в текущем контексте - периодически возникающая ошибка .net, не полученная от С#C#

Место общения программистов C#
Ответить
Anonymous
 Имя "sb" не существует в текущем контексте - периодически возникающая ошибка .net, не полученная от С#

Сообщение Anonymous »

У меня есть файл .net, который использует C# для обработки некоторой информации формы (публикации), ее анализа, выполнения вычислений и создания строки для печати на экране и отправки по электронной почте.
Я получаю следующую ошибку, однако она появляется только в разное время. Страница будет работать в течение часа (или другого случайного промежутка времени), а затем не будет работать в течение определенного периода времени.

Из моего файла .aspx.

Сообщение об ошибке компилятора: CS0103: имя «sb» не существует в текущем контексте

Код: Выделить всё

Line 86:        

Вот макет кода. Я включаю, хотя и не думаю
есть проблема с кодом, потому что иногда он работает, а
иногда нет. Как будто у кого-то просто произошел провал в мозгу. Я искал файлы для удаления и ничего не нашел. Это моя первая попытка работы с C#. Мы используем его у меня на работе, и я довольно часто видел код, но не пробовал играть с ним самостоятельно.


*начало Grade_the_quiz.aspx*
конец заголовка/начало макета сайта (удалено для простоты)

Код: Выделить всё

How do you Compare?
Compare yourself to your competition - how do you measure up against the best practices benchmark of the most successful Senior Living Caregivers in America?*






(и т. д., конец html, #EOF удален для простоты)

начало automail.aspx .cs

Код: Выделить всё

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Net;
using System.Text;

public partial class formsucker : System.Web.UI.Page
{

public void Page_Init(object sender, EventArgs e)
{
string reTake = "", answerScore = "", pleaseWork = "", firstname = "", email = "";
int noAnswer = 0, testVal = 0;

String sdData = Request["sd"];

string[] sdValuesSplit = sdData.Split('~');
foreach (string postValues in sdValuesSplit)
{
if (postValues.Contains("FirstName"))
{
firstname = postValues.Split('=')[1];

}
if (postValues.Contains("EMail"))
{
email = postValues.Split('=')[1];

}

}

StringBuilder sb = new StringBuilder();

sb.Append("
Below are your results to the quiz " + firstname + ", and we will email them to " + email + " right away!
");

switch (Request["CUSTOM_FORM_FIELD_11111"])
{
case "Yes":
sb.Append("
Do you have a system to track your notes, history and activity?[/b]

[*][i]YES[/i]

 Congratulations!  You are ahead of many!  You understand the value in capturing your prospects/clients critical information.  Capturing information about their history, notes and activity allows information to be shared amongst your team.  You are utilizing a power piece of the puzzle when it comes to keeping up to date with your prospects/clients
");[b]                   testVal = testVal + 5;
break;
case "No":
sb.Append("
Do you have a system to track your notes, history and activity?[/b]

[*][i]NO[/i] Consider how much time and money it cost to find new leads -- not keeping track of this information can lead to your prospects or clients falling through the cracks.   Marketing to your prospect/client does not work if you don't know what the last activity 
");[b]                   break;
default:
sb.Append("
Do you have a system to track your notes, history and activity?[/b]

[*][i]You Didn\'t Answer the Question[/i]
");
noAnswer = noAnswer + 1;
break;
}
Больше операторов Switch, которые добавляются к sb (удалено около 20 операторов Switch.. он оценивает тест, а затем возвращает разные операторы и добавляя их в sb.

Код: Выделить всё

  StreamWriter sw = new StreamWriter(@"C:\inetpub\websites\occupancyadvantage.com\mailTest.txt", true);
try
{

System.Net.Mail.MailMessage automail = new System.Net.Mail.MailMessage();
automail.Subject = "How Do You Compare Quiz Results";
automail.To.Add(email);
MailAddress address = new MailAddress("XXXXXXXREMOVED", "XXXXXXREMOVED");
automail.From = address;
automail.IsBodyHtml = true;
automail.Body = "
" + sb + "

XXXXXREMOVED
" +
"This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. This message contains confidential information and is intended only for the individual named. If you are not the named addressee you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately by e-mail if you have received this e-mail by mistake and delete this e-mail from your system. If you are not the intended recipient you are notified that disclosing, copying, distributing or taking any action in reliance on the contents of this information is strictly prohibited." +
"
XXXXXREMOVED Notifications | 2012";
SmtpClient autosmtp = new SmtpClient("XXXXXREMOVED", 25);
NetworkCredential netCred = new NetworkCredential("XXXXXREMOVED", "XXXXXREMOVED");
autosmtp.Credentials = netCred;
autosmtp.Send(automail);

//SmtpMail.SmtpServer = "mail.XXXXXREMOVED.net";
//SmtpMail.Send(automail);

sw.WriteLine("Success:" + DateTime.Now.ToString());
sw.Close();
sw.Dispose();

}
catch (Exception x)
{
sw.WriteLine("Failure:" + DateTime.Now.ToString());
sw.WriteLine(x.ToString() + ":" + x.StackTrace.ToString());
sw.Close();
sw.Dispose();
}

}
}
Если вы зашли так далеко, надеюсь, я разместил самую важную информацию. Я просмотрел около 20 из них и нашел разные способы, которыми это происходит, просто не могу найти свое решение. Я создал все в блокноте ++ Исходный сайт со всем происходящим был в VS.

Подробнее здесь: https://stackoverflow.com/questions/114 ... t-error-no
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»