OK thanks for your help with that!
Violet_82 89 Posting Whiz in Training
Hi guys,
I'm looking into MVC and I'm reasing this tutorial http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-fundamentals
I've got to the point of adding a model and the class they add is this:
public class StoreIndexViewModel
{
public int NumberOfGenres { get; set; }
public List<string> Genres { get; set; }
}
I'm not really familiar with this syntax public List<string> Genres
and I was wondering if anybody can help me understanding this a bit better. They refer to it as a list of string, so why not use an array of strings? Is that also what they call a "generic"? How do I get values in that list of string and how do I get them out please?
thanks
Violet_82 89 Posting Whiz in Training
Ah, I see, thanks!
Violet_82 89 Posting Whiz in Training
It's not a silly question at all. In fact, I have no idea, and I'll explain why. The exercise detailed on the book, is essentially the same as mine, but the project name and all the file names are different. Theirs works, and when I look at the database created I can see the data in it. At no point they have modified the connection string.
I then reused pretty much the same code for a different project, and obviously I haven't touched the connection string. The assumption, I presume, was that something else will take care of it, as it appears to have done with their own exercise. Something obviously has gone wrong.
I'll have a look, so the string needs to point to the database I created correct, presumably it has its name on in in a string format?
Violet_82 89 Posting Whiz in Training
Hello guys, totally new to MVC and I've built a small simple application with the help of a book I'm reading. But, needless to say it, I run into some problems. Let me run through what I did and what the problem is (by the way, I'm not so sure how easy it will be to show you the code, I will probably add everything to pastebin...funny they say the MVC application are easier to test...um...not so sure about that).
ANyway, my project is called Storage_test and it is nothing else than a form that allows users to input some data in a database and then retrieve them on the same page.
Now, let me say that while I appreciate this can be done in more effective ways, as said I've just started and found this method fairly easy, so I rather fix this than finding a better one.
So, first of all, I created a database, named Storage_test.sdf and the table in it Storage_test_records (the book suggested to do that with SQL Server Compact and so I did), here is the screenshot: http://s10.postimg.org/n8em2mw3t/Storage_test_records.png
Then I proceeded to create a model class StorageRecord.cs which essentially is a representation of the storage record which will go in the database, here http://pastebin.com/FT1s40wk
Then a StorageRecordContext.cs that contains the DbContex info to use the Entity Framework info (Which the book made me install as an add on to Visual studio 2012), here http://pastebin.com/xqaH6XqE
And a controller called …
Violet_82 89 Posting Whiz in Training
I just wanted to share this with the community, in case anybody finds it useful. I'm learning ASP.NET and started with Web Forms and now I'm moving slowly to MVC. As I have just started with MVC - which is significantly different from Web Form - I've been looking for a good book/tutorial, but it has been harder than I thought. Yes I did find good books, but they all required some knowledge I didn't have. SO, eventually I stumbled across this one, "Intro to ASP.NET MVC 4 with visual studio", by Rick Anderson and Scott Hanselman, here is a link to it (the link is from the microsoft website and will download the PDF straightaway - note to mods: I could only find a direct link. ) Intro to ASP.NET MVC 4 with Visual Studio (Beta)
It's a good starting point, and then you can expand from there and get a good book.
Violet_82 89 Posting Whiz in Training
Cool, thanks!
Violet_82 89 Posting Whiz in Training
OK thanks. Do you happen to know a good tutorial specifically on this as the book I have doesn't really go too much into it
Violet_82 89 Posting Whiz in Training
Ah...I had an idea. Could it be that I get the error because some of the input fields contain an empty string and therefore I'm trying to convert an empty string into a decimal? Just an idea.
Violet_82 89 Posting Whiz in Training
HI guys, quick (and perhaps stupid) question. Basically I'm getting some values out of a database, converting them into string and store them in dedicated input fields:
if (reader.HasRows) { //because there should be only 1 row to read, otherwise use while
reader.Read();
rent.Value = Convert.ToString(reader["Rent"]);
car.Value = Convert.ToString(reader["Car"]);
bills.Value = Convert.ToString(reader["Bills"]);
food.Value = Convert.ToString(reader["Food"]);
//expenseComment.Value = Convert.ToString(reader[""]);
}
reader.Close();
hookUp.Close();
I have an extra input field <input type="text" id="total" runat="server" readonly>
where I'd like to store the sum of the above values so I created a decimal variable private decimal expensesTotal;
to store all the values in it - rent, car, bills and food. I converted all the values of the above input fields into decimal values like so
expensesTotal = Decimal.Parse(rent.Value) + Decimal.Parse(car.Value) + Decimal.Parse(bills.Value) + Decimal.Parse(food.Value);
and then converted the results back into string and save it onto the total input field like so:
total.Value = Convert.ToString(expensesTotal);
but ASP.NET returns an error:
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: Input string was not in a correct format.
Source Error:
Line 50: reader.Close();
Line 51: hookUp.Close();
Line 52: expensesTotal = Decimal.Parse(rent.Value) + Decimal.Parse(car.Value) + Decimal.Parse(bills.Value) + Decimal.Parse(food.Value);
Line 53: total.Value = Convert.ToString(expensesTotal);
Line 54: }
Source File: c:\Users\antonio.borrillo\Documents\Visual Studio 2012\WebSites\Expenses\Overview.aspx.cs Line: 52
Stack Trace:
[FormatException: Input string was not in …
Violet_82 89 Posting Whiz in Training
Yes, I've seen that syntax, but I had no idea that .NET handled the "private" versions behind the scene. So what does .NET exactly do, if it is not too difficult to explain/understand with the private variables?
Violet_82 89 Posting Whiz in Training
Thanks for that, yes I supposed you're right, that's the approach the author has decided to take.
You actually do have the private version... .NET is handing that private for you.
What do you mean exactly by that? Just to clarify, I was referring to the last example where you have only one private variable, Price, the other ones, Names and ImageUrl are public. So, are you saying that Names and ImageUrl have their own private counterparts implicitly declared somewhere?
Violet_82 89 Posting Whiz in Training
But I think I can live with that. What puzzles me is the usage. Let's take another example, completely unrelated, that hopefully will help me to clarify the whole thing. Here is an application:
Product.cs:
using System;
public class Product
{
private decimal price;
private string imageUrl;
private string name;
public Product(string the_name, decimal the_price, string the_imageUrl)
{
name = the_name;
price = the_price;
imageUrl = the_imageUrl;
}
}
Default.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
private void Page_Load(object sender, EventArgs e)
{
Product saleProduct = new Product("Kitchen Garbage", 49.99M, "garbage.jpg");
//Response.Write(saleProduct.GetHtml());
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Product Test</title>
</head>
<body></body>
</html>
Pretty simple: a few private variables, when I create the new object, the constructor is called and the attributes values specified in the object creations are copied into the private variables. That's it. That's the way I'd do it.
How about this instead (Default.aspx stays the same):
Product.cs
using System;
public class Product
{
public string Name { get; set; }
private decimal price;
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string ImageUrl { get; set; }
public Product(string the_name, decimal the_price, string the_imageUrl)
{
Name = the_name;
price = the_price;
ImageUrl = the_imageUrl;
}
}
I saw this example somewhere in the book I'm reading. What's this nonsense?! What is the point of having public variables like Name and ImageUrl in this case if we don't have …
Violet_82 89 Posting Whiz in Training
No, I meant the way it is done in any other OO language, with set and get methods, like this (example taken from http://www.csharp-station.com/Tutorial/CSharp/lesson10)
using System;
public class Customer
{
private int m_id = -1;
public int GetID()
{
return m_id;
}
public void SetID(int id)
{
m_id = id;
}
private string m_name = string.Empty;
public string GetName()
{
return m_name;
}
public void SetName(string name)
{
m_name = name;
}
}
public class CustomerManagerWithAccessorMethods
{
public static void Main()
{
Customer cust = new Customer();
cust.SetID(1);
cust.SetName("Amelio Rosales");
Console.WriteLine(
"ID: {0}, Name: {1}",
cust.GetID(),
cust.GetName());
Console.ReadKey();
}
}
here we have a get method and a set method
Violet_82 89 Posting Whiz in Training
But why not doing it the usual way via a setter/getter method? I don't get (no pun intended) that!?
Violet_82 89 Posting Whiz in Training
I just came across something strange, and I posted it here because although it is C# it is still part of learning ASP.NET.
Usually when you use setters and getters, you have proper methods to set and access private variables (I'm referring to C++ and JAVA mainly) but here in C# you seem to have setters and getters methods and then this strange syntax:
public class Product
{
private string name;
private decimal price;
private string imageUrl;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
What on earth is that? So Name is effectively a public variable here isn't it? And how about get and set? what are they? Methods?!
Violet_82 89 Posting Whiz in Training
OK, I think I got it. There was no need to create a new table in the first place, facepalm, as I can simply read the results from the current tables as they WHERE filter will do the job for me!
protected void displayLondonPrices(object sender, EventArgs e) {
string londonPrice;
string london_surname;
string london_name;
hookup = new SqlConnection("Server=localhost\\SqlExpress;Database=tests;" + "Integrated Security=True");
strInsert = "SELECT Name,Surname,Price FROM transactions WHERE Town='London'";
sqlCmd = new SqlCommand(strInsert, hookup);
hookup.Open();
reader = sqlCmd.ExecuteReader();
queryResults.Text = " ";
while (reader.Read()) {
london_name = Convert.ToString(reader["Name"]);
london_surname = Convert.ToString(reader["Surname"]);
londonPrice = Convert.ToString(reader["Price"]);
queryResults.Text += "user in London is " + london_name + " " + london_surname + " and price paid is " + londonPrice + "<br />";
}
reader.Close();
hookup.Close();
}
The result returned now is:
user in London is Antonio Borrillo and price paid is 345.00
user in London is Thomas Hardy and price paid is 23.00
user in London is Hanna Moos and price paid is 345.00
Violet_82 89 Posting Whiz in Training
Thanks, no I'm trying to show the surnames and prices of all the users that live in london, without summing the prices up, so the result will display probably about 2 or 3 rows
I dont' think I'm far from it, I replaced my query with this strInsert = "SELECT Surname,Price AS Londoners FROM transactions WHERE Town='London'";
and the results with this queryResults.Text += "users in London are " + londonPrice;
(sorry I just realized that my text says the sum of prices, which is wrong as that's not what I wanted) and get this result:users in London are 345.00users in London are 23.00users in London are 345.00
which is almost there, except that I want also the Surname
Violet_82 89 Posting Whiz in Training
Hi, I run into an interesting thing. I'm looking into SQL a bit, and was reading some tutorial on W3C, so I built a small application to play with SQL queries: inserting info in a table and then retrieve it as it is, filter it etc.
The table contains 5 columns: Id(int and primary key), Name (nvarchar), Surname (nvarchar), Town (nvarchar), Price (decimal) and the data is inserted upon submission of a form. Now, I was trying to retrieve all the surnames and prices of all people living in London. The query in itself is pretty simple: SELECT Surname,Price FROM transactions WHERE Town='London'
but there is a problem: I want to display the results in a label as its value and therefore I need another table where copying these results. Here is the full code but unfortunately I get an error, the compiler complains about the "AS":
protected void displayLondonPrices(object sender, EventArgs e) {
string londonPrice;
hookup = new SqlConnection("Server=localhost\\SqlExpress;Database=tests;" + "Integrated Security=True");
strInsert = "SELECT Surname,Price FROM transactions AS Londoners WHERE Town='London'";
sqlCmd = new SqlCommand(strInsert, hookup);
hookup.Open();
reader = sqlCmd.ExecuteReader();
while (reader.Read()) {
londonPrice = Convert.ToString(reader["Londoners"]);
queryResults.Text = "Total in London is " + londonPrice;
}
reader.Close();
hookup.Close();
}
Essentially, I need something that the reader can read, which is why I used AS Londoners
in the query. Is there another way?
Violet_82 89 Posting Whiz in Training
Brilliant, thanks for clarifying that
Violet_82 89 Posting Whiz in Training
Just thinking about something though. Surely I can turn this around and learn a bit more about the error and the way the query is handled. So, I missed the semicolon: what effect does that have on the application? Meaning, how is the query interpreted without the semicolon? Why does the login fail?
Violet_82 89 Posting Whiz in Training
OK, so apparently the right query is
strInsert = "SELECT Rent, Car, Bills, Food FROM( SELECT expenseCode.ExpenseType, expenses.Cost FROM expenses INNER JOIN expenseCode ON expenses.ExpenseId = expenseCode.Id WHERE (Datepart(month, expenses.Date) = @theMonth)) sq PIVOT( SUM(Cost) FOR ExpenseType IN (Rent, Car, Bills, Food)) pt;";
Got to admit that I didn't come to the solution myself, but got some help as I'm not too strong in SQL. So, the difference is that expenses.Date from the inner SELECT is gone, the old one was
strInsert = "SELECT Rent, Car, Bills, Food FROM( SELECT expenseCode.ExpenseType, expenses.Cost, expenses.Date FROM expenses INNER JOIN expenseCode ON expenses.ExpenseId = expenseCode.Id WHERE (DATEPART(month, expenses.Date) = @theMonth)) sq PIVOT( SUM(Cost) FOR ExpenseType IN (Rent, Car, Bills, Food)) AS pt";
Not quite sure what the difference translates into what though. OK we got rid of expenses.Date: what does that do?
Violet_82 89 Posting Whiz in Training
Facepalm. And so it is. I've been looking at this code over and over, and didn't spot the flipping missing semi-colon.
Can't apologize enough...
Sorry for wasting your time on such a trivial issue. I put it down to the fact that I haven't copied and pasted but typed every single word in there. Sorry.
Violet_82 89 Posting Whiz in Training
I must admit I feel a little embarrassed to post this, but I don't seem to get this simple flipping application to work and I'm getting this error:
Login failed for user ''.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Login failed for user ''.
Source Error:
Line 21: sqlCmd.Parameters.Add("@town", town.Value);
Line 22: sqlCmd.Parameters.Add("@price", price.Value);
Line 23: hookup.Open();
Line 24: sqlCmd.ExecuteNonQuery();
Line 25: hookup.Close();
Source File: c:\Users\antonio.borrillo\Documents\Visual Studio 2012\WebSites\testing\Default.aspx.cs Line: 23
Stack Trace:
[SqlException (0x80131904): Login failed for user ''.]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295887
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +69
System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +30
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +317
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +889
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +225
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +37
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnectionOptions userOptions) +558
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnectionOptions userOptions) +67
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1052
System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 …
Violet_82 89 Posting Whiz in Training
@djjavons, I run teh debug and it looks like the values just don't get across as you can see from the debugging screenshot http://s22.postimg.org/5i02eo1xd/debugging.jpg (you'll see that all teh values are incorrect, rent is empty, car is 44.0 0 but it should be 54.00, bills should be 30,00 but it is empty, and food is 56.00 but should be 66.00).
Also, you could write out the SQL statement to the immediate window and execute it as a new query to see what results are returned
How is that done? is it just right click on the table and select new query, then run it fromt here? The thins is I don't see any results except for Command completed successfully
, as in the screenshot here http://s2.postimg.org/ms61wn7yh/sql_query_result.jpg
Violet_82 89 Posting Whiz in Training
@james E: thanks for that but I get an error when I use your string strInsert = "SELECT et.ExpenseType, ISNULL(SUM(er.Cost),0.00) as Cost FROM ExpenseType et WITH(NOLOCK) LEFT OUTER JOIN ExpenseRecord er WITH(NOLOCK) ON er.ExpenseTypeId = et.ExpenseTypeId GROUP BY et.ExpenseType";
saying that :
Invalid object name 'ExpenseType'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'ExpenseType'.
Source Error:
Line 42: sqlCmd.Parameters.Add(param);
Line 43: hookUp.Open();
Line 44: reader = sqlCmd.ExecuteReader();
Line 45: if (reader.HasRows) { //because there should be only 1 row to read, otherwise use while
Line 46: reader.Read();
Source File: c:\Users\antonio.borrillo\Documents\Visual Studio 2012\WebSites\Expenses\Overview.aspx.cs Line: 44
Stack Trace:
[SqlException (0x80131904): Invalid object name 'ExpenseType'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1754082
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5295874
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +242
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1325
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteReader() +99
Overview.Page_Load(Object sender, EventArgs e) in c:\Users\antonio.borrillo\Documents\Visual Studio 2012\WebSites\Expenses\Overview.aspx.cs:44
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
@djjavons …
Violet_82 89 Posting Whiz in Training
Has anybody got an idea? I'm really struggling to understand why only part of the data in the table is returned.
Violet_82 89 Posting Whiz in Training
Um, unfortunately I've just realized that the application doesn't work, for whatever reasons. I can insert data in the database - I can check that from visual studio and the new data is there - but I don't seem to be able to retrieve the data from the database and populate the input fields with anything except for 2 old values that are there, car and food (respectively 44.00 and 56.00, you can see them in the first post, where I have both tables and here is a screenshot of the Overview page as it is now)
but if I insert more values for anything, including food and car, the app doesn't add them up or display them at all (but note that it is adding up the old values for car). Weird. I'm looking through my code over and over, but I don't seem to be able to find the error.
Here are the files, just in case anybody fancies having a look through it, because I can't spot anything wrong, but then again I have been looking at this app for a while now so perhaps some fresh eyes will help:
Overview.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Overview.aspx.cs" Inherits="Overview" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="HeadingPlaceholder" Runat="Server">
<h2>Data extract for the month of <%--<span runat="server" id="currentMonth"></span>--%><asp:Label ID="currentMonth" runat="server" Text="Label"></asp:Label> </h2>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceholder" Runat="Server">
<div class="results">
<div class="control-group">
<label class="control-label" for="rent">Rent</label>
<div class="controls">
<input type="text" id="rent" runat="server" readonly>
</div> …
Violet_82 89 Posting Whiz in Training
Hi thanks, Ok didn't occur to me, but since it is working as it is with 01, do I need to convert that to an int anyway? Is it just for good practice?
Also, is there any simple way to test another month to make sure that it work, or should I wait for February and see then :-)?
thanks
Violet_82 89 Posting Whiz in Training
Ah, wait apparently that's bad practice, I just came across this interesting resource http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06.
Ok, so forget the above. I have done it again with parameters:
//get the data
hookUp = new SqlConnection("Server=localhost\\SqlExpress;Database=Applications;" + "Integrated Security=True");
strInsert = "SELECT Rent, Car, Bills, Food FROM( SELECT expenseCode.ExpenseType, expenses.Cost, expenses.Date FROM expenses INNER JOIN expenseCode ON expenses.ExpenseId = expenseCode.Id WHERE (DATEPART(month, expenses.Date) = @theMonth)) sq PIVOT( SUM(Cost) FOR ExpenseType IN (Rent, Car, Bills, Food)) AS pt";
//1. defining @theMonth parameter as in http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06
SqlParameter param = new SqlParameter();
param.ParameterName = "@theMonth";
param.Value = now.ToString("MM");
sqlCmd = new SqlCommand(strInsert, hookUp);
// 2. add new parameter to command object
sqlCmd.Parameters.Add(param);
hookUp.Open();
reader = sqlCmd.ExecuteReader();
I tested it (well only for January as I wouldn't know how to test it for February) and it works, so now I have the current month results always displayed at the top of the page. There is only one thing that puzzles me.
As you can see I used param.Value = now.ToString("MM");
but originally I used param.Value = now.ToString("M");
because I was after an int with no 0's: but if I use only one "M" it doesn't work, no errors or anything, it just doesn't retrieve the data. If I go for 2 "MM" it works. Not convinced, I run a test, which, alas, confused me even more.
I added a test input field <input type="text" id="testingDate" runat="server" readonly>
in my aspx file and in the code behind I added …
Violet_82 89 Posting Whiz in Training
Hi, thanks for the suggestions. I'm halfway developing this, and something occurred to me about displaying the current month. Would it be easier if I did something like this (which isn't that different from what you suggested anyway):
-get the numerical representation of month:
DateTime now = DateTime.Now;//get current date
testingDate.Value = now.ToString("MM");
And then somehow using that now.ToString("Month");
in the SQL string, something along the lines of:
"SELECT Rent, Car, Bills, Food FROM( SELECT expenseCode.ExpenseType, expenses.Cost, expenses.Date FROM expenses INNER JOIN expenseCode ON expenses.ExpenseId = expenseCode.Id WHERE (DATEPART(month, expenses.Date) = " + now.ToString('MM') + ")) sq PIVOT( SUM(Cost) FOR ExpenseType IN (Rent, Car, Bills, Food)) AS pt";
And that should just sort the data out each month, correct?
Violet_82 89 Posting Whiz in Training
Yes I was thinking about something similar, except for the sum...so are you effectively doing it twice (once in the SQL statement and once outside?) or is the first one part of the PIVOT statement? Finally, 2 more questions if I may.
1)I had a look at subqueries as well, since you're using one, and they are largely clear but here you're using a FROM subquery, and I only saw a few examples. How should I read that subquery? My interpretation, probably wrong, of the whole SQL statement is (in pseudocode):
Select the Rent, Car, Bills and Food FROM [start of subquery]the new table containing ExpenseType, Cost and Date fields obtained by merging expenseCode and expenses WHERE the month is january[end of subquery] and create a new sq table, then SUM all the costs and 'rotate' the table so that Rent, Car, Bills and Food are column headings and name the new table pt
2)You used WHERE(DATEPART(month, dbo.expenses.Date) = 1)
as filter, which is great, but what if I want to display, say February? I mean, what I have in mind - and please forgive me for not making it clear at the beginning - would be to have the current month's worth of expenditure always at the top, and then perhaps past months at the bottom...so perhaps for the other months I will have to use a separate SQL statement rather than trying to incorporate everything in one?
Violet_82 89 Posting Whiz in Training
Thanks guys.
What if you added an extra expense type? You'd add a new input manually?
Good point.
@djjeavons. Thanks for the explanation. I took a bit of time to read a bit more about SQL (the w3c school SQL tutorial helped a bit ) because I realized I really don't know much about it....I feel a bit better now :-)! Anyway, I'm just thinking: so we create this new table where I can get the data from, but what I don't understand is, when is this table created? Everytime I run the application? Where does it reside, together with the other two tables? Is the data retrieval as it would be for any other table or is it different since it is a table that we create dynamically?
So in other words, I use your code to create the merged table and then I can get read out values straightaway in a normal fashion
Violet_82 89 Posting Whiz in Training
Hi thanks, that's great. I'm not terribly familiar with SQL, so I'm looking into this PIVOT and finding it slightly difficult to visualize this new table, not to mention the SQL query which is a tad unfamiliar to me. OK, let's look at them. Does the new table (just so I can visualize it, that's all) look like this:
About the query, in the first bit you're selecting Rent, Car, Food and Bills but from which table? If I read it correctly with all the parentesis, it looks like you're selecting from "sq"? Then PIVOT
statement which we said creates the table and then I seem to understand, you sum up all the Food, Car, Bills and Rent values, correct?
I looked this up WHERE(DATEPART(month, dbo.expenses.Date) = 1)
so you are essentially getting the month part of the date, but what does '=1' mean?
Finally, that "AS pt", does it mean that you're creating an extra column called pt?
Also, one more question: would it be easier to do what I thought I could do above, adding a filter to the SQL retrieval statement to say if the ExpenseId = 1 or 2 or 3 or 4 and take it from there, or is this a silly approach? I ask just so I understand really, if you excuse my ignorance in SQL :- )!
Violet_82 89 Posting Whiz in Training
Hi guys, I'm in a bit of a situation here and I was wondering if anybody has any suggestion. Basically, I need to retrieve some data from 2 or perhaps 1 SQL table (that's what I'd like you to help me finding out).
OK, here are my two tables (sure you've seen them already):
expenses table (which is updated by the application):
expensesCode (whose data never change):
Right, so I have to get the data out of the tables. I'd do what I normally do, but here there is a problem: this is how my application for presenting the data looks like:
So I have to determine which expense is what when I retrieve the data because the first table (expenses) contains the relevant numerical data I'm interested in but it has ints
in place of the type of expense. So, how do I proceed? I'd use a normal SELECT
statement to retrieve the data but it's not clear to me how, when and if I should determine what's what (is it a food, car, bill or rent expense?) Do I have to access both tables or is it just a matter of filtering the data in the expenses table, something like "is expensesID value 4? If so it's food so get the cost and display it in the food field"?
Violet_82 89 Posting Whiz in Training
I can live with tha because I don't want to mess it stuff around again :-)
thanks for all your help, much appreciated!
Violet_82 89 Posting Whiz in Training
OK great, thanks for all your help and patient explanations, much appreciate it. By the way I had a look at the book you suggested, it looks pretty good, will probably get that!
Violet_82 89 Posting Whiz in Training
Fab, thanks and I take I can save that in a variable to then reuse if I need to, something like string text = Response.Write(Request.Form["myHiddenField"]);
Violet_82 89 Posting Whiz in Training
No problem. Yep I have 2 books on ASP.NET (I started with 3.5 and now have 4.5) but none of them mentioned anything about sessions...that's why I asked about an online tutorial :-).
Anyway, can I ask you a cheeky question still about states? I've read that you could use a bunch of things to achieve what we have done now, even hidden fields. Now, in theory, would I be able to get the same results if I had a hidden field where I stored the ID of the radio button clicked on, then I'd use the switch statement as I did in my code and then copy the expenseID which is the variable that holds the int (1,2,3 or 4 depending on the ID) in another hidden field and go on as normal? Would that work? Funny thing is, I did use a hidden field but only to store the ID of the radio button, not to store expenseID which kept going back to 0 at each new session. Here is some code and pseudo code to illustrate that:
protected void CheckedChanged(object sender, EventArgs e)
{
amount.Visible = true;//showamount info on page load
/*find out the id of the selected button*/
RadioButton buttonId = sender as RadioButton;//cast sender as button
radioButtonId = radioButtonID.Value = buttonId.ID;//select the ID and copy it into hidden field radioButtonId
switch (radioButtonId)
{
case "rent":
expenseID = 1;
break;
case "car":
expenseID = 2;
break;
case "bills":
expenseID = 3;
break;
case "food": …
Violet_82 89 Posting Whiz in Training
oops, maybe you didn't see the previous post : -), session must have a capital S and not small, that's why I got the errors
Violet_82 89 Posting Whiz in Training
that seems to be the problem, things work now. Thanks a lot for your help. Can I ask you, are you aware of any good tutorial on sessions and state management I can look at? The topic is interesting and I think it will be useful for me to learn more. I couldn't really find a good tutorial unfortunately, not a good one that I could understand, some were really way too advanced for me.
thanks
Violet_82 89 Posting Whiz in Training
Wait wait....'session' should have a capital S, I think
Violet_82 89 Posting Whiz in Training
Just the ones I mentioned:
The name 'session' doesn't exist in the current context
Screenshot attached (ignore the add(string,object) warnings please):
http://s24.postimg.org/j9ebkpoyt/Session_Error.jpg
Violet_82 89 Posting Whiz in Training
um, still no joy, same error, or I should say errors, as there are 3 of them:
the first one in the checkedChanged, towards the end of it session["expenseID"] = expenseID;
(note that I have added the code you suggested at the top of the method):
protected void CheckedChanged(object sender, EventArgs e)
{
amount.Visible = true;//showamount info on page load
//adding the session
if (Session["expenseID"] == null)
Session.Add("expenseID", expenseID);
/*find out the id of the selected button*/
RadioButton buttonId = sender as RadioButton;//cast sender as button
// radioButtonID.Text = buttonId.ID;//select the ID
radioButtonId = radioButtonID.Value = buttonId.ID;//select the ID
switch (radioButtonId)
{
case "rent":
expenseID = 1;
break;
case "car":
expenseID = 2;
break;
case "bills":
expenseID = 3;
break;
case "food":
expenseID = 4;
break;
}
session["expenseID"] = expenseID;
}
The second and third errors are in the submitForm method, when I insert the data in the SQL table sqlCmd.Parameters.Add("@expenseid", session["expenseID"]);
and when I remove the session session.Remove("expenseID");
:
protected void submitForm(object sender, EventArgs e){
hookUp = new SqlConnection("Server=localhost\\SqlExpress;Database=Applications;" + "Integrated Security=True");
strInsert = "INSERT INTO expenses(Date,ExpenseId,Cost,Comment) VALUES (@date,@expenseid,@cost,@comment)";
sqlCmd = new SqlCommand(strInsert, hookUp);
// sqlCmd.Parameters.Add("@date", DateTime.Now.ToString("dd/MM/yyyy"));
sqlCmd.Parameters.Add("@date", DateTime.Now);
sqlCmd.Parameters.Add("@expenseid", session["expenseID"]);
sqlCmd.Parameters.Add("@cost", Convert.ToDecimal(billValue.Text));
sqlCmd.Parameters.Add("@comment", expenseComment.Value);
hookUp.Open();
sqlCmd.ExecuteNonQuery();
hookUp.Close();
session.Remove("expenseID");
initForm();//re Initialize form after submission
}
Could I be that I placed them in the wrong place?
Violet_82 89 Posting Whiz in Training
I think I can definitely live with that, no problem. There is only one thing.. now I have two boot menus, the first one whish was there before listing about 4-5 entries (I don't have a screenshot with me but it looks pretty similar to this except with different version of OS's and 2 entries for WIndows http://s7.postimg.org/vt1yzjquz/dual_boot_boot_loader.jpg) and if I select windows from here, as I used to do before I get an error, a pretty nasty one saying that ntoskrnl.exe is corrupted http://s16.postimg.org/nhvssoj2d/windows_Error.jpg
But if I instead select the second windows entry I ended up onto another boot screen, this one http://s14.postimg.org/4d4jcboip/enu.jpg and here I can start windows OK. Weird.
Violet_82 89 Posting Whiz in Training
Um, I get an error unfortunately
The name 'session' doesn't exist in the current context
The using statements seem all there, but on the net people with the same error are saying that it may be that somehow my class is not inheriting from Page...but surely if that was the case I would have sen the error before...
Violet_82 89 Posting Whiz in Training
Hi, thanks, sorry I've been reading a bit about state management and sessions, interesting stuff, never heard of that before : -), but no surprise here as I'm still at the very beginning!
I seem to understand that, as I've seen from the examples, the session variable is not declared? is that possible? But from what you're saying, your copying an existing string variable (expenseID) in a session variable (which doesn't have any type?)session["expenseID"] = expenseID;
.
So if I understand everything correctly my code should look like this:
public partial class Home : System.Web.UI.Page
{
private int expenseID;
...
protected void CheckedChanged(object sender, EventArgs e)
{
amount.Visible = true;//showamount info on page load
/*find out the id of the selected button*/
RadioButton buttonId = sender as RadioButton;//cast sender as button
// radioButtonID.Text = buttonId.ID;//select the ID
radioButtonId = radioButtonID.Value = buttonId.ID;//select the ID
switch (radioButtonId)
{
case "rent":
expenseID = 1;
break;
case "car":
expenseID = 2;
break;
case "bills":
expenseID = 3;
break;
case "food":
expenseID = 4;
break;
}
session["expenseID"] = expenseID;
}
protected void submitForm(object sender, EventArgs e){
...
sqlCmd.Parameters.Add("@expenseid", session["expenseID"]);
sqlCmd.Parameters.Add("@cost", Convert.ToDecimal(billValue.Text));
sqlCmd.Parameters.Add("@comment", expenseComment.Value);
hookUp.Open();
sqlCmd.ExecuteNonQuery();
hookUp.Close();
session.Remove("expenseID");
}
Violet_82 89 Posting Whiz in Training
Right, the expenseID is indeed 0 inside submitForm. OK so the choices I have are 2:
1)Use Request.Form
, which I've never used (or heard of), but happy to investigate if you think it's a good idea. If I go with this option I will have to move the switch inside the submitForm()
method and hopefully cook something up with the Request.Form
which will allow me to get around the problem described above
2)session variable: never heard of that before either, but again, more than happy to investigate: this option will allow me to keep things as they are and get around the above issue with expenseID being 0 and not keeping its value.
As I don't know much about c# to decide, which one do you think is better? I suspect the 2nd one will involve less changes? So is it just a matter of storing the value currently in expenseID in a session variable and use it to push the content onto the database?
Violet_82 89 Posting Whiz in Training
Ah, one thing though: if I move the switch statement, it won't work will it, because I'm relying on the sender
which in the CheckedChanged method will work but in the submitForm, it won't "contain" (if that's the right way to say) the radio button anymore, so I can't get its ID. Correct? I'll add a breakpoint and see if I can look at the value of expenseID as you said
Violet_82 89 Posting Whiz in Training
Thanks. I did put a breakpoint there and the values returned are OK. So I'll then get the ID and change the value of expenseID accordingly inside the submitForm function (I guess it's just a matter of moving the switch statement). But there is one thing that bugs me though: if all these problems are caused by the above, shouldn't I get a different type of error rather than
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_expenses_ToexpenseCode". The conflict occurred in database "Applications", table "dbo.expenseCode", column 'Id'.
The statement has been terminated.