Please help me with this error! Here ResultValue is an enumeration.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Answer.ResultValue'
Source Error:
Line 38: Answer a = (Answer)al[i];
Line 39:
Line 40: if (a.Result == Answer.ResultValue.Correct)
Line 41: correct=correct+1;
Line 42: }
=================================
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArrayList al = (ArrayList)Session["AnswerList"];
if (al == null)
{
Response.Redirect("History.aspx");
}
resultGrid.DataSource = al;
resultGrid.DataBind();
// Save the results into the database.
if (IsPostBack == false)
{
// Calculate score
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
correct=correct+1;
}
double score = (correct / questions) * 100;
SqlDataSource studentQuizDataSource = new SqlDataSource();
studentQuizDataSource.ConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
studentQuizDataSource.InsertCommand = "INSERT INTO UserQuiz ([QuizID],
[DateTimeComplete], [Score], [UserName]) VALUES (#QuizID, #DateTimeComplete,
#Score, #UserName)";
studentQuizDataSource.InsertParameters.Add("QuizID",
Session["QuizID"].ToString());
studentQuizDataSource.InsertParameters.Add("Score", score.ToString());
studentQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
studentQuizDataSource.InsertParameters.Add("DateTimeComplete",
DateTime.Now.ToString());
int rowsAffected = studentQuizDataSource.Insert();
if (rowsAffected == 0)
{
errorLabel.Text = "There was a problem saving your quiz results into our
database. Therefore, the results from this quiz will
not be displayed on the list on the main menu.";
}
}
}
protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
}
}
code for Answer.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 Answer : System.Web.UI.Page
{
private string m_QuestionID;
private string m_CorrectAnswer;
private string m_UserAns;
private string m_Result;
public string QuestionID
{
get
{
return m_QuestionID;
}
set
{
m_QuestionID = value;
}
}
public string CorrectAnswer
{
get
{
return m_CorrectAnswer;
}
set
{
m_CorrectAnswer = value;
}
}
public string UserAns
{
get
{
return m_UserAns;
}
set
{
m_UserAns = value;
}
}
public string Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return "Correct";
}
else
{
return "Incorrect";
}
}
}
public enum ResultValue
{
Correct,
Incorrect
}
}
It's pretty obvious you're trying to compare Enumeration Types with Strings, which aren't the same and can't be compared like that. Instead, I think you should try replacing this bit of code:
public string Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return "Correct";
}
else
{
return "Incorrect";
}
}
}
with
public ResultValue Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return ResultValue.Correct;
}
else
{
return ResultValue.Incorrect;
}
}
}
Try evaluating this :-
if (a.Result == Answer.ResultValue.Correct.ToString())
Related
ERROR:
System.FormatException: 'Input string was not in a correct format.'
I am having the user input into a form, but before it is accepted it must be validated (starting with IsFilledIn()). I have parsed the string from the textbox in the form to an int so it can go into the DB. It seems it is completely skipping validation when I hit submit but have included all that is need (I think).
Current code:
Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lab5_validation;
using System.Data.SqlClient;
namespace FinalAJG
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnsubmit_Click(object sender, EventArgs e)
{
Character temp = new Character();
//Sets temporary Variables
temp.CharName = txtCharName.Text;
temp.Health = Int32.Parse(txtHealth.Text);
temp.Lvl = Int32.Parse(txtLvl.Text);
temp.Agility = Int32.Parse(txtAgility.Text);
temp.Strength = Int32.Parse(txtStrength.Text);
temp.Stamina = Int32.Parse(txtStamina.Text);
temp.Armor = Int32.Parse(txtArmor.Text);
temp.HoursPlayed = Double.Parse(txtHoursPlayed.Text);
temp.PlayedSince = DateTime.Parse(txtPlayedSince.Text);
temp.Cass = txtClass.Text;
if (!temp.Feedback.Contains("ERROR:"))
{
Feedback.Text = temp.AddARecord();
}
else
{
Feedback.Text = temp.Feedback;
}
}
}
}
Character.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Lab5_validation;
namespace FinalAJG
{
class Character
{
//Define PRIVATE variables.
bool blnResult;
private string charname;
private string cass;
private int health;
private int lvl;
private int agility;
private int strength;
private int stamina;
private int armor;
private double hoursplayed;
private DateTime playedsince;
private float AvgPlayTime=777;
private int TotalPoints=444;
public string feedback = "";
// Creates Public variables the users can input to, then stores them to private variable if validated correctly.
public string CharName
{
get
{
//Returns private variable to class.
return charname;
}
set
{
//IF-ELSE statement to validate user input.
if (ValidationLibrary.IsItFilledIn(value))
{
// Sets private variable 'fName' to equal user input on public variable.
charname = value;
}
else
{
//If they enter invalid input, the feed back will be set to an error message, and the private variable will not be set.
feedback += "\n\nERROR: Enter your charcters name!!!";
}
}
}
//Public variable to receive user input securly.
public string Cass
{
get
{
//Returns Private variable
return cass;
}
set
{ //IF-ELSE statement to validate user input.
if (ValidationLibrary.IsItFilledIn(value))
{
cass = value; // Sets Private Variable
}
else
{//Feedback gives error IF validation
feedback += "\n\nERROR: Enter your Class!(ONLY OPTIONS ARE, Mage, Assassin, Warrior, Archer, Druid, and Warlock!!";
}
}
}
//Same as previous Public Variables
public int Health
{
get
{
return health;
}
set
{ //Checks for user input, if not true give error feedback.
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
health = value;
}
else
{
feedback += "\n\nERROR: Enter Characters Health (25-100)!! ";
}
}
}
//Same as previous Public Variables
public int Lvl
{
get
{
return lvl;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
lvl = value;
}
else
{
feedback += "\n\nERROR:Enter your Characters level! (1-80)\n ";
}
}
}
//Same as previous Public Variables, except it will not be required to fill it in.
public int Agility
{
get
{
return agility;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
agility = value;
}
else
{
feedback += "\n\nERROR:Enter valid Date!! (02-20-2020, 11/11/2011, 06/24/2019)";
}
}
}
//Same as previous Public Variables
public int Strength
{
get
{
return strength;
}
set
{
//Validates to ensure the required length of zipcode is entered
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
do
{
strength = value;
} while (blnResult == true);
}
else
{
feedback += "\n\nERROR:Enter Characters strength!! (1-25) ";
}
}
}
//Same as previous Public Variables
public int Stamina
{
get
{
return stamina;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
stamina = value;
}
}
}
//Same as previous Public Variables except the validation checks for valid characters and the correct length
public int Armor
{
get
{
return armor;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
armor = value;
}
else
{
feedback += "\n\nERROR:Enter Valid armor rating!! (10-50) ";
}
}
}
//Same as previous Public Variables
public double HoursPlayed
{
get
{
return hoursplayed;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
hoursplayed = value;
}
else
{
feedback += "\n\nERROR:Enter Valid Number!!(.5, 2.3, 6.4, 92)";
}
}
}
//Same as previous Public Variables except checks for required characters for a valid Email.
public DateTime PlayedSince
{
get
{
return playedsince;
}
set
{
if (ValidationLibrary.IsItFilledIn(value.ToString()))
{
playedsince = value;
}
else
{
feedback += "\n\nERROR:Enter valid Date!! (02-20-2020, 11/11/2011, 06/24/2019)";
}
}
}
// Feedback variable to display results or error message.
public string Feedback
{
get
{
return feedback;
}
set
{ // IF feedback contains 'ERROR' then leave it blank and display which input was incorrect
if (feedback.Contains("ERROR:"))
{
feedback += "";
}
//ELSE, store and display the results.
else
{
feedback = value;
}
}
}
public string AddARecord()
{
//Init string var
string strResult = "";
//Make a connection object
SqlConnection Conn = new SqlConnection();
//Initialize it's properties
Conn.ConnectionString = ********************";//Set the Who/What/Where of DB
//Sends command to SQL Server
string strSQL = "INSERT INTO Chars (CharName, Class, Health, Lvl, Agility, Strength, Stamina, Armor, HoursPlayed, PlayedSince, AvgPlayTime, TotalPoints) VALUES (#CharName, #Class, #Health, #Level, #Agility, #Strength, #Stamina, #Armor, #HoursPlayed, #PlayedSince, #AvgPlayTime, #TotalPoints)";
// Sends out Command
SqlCommand comm = new SqlCommand();
comm.CommandText = strSQL; //Commander knows what to say
comm.Connection = Conn; //Where's the phone? Here it is
// Adds all parameters.
comm.Parameters.AddWithValue("#CharName", CharName);
comm.Parameters.AddWithValue("#Class", Cass);
comm.Parameters.AddWithValue("#Health", Health);
comm.Parameters.AddWithValue("#Level", Lvl);
comm.Parameters.AddWithValue("#Agility", Agility);
comm.Parameters.AddWithValue("#Strength", Strength);
comm.Parameters.AddWithValue("#Stamina", Stamina);
comm.Parameters.AddWithValue("#Armor", Armor);
comm.Parameters.AddWithValue("#HoursPlayed", HoursPlayed);
comm.Parameters.AddWithValue("#PlayedSince", PlayedSince);
comm.Parameters.AddWithValue("#AvgPlayTime", AvgPlayTime);
comm.Parameters.AddWithValue("#TotalPoints", TotalPoints);
//Attempts to connect to the Database server
try
{
//Calls to the database server, like dialing a phone.
Conn.Open();
int intRecs = comm.ExecuteNonQuery();
//Output to rhe user the success of inserting records
strResult = $"SUCCESS: Inserted {intRecs} records.";
//Close the Connection to Database Server
Conn.Close();
}
//This will catch any errors if we run into issues connecting.
catch (Exception err)
{
//Displays The Error.
strResult = "ERROR: " + err.Message;
}
finally
{
}
return strResult;
}
public DataSet SearchPerson(String strCharName, String strCharID)
{
//Create a dataset to return filled
DataSet ds = new DataSet();
//Create a command for our SQL statement
SqlCommand comm = new SqlCommand();
//Write a Select Statement to perform Search
String strSQL = "SELECT CharID, CharName, Class, Health, Level, Agility, Strength, Armor, HoursPlayed, PlayedSince, AvgPlayTime, TotalPoints FROM Chars WHERE 0=0";
//If the First/Last Name is filled in include it as search criteria
if (strCharName.Length > 0)
{
strSQL += " AND CharName LIKE #CharName";
comm.Parameters.AddWithValue("#CharName", "%" + strCharName + "%");
}
if (strCharID.Length > 0)
{
strSQL += " AND CharID LIKE #CharID";
comm.Parameters.AddWithValue("#CharID", "%" + strCharID + "%");
}
//Create DB tools and Configure
//*********************************************************************************************
SqlConnection conn = new SqlConnection();
//Create the who, what where of the DB
string strConn = #GetConnected();
conn.ConnectionString = strConn;
//Fill in basic info to command object
comm.Connection = conn; //tell the commander what connection to use
comm.CommandText = strSQL; //tell the command what to say
//Create Data Adapter
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm; //commander needs a translator(dataAdapter) to speak with datasets
//*********************************************************************************************
//Get Data
conn.Open(); //Open the connection (pick up the phone)
da.Fill(ds, "Chars_Temp"); //Fill the dataset with results from database and call it "EBooks_Temp"
conn.Close(); //Close the connection (hangs up phone)
//Return the data
return ds;
}
private string GetConnected()
{
return ************************
}
// Initialize Public Class from person().
public Character()
{
charname = "";
cass = "";
health = 25;
lvl = 1;
agility = 1;
strength = 1;
stamina = 1;
armor = 10;
hoursplayed = 0;
playedsince = DateTime.Now;
feedback = "";
}
}
}
Validation:
//Allen J. Gawlowicz
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lab5_validation
{
public class ValidationLibrary
{
bool result = false;
string temp;
//Validates for alphabetical input only.
public static bool Goodchar(string temp)
{
bool result = false;
string strGoodChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// FOR EACH charcacter in Variable, check to make sure it is Alphabetical
foreach (char ch in strGoodChars.ToUpper())
{//If the variable contains only alphabetical, result= true.
if (temp.Contains(ch))
{
result = true;
}
}
return result;
}
//Checks to see if user inputs a bad word.
public static bool GotBadWords(string temp)
{
bool result = false;
//Array which holds all bad words to ever exist!!
string[] strBadwords = { "POOP", "HOMEWORK", "CACA" };
// FOR EACH word in the array it checks to see if input value matches.
foreach (string strBW in strBadwords)
{
if (temp.Contains(strBW))
{
result = true;
}
}
return result;
}
//Function which checks if user inputs.
public static bool IsItFilledIn(string temp)
{
bool result = false;
//If the number of characters entered is greater than 0 (then obviously), it is filled in (true).
if (temp.Length > 0)
{
result = true;
}
return result;
}
//Function which checks if user input is a future date.
public static bool IsAFutureDate(DateTime temp)
{
bool blnResult;
//IF usrr input is today or before, then blnRes = false.
if (temp <= DateTime.Now)
{
blnResult = false;
}
else
{
blnResult = true;
}
return blnResult;
}
//Function which checks user email input for '#' and '.'.
public static bool IsValidEmail(string temp)
{
bool blnResult = true;
int atLocation = temp.IndexOf("#");
int NexttatLocation = temp.IndexOf("#", atLocation + 1);
int periodLocation = temp.LastIndexOf(".");
if (temp.Length < 8)
{
blnResult = false;
}
else if (atLocation < 2)
{
}
else if (periodLocation + 2 > (temp.Length))
{
blnResult = false;
}
return blnResult;
}
//Function which checks for '.' in the input URL.
public static bool IsValidUrl(string temp)
{
bool blnResult = true;
int NexttatLocation = temp.IndexOf(".");
int periodLocation = temp.LastIndexOf(".");
if (temp.Length < 10)
{
blnResult = false;
}
else if (periodLocation + 2 > (temp.Length))
{
blnResult = false;
}
return blnResult;
}
//Function which checks user input for a specific length. ('min' will changed depending on variable in main program).
public static bool IsMinimumAmount(string temp, int min)
{
bool blnResult;
if (temp.Length >= min)
{
blnResult = true;
}
else
{
blnResult = false;
}
return blnResult;
}
public static bool IsMinimumAmount(double temp, double min)
{
bool blnResult;
if (temp >= min)
{
blnResult = true;
}
else
{
blnResult = false;
}
return blnResult;
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Lab5_validation;
namespace FinalAJG
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Your Parse methods cannot accept an empty string. Instead, I suggest TryParse, which will try to parse the string, and if it fails then you will get the default value for the assignment target. So if you do this:
int.TryParse(txtHealth.Text, out temp.Health);
The value of temp.Health will be the parsed value of the string, or it will be the default (which is 0 for int).
The same approach can be used for double and DateTime, so:
double.TryParse(txtHoursPlayed.Text, out temp.HoursPlayed);
DateTime.TryParse(txtPlayedSince.Text, out temp.PlayedSince);
Alternatively, you can check if the input string IsNullOrWhiteSpace and assign a default if that's true:
temp.Health = string.IsNullOrWhiteSpace(txtHealth.Text) ? 0 : int.Parse(txtHealth.Text);
But of course the TryParse methods are generally cleaner.
Ok, so I am trying to figure out why I am having a looping issue. The intention of the method GetNewDvdInfo() is to return a new dvd class with 5 properties and will be passed on to DvdController.cs in the CreateDvd() method and will then display all the dvds and the dvd the user added. The problem is that the GetNewDvdInfo() method is repeating itself, but when I was returning null instead, it was not looping.
DvdView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
/*
GetMenuChoice() : int
GetNewDvdInfo(): Dvd
DisplayDvd(Dvd dvd) : void
EditDvdInfo(Dvd dvd) : Dvd
SearchDvd() : int
ConfirmRemoveDvd(Dvd) : boolean
*/
namespace DvdManager.View
{
public class DvdView
{
public int GetMenuChoice()
{
string input;
int choice;
Console.Clear();
Console.WriteLine("Press 1 to display movies");
Console.WriteLine("Press 2 to add movie");
input = Console.ReadLine();
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
break;
case 2:
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
return choice;
}
public Dvd GetNewDvdInfo() //looping here
{
string inputReleaseYear;
string inputRating;
int id = 4;
string readTitle;
int readReleaseYear;
string readDirector;
float readRating;
Console.WriteLine("What is the Title of the DVD?");
readTitle = Console.ReadLine();
Console.WriteLine("What is the Release Year of the DVD?");
inputReleaseYear = Console.ReadLine();
int.TryParse(inputReleaseYear, out readReleaseYear);
Console.WriteLine("Who is the Director of the DVD?");
readDirector = Console.ReadLine();
Console.WriteLine("What is the star rating of the DVD?");
inputRating = Console.ReadLine();
float.TryParse(inputRating, out readRating);
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo();
return dvd;
}
public void DisplayDvd(Dvd dvd)
{
}
public Dvd EditDvdInfo(Dvd dvd)
{
return null;
}
public int SearchDvd()
{
return 0;
}
public Boolean ConfirmRemoveDvd(Dvd dvd)
{
return false;
}
}
}
DvdController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;
using DvdManager.View;
/*
Run() : void
Private CreateDvd(): void
Private DisplayDvds(): void
Private SearchDvds(): void
Private EditDvd() : void
Private RemoveDvd() : void
*/
namespace DvdManager.Controllers
{
public class DvdController
{
public DVDList _dvds = new DVDList();
public void Run()
{
Console.WriteLine("Welcome To Dvd Manager");
DvdView view = new DvdView();
var pass = view.GetMenuChoice();
if (pass == 1)
{
CreateDvd();
}
else if (pass == 2)
{
view.GetNewDvdInfo();
CreateDvd();
}
else
Console.WriteLine("Invalid.");
}
private void CreateDvd() //Create
{
var myView = new DvdView();
var dvdInfos = myView.GetNewDvdInfo();
List<Dvd> Dvds = _dvds.GetList();
Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
Dvds.Add(dvdInfos);
DisplayDvds();
}
private void DisplayDvds() //Read List<Dvd> dvds
{
List<Dvd> Dvds = _dvds.GetList();
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
RemoveDvd();
}
private void SearchDvds() //List
{
}
private void EditDvd(int id, Dvd dvd) //Update
{
}
private void RemoveDvd() //Delete int id
{
List<Dvd> Dvds = _dvds.GetList();
//Dvds.RemoveAt(Dvds[1]);
Dvds.Remove(Dvds.Single(x => x.Id == 1));
Console.WriteLine("Removed movie from list:");
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
}
}
}
You are making a recursive call at the end of GetNewDvdInfo(), just remove it.
You are calling this method recursively here:
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo(); //!!!
return dvd;
Hence the looping. It seems like this line of code is not needed.
I'm working on a "bank application" in C# WPF where I came upon error:CS0052
Inconsistent accessibility: field type 'List' is less
accessible than field 'Customer.CustomerAccountsList'
The idea is that the method bool DoseThisAccountExistAlready() should check all customers one by one and see if his/her accounts have the same data as the account that is about to be created.
However CustomerAccountsList must be public or DoseThisAccountExistAlready() can't access the accounts data.
How do I fix this error?
//main window
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Uppgift2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public List<Customer> ListOfAllCustomers = new List<Customer>();
public bool Login(string fornamn, string efternamn, string pin)
{
foreach (Customer c in ListOfAllCustomers)
{
if (c.firstname == fornamn && c.lastname == efternamn && c.pinKod == pin)
{
MessageBox.Show("Login succesfull. Welcome " + c.firstname + " " + c.lastname);
WindowAccountOperations LoggedInUser = new WindowAccountOperations();
LoggedInUser.ShowDialog();
return true;
}
else
{
MessageBox.Show("Det finns inte ett sånt användare. Kontrolera användarnamn och pin");
return false;
}
}
return false;
}
//Customer pin could be remade into a rondom generator with an if() that forces it to be a four digit number
/*
* Random randomPin = new Random();
randomPin.Next(x, y);
if(randomPin.ToString().Length!=4)
{
}
*/
public bool CreateNewCustomer(string fornamn, string efternamn, string telefon, string customerAdress, string customerPin)
{
//Is there already such customer?
foreach (Customer c in ListOfAllCustomers)
{
if ((c.firstname == fornamn && c.lastname == efternamn && c.adress == customerAdress))
{
MessageBox.Show("Kunden med ett sånt förnamn, efternamn och adress redan finns");
return false;
}
if(c.pinKod == customerPin)
{
MessageBox.Show("Kunden med ett sånt pinkod redan finns");
return false;
}
else
{
ListOfAllCustomers.Add(new Customer(TBFirstNameNyKund.Text, TBSecondNameLogin.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text));
MessageBox.Show("Registration complete. Du kan nu logga in");
TBFirstNameNyKund.Clear(); TBSecondNameLogin.Clear(); TBAdressNyKund.Clear(); TBPinNyKund.Clear();//clear login textboxes
return true;
}
}
return false;
}
public bool DoseThisAccountExistAlready(string kontoNummer, string kontotyp)
{
foreach (Customer c in ListOfAllCustomers )
{
foreach(Account a in c.CustomerAccountsList)
{
if(a.accountType==kontotyp)//Does customer c try to create another type of account he already has?
{
return true;
}
if(a.accountNumber==kontoNummer)
{
return true;
}
}
return false;
}
return false;
}
private void ButtonLogin_Click(object sender, RoutedEventArgs e)
{
Login(TBFirstNameLogin.Text, TBSecondNameLogin.Text, TBPinLogin.Text);
}
private void ButtonSkapaKund_Click(object sender, RoutedEventArgs e)
{
CreateNewCustomer(TBFirstNameNyKund.Text, TBSecondNameNyKund.Text, TBTelNyKund.Text, TBAdressNyKund.Text, TBPinNyKund.Text);
}
}
}
//customer class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uppgift2
{
public class Customer
{
public string adress;
public string celphone;
public string firstname;
public string lastname;
public string pinKod;
public List<Account> CustomerAccountsList = new List<Account>();//Error apears here.
public Customer(string fname,string lname, string tel, string customerAdress,string customerPin)
{
adress = customerAdress;
celphone = tel;
firstname = fname;
lastname = lname;
pinKod = customerPin;
}
}
}
//account base class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uppgift2
{
abstract class Account //The abstract modifier indicates that the thing being modified has a missing or incomplete implementation=base class for other classes
{
public double payoutAmmount;
protected double payoutTax;
public bool creditPosible;
public string accountNumber;
public string accountType;
public double balance;
protected double interest; //customer shouldent be able to modify interest %
//constructor
public Account(string kontoNummer, double KontoStartsaldo,string kontoTyp, double ranta, bool finsdetkredit,double uttagPris)
{
accountNumber = kontoNummer;
balance = KontoStartsaldo;
accountType = kontoTyp;
creditPosible = finsdetkredit;
payoutTax = uttagPris;
}
public double InsertMoney(int chosenAccount, double payout) //int chosenAccount becouse i thought to use a combo box index
{
payoutAmmount = payout;
balance = balance - payout + (payout * payoutTax);
return balance;
}
}
}
You can't have a public List<Account> because the Account class has no access modifier so it is defaulted by the compiler to be internal. You can't have a public property of an internal type. You need to make it public for this to work.
I'm trying to extract a complete method which is inside a cs file.
for instance.. suppose we have a class like this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetMethodNm
{
class MyClass
{
public int ComplexMethod(int param1, int myCustomValue)
{
if (param1 == myCustomValue)
{
return 54;
}
else
{
return 0;
}
}
public string ComplexMethodV(int param1, int myCustomValue)
{
if (param1 < myCustomValue)
{
return "300";
}
else
{
return "My custom value to return";
}
}
public bool ComplexMethodX(int param1, int myCustomValue)
{
if (param1 == myCustomValue)
{
return true;
}
else
{
return false;
}
}
}
}
Then I need to extract the method reading the cs file ComplexMethodV .. How can I do this? I have tried with reflection but I can only get the name and some things inside of it.. but I would need the literal method within.
Using Roslyn tasks like this are relitively easy. In a project add the NuGet package Microsoft.CodeAnalysis.CSharp, then just use the following code
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace SandboxConsole
{
class Program
{
public static void Main()
{
var text = File.ReadAllText("MyClass.cs");
var tree = CSharpSyntaxTree.ParseText(text);
var method = tree.GetRoot().DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.First(x => x.Identifier.Text == "ComplexMethodV");
Console.WriteLine(method.ToFullString());
Console.ReadLine();
}
}
}
This outputs the text
public string ComplexMethodV(int param1, int myCustomValue)
{
if (param1 < myCustomValue)
{
return "300";
}
else
{
return "My custom value to return";
}
}
See the Wiki for more advanced tutorials on how to do things like parse entire solutions.
I have been searching the internet for days now and I was just wondering if anyone has done any work with exporting data to excel using MVC 3. I really need a good tutorial that has step-by-step instructions on how to export excel data using MVC 3 with C#. I have found plenty of articles but none of them seem to work with my existing database. I am just looking for some instruction on where to put methods etc. This tutorial http://stephenwalther.com/blog/archive/2008/06/16/asp-net-mvc-tip-2-create-a-custom-action-result-that-returns-microsoft-excel-documents.aspx
seems to be highly recommended on stack overflow. I have followed the article's instructions to the letter but I can't run the program because Visual studio is throwing an error on the return for method GenerateExcel1
This is where VS is saying I have an error
return this.Excel(db, db.iamp_mapping, "data.xls")
right now I am getting 2 error messages that say
Error 1 'DBFirstMVC.Controllers.PaController' does not contain a
definition for 'Excel' and the best extension method overload
'DBFirstMVC.CustomActionResults.ExcelControllerExtensions.Excel(System.Web.Mvc.Controller,
System.Data.Linq.DataContext, System.Linq.IQueryable, string)' has
some invalid arguments C:\Documents and Settings\lk230343\My
Documents\Visual Studio 2010\WebSites\DBFirstMVC
Saves\DBFirstMVC_CRUD_and_PAGING_done\DBFirstMVC\Controllers\PaController.cs 193 24 DBFirstMVC
Error 2 Argument 2: cannot convert from 'DBFirstMVC.Models.PaEntities'
to 'System.Data.Linq.DataContext' C:\Documents and
Settings\lk230343\My Documents\Visual Studio 2010\WebSites\DBFirstMVC
Saves\DBFirstMVC_CRUD_and_PAGING_done\DBFirstMVC\Controllers\PaController.cs 193 35 DBFirstMVC
Has anyone ever seen these errors before or have any idea on how I can fix them? I mean the excel method exists in ExcelControllerExtensions.cs and I thought I had made that assembly available to the PaController. Honestly, I have no idea why it is throwing an error on the return so any advice/discussion/help would be welcomed. I have included the code for the 3 files that I have been messing with but if you think I forgot to post one that is needed to diagnose this error let me know and I will post it. Thanks for your help!
PaController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Web.UI.WebControls;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
using System.Data;
using PagedList;
using PagedList.Mvc;
using DBFirstMVC.Controllers;
using System.IO;
using DBFirstMVC;
using DBFirstMVC.CustomActionResults;
namespace DBFirstMVC.Controllers
{
public class PaController : Controller
{
private PaEntities db = new PaEntities();
//
// GET: /Pa/
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "PA desc" : "";
ViewBag.MPSortParm = sortOrder == "MP" ? "MP desc" : "MP asc";
ViewBag.IASortParm = sortOrder == "IA" ? "IA desc" : "IA asc";
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var IAMP = from p in db.iamp_mapping select p;
if (!String.IsNullOrEmpty(searchString))
{
IAMP = IAMP.Where(p => p.PA.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "Pa desc":
IAMP = IAMP.OrderByDescending(p => p.PA);
break;
case "MP desc":
IAMP = IAMP.OrderByDescending(p =>p.MAJOR_PROGRAM);
break;
case "MP asc":
IAMP = IAMP.OrderBy(p =>p.MAJOR_PROGRAM);
break;
case "IA desc":
IAMP = IAMP.OrderByDescending(p => p.INVESTMENT_AREA);
break;
case "IA asc":
IAMP = IAMP.OrderBy(p => p.INVESTMENT_AREA);
break;
default:
IAMP = IAMP.OrderBy(p => p.PA);
break;
}
int pageSize = 25;
int pageNumber = (page ?? 1);
return View(IAMP.ToPagedList(pageNumber, pageSize));
}
//
// GET: /Pa/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Pa/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Pa/Create
[HttpPost]
public ActionResult Create(iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.iamp_mapping.Add(IAMP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Pa/Edit/5
public ActionResult Edit(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
//
// POST: /Pa/Edit/5
[HttpPost]
public ActionResult Edit(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("");
}
}
catch
{
return View();
}
}
//
// GET: /Pa/Delete/5
public ActionResult Delete(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
//
// POST: /Pa/Delete/5
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
var vIAMP = db.iamp_mapping.Find(id);
db.Entry(vIAMP).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception e)
{
throw (e);
//return View();
}
}
public ActionResult GenerateExcel1()
{
using (var db = new PaEntities())
{
return this.Excel(db, db.iamp_mapping, "data.xls");
}
}
}
}
ExcelResult.cs
using System;
using System.Web.Mvc;
using System.Data.Linq;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Drawing;
namespace DBFirstMVC
{
public class ExcelResult : ActionResult
{
private DataContext _dataContext;
private string _fileName;
private IQueryable _rows;
private string[] _headers = null;
private TableStyle _tableStyle;
private TableItemStyle _headerStyle;
private TableItemStyle _itemStyle;
public string FileName
{
get { return _fileName; }
}
public IQueryable Rows
{
get { return _rows; }
}
public ExcelResult(DataContext dataContext, IQueryable rows, string fileName)
: this(dataContext, rows, fileName, null, null, null, null)
{
}
public ExcelResult(DataContext dataContext, string fileName, IQueryable rows, string[] headers)
: this(dataContext, rows, fileName, headers, null, null, null)
{
}
public ExcelResult(DataContext dataContext, IQueryable rows, string fileName, string[] headers, TableStyle tableStyle, TableItemStyle headerStyle, TableItemStyle itemStyle)
{
_dataContext = dataContext;
_rows = rows;
_fileName = fileName;
_headers = headers;
_tableStyle = tableStyle;
_headerStyle = headerStyle;
_itemStyle = itemStyle;
// provide defaults
if (_tableStyle == null)
{
_tableStyle = new TableStyle();
_tableStyle.BorderStyle = BorderStyle.Solid;
_tableStyle.BorderColor = Color.Black;
_tableStyle.BorderWidth = Unit.Parse("2px");
}
if (_headerStyle == null)
{
_headerStyle = new TableItemStyle();
_headerStyle.BackColor = Color.LightGray;
}
}
public override void ExecuteResult(ControllerContext context)
{
// Create HtmlTextWriter
StringWriter sw = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(sw);
// Build HTML Table from Items
if (_tableStyle != null)
_tableStyle.AddAttributesToRender(tw);
tw.RenderBeginTag(HtmlTextWriterTag.Table);
// Generate headers from table
if (_headers == null)
{
_headers = _dataContext.Mapping.GetMetaType(_rows.ElementType).PersistentDataMembers.Select(m => m.Name).ToArray();
}
// Create Header Row
tw.RenderBeginTag(HtmlTextWriterTag.Thead);
foreach (String header in _headers)
{
if (_headerStyle != null)
_headerStyle.AddAttributesToRender(tw);
tw.RenderBeginTag(HtmlTextWriterTag.Th);
tw.Write(header);
tw.RenderEndTag();
}
tw.RenderEndTag();
// Create Data Rows
tw.RenderBeginTag(HtmlTextWriterTag.Tbody);
foreach (Object row in _rows)
{
tw.RenderBeginTag(HtmlTextWriterTag.Tr);
foreach (string header in _headers)
{
string strValue = row.GetType().GetProperty(header).GetValue(row, null).ToString();
strValue = ReplaceSpecialCharacters(strValue);
if (_itemStyle != null)
_itemStyle.AddAttributesToRender(tw);
tw.RenderBeginTag(HtmlTextWriterTag.Td);
tw.Write(HttpUtility.HtmlEncode(strValue));
tw.RenderEndTag();
}
tw.RenderEndTag();
}
tw.RenderEndTag(); // tbody
tw.RenderEndTag(); // table
WriteFile(_fileName, "application/ms-excel", sw.ToString());
}
private static string ReplaceSpecialCharacters(string value)
{
value = value.Replace("’", "'");
value = value.Replace("“", "\"");
value = value.Replace("”", "\"");
value = value.Replace("–", "-");
value = value.Replace("…", "...");
return value;
}
private static void WriteFile(string fileName, string contentType, string content)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
context.Response.Charset = "";
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = contentType;
context.Response.Write(content);
context.Response.End();
}
}
}
ExcelControllerExtensions
using System;
using System.Web.Mvc;
using System.Data.Linq;
using System.Collections;
using System.Web.UI.WebControls;
using System.Linq;
namespace DBFirstMVC.CustomActionResults
{
public static class ExcelControllerExtensions
{
public static ActionResult Excel
(
this Controller controller,
DataContext dataContext,
IQueryable rows,
string fileName
)
{
return new ExcelResult(dataContext, rows, fileName, null, null, null, null);
}
public static ActionResult Excel
(
this Controller controller,
DataContext dataContext,
IQueryable rows,
string fileName,
string[] headers
)
{
return new ExcelResult(dataContext, rows, fileName, headers, null, null, null);
}
public static ActionResult Excel
(
this Controller controller,
DataContext dataContext,
IQueryable rows,
string fileName,
string[] headers,
TableStyle tableStyle,
TableItemStyle headerStyle,
TableItemStyle itemStyle
)
{
return new ExcelResult(dataContext, rows, fileName, headers, tableStyle, headerStyle, itemStyle);
}
}
}
Model1.context.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
namespace DBFirstMVC.Models
{
public partial class PaEntities : DbContext
{
public PaEntities()
: base("name=PaEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<iamp_mapping> iamp_mapping { get; set; }
public DbSet<pa_mapping> pa_mapping { get; set; }
}
}
iamp_mapping.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace DBFirstMVC.Models
{
public partial class iamp_mapping
{
public string PA { get; set; }
public string MAJOR_PROGRAM { get; set; }
public string INVESTMENT_AREA { get; set; }
}
}
The reason for the error is right there in the message: cannot convert from 'DBFirstMVC.Models.PaEntities' to 'System.Data.Linq.DataContext. It means that you PaEntities type cannot be converted to System.Data.Linq.DataContext, therefore none of your Excel extension methods' signature matches the arguments you are passing.
What is your PaEntities type? Does it inherit from System.Data.Linq.DataContext?