Wait for input from the user in C# - c#-4.0

How can I make a program stop in order to insert inputs, such as username and password,
"UserId=te; PWD=t57; database=ph3;");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
MySqlConnection conDatabase = new MySqlConnection("Data Source=localhost;" +
"Persist Security Info=yes;" +
"UserId=te; PWD=t57; database=ph3;");
conDatabase.Open();
// MySqlCommand cmdDatabase = new MySqlCommand("DROP TABLE IF EXISTS `q_mem_sur`; create table q_mem_sur as SELECT Count(*) As rowa, member.Ssurname, Sum(Case When ((member.status = '1')) Then 1 Else 0 End) As Status11 From member Group By member.Ssurname Order By rowa Desc;", conDatabase);
string[] arr = new string[12];
arr[0] = "UPDATE `member` SET `amphurecode`= SUBSTRING(member.own,3,4)";
arr[1] = "UPDATE `member` SET `provincecode`= SUBSTRING(member.own,3,2)";
arr[2] = "DROP TABLE IF EXISTS `q_mem_tim`; create table q_mem_tim as SELECT member.idmember, member.own, member.provincecode, province.PROVINCE_NAME, member.amphurecode, amphur.AMPHUR_NAME, member.novote, member.Sname, member.Ssurname, member.Hno, member.Moo, member.Sex, member.tambol, member.dateofbirth, member.migratedate, Year( Current_Date( ) ) - Year( member.dateofbirth ) AS y, DATEDIFF('2011-08-01',(migratedate)) AS d FROM member LEFT JOIN amphur ON ( member.amphurecode = amphur.AMPHUR_CODE ) LEFT JOIN province ON member.provincecode = province.PROVINCE_CODE";
arr[10] = "UPDATE q_mem_birth SET agec = CASE WHEN y < 10 THEN '¿' WHEN y > 10 and y < 20 and Sex='¿' THEN '¿¿' WHEN y > 10 and y < 20 and Sex='¿' THEN '¿¿' ELSE '¿¿' END";
arr[11] = "drop table if exists q_mem_birth; create table q_mem_birth as SELECT q_mem_tim.idmember,q_mem_tim.own,q_mem_tim.PROVINCE_NAME,q_mem_tim.AMPHUR_NAME,q_mem_tim.novote,q_mem_tim.Sname,q_mem_tim.Ssurname,q_mem_tim.Hno,q_mem_tim.Moo,q_mem_tim.Sex,q_mem_tim.tambol,q_mem_tim.dateofbirth,q_mem_tim.migratedate,q_mem_tim.y,q_mem_tim.d,q_mem_tim.agec FROM q_mem_tim where q_mem_tim.dateofbirth is not null and q_mem_tim.dateofbirth != '00000000' and day(q_mem_tim.dateofbirth) != '00' and day(q_mem_tim.dateofbirth) > 0 and day(q_mem_tim.dateofbirth) < 11 and month(q_mem_tim.dateofbirth) != '00' and month(q_mem_tim.dateofbirth) > 8 and month(q_mem_tim.dateofbirth) < 10 order by tambol,Moo, month(dateofbirth),day(dateofbirth) ";
foreach (string s in arr)
{
Console.WriteLine(s);
MySqlCommand cmdDbase = new MySqlCommand((s), conDatabase);
cmdDbase.CommandTimeout = 500;
cmdDbase.ExecuteNonQuery();
}
conDatabase.Close();
}
}
}

You probably want to use the Console.ReadLine(); method. For more details, see Console.ReadLine Method (MSDN).
Something like this:
Console.WriteLine("Enter username");
string uname=Console.ReadLine();

Related

Copying a MySQL search query into a Data table

I am having trouble getting the data inside a DataTable into a DataGridView. I found code in Visual Basic and tried translating it into Visual C++.
String^ cninfo = "server=localhost; port=3306; username=test; password=Lalala123; database=turismo";
MySqlConnection^ cn = gcnew MySqlConnection;
MySqlDataAdapter^ cmdadp;
DataTable^ Table = gcnew DataTable;
String^ search = searchtxt->Text;
int^ rowposition = 0;
String^ id_searchQuery = ("select * from clientes where CLIENT_ID = #search;");
String^ name_searchQuery = ("select * from clientes where FIRST_NAME like '%#search%';");
String^ lastname_searchQuery = ("select * from clientes where LAST_NAME like '%#search%';");
String^ origin_searchQuery = ("select * from clientes where COUNTRY_ORIGIN like '%#search%';");
if (radid /*Radbutton for id_searchQuery*/->Checked == true) {
cn->ConnectionString = cninfo;
cn->Open();
//defining parameters for the search query
MySqlCommand^ searchCmd = gcnew MySqlCommand(id_searchQuery, cn);
searchCmd->CommandType = CommandType::Text;
searchCmd->Parameters->AddWithValue("#search", search);
//filling the DataTable with MySqlDataAdapter
cmdadp->Fill(Table);
//counting each DataTale line to enter it into a DataGridView with a while function
while (rowposition < Table->Rows->Count) {
DataRow^ MyDataRow = Table->Rows(rowposition);
}
cn->Close();
}
On (rowposition < Table->Rows->Count) { i get the "<" highlighted and i get
No operator "<" matches these commands
And on DataRow^ MyDataRow = Table->Rows(rowposition); i get highlighted "Table" and i get
call of an object of a handle type without apropriate operator () or conversion functions to pointer-to-function type
What happens if you just declare rowposition as an int rather than int^?
Table->Rows is of type DataRowCollection Class. Try accessing the row using the Item property array notation, e.g., Table->Rows[rowposition]
answered by #Phil Brubaker

OutOfMemory exception in dataGridView

I am using 2 datagridview to see the data in a windows form application.
The first DGV show the products according to the ids passed to them.
On click of VIEW as of my one column in DGV1, it passes the product id to and fetch the complete records from database and show the records to the other DGV2.
this is my code:
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == (Object)"View")
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int prod_id = Convert.ToInt16(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
dataGridView2.DataSource = null;
dataGridView2.Rows.Clear();
retFindProducts = new MySqlCommand("SELECT DISTINCT tf_history.thefind_id, tf_product.product_id, tf_product.`name`, tf_product.product_url, tf_product.image_tpm, tf_product.image_thefind, tf_product.image_accuracy, (SELECT MIN(tf_h.price) FROM tf_history AS tf_h WHERE tf_h.thefind_id = tf_history.thefind_id) as price, oc_product.price AS priceTPM FROM tf_product LEFT JOIN tf_history ON tf_product.product_id = tf_history.product_id AND tf_product.thefind_id = tf_history.thefind_id LEFT JOIN oc_product ON tf_product.product_id = oc_product.product_id WHERE tf_product.product_id = #product_id", con);
historyData = new MySqlCommand("SELECT price, date from tf_history WHERE thefind_id = #thefind_id", con);
retFindProducts.CommandTimeout = 300;
historyData.CommandTimeout = 300;
retFindProducts.Parameters.AddWithValue("#product_id", prod_id);
dr = retFindProducts.ExecuteReader();
retFindProducts.Parameters.Clear();
while (dr.Read())
{
dataGridView2.Rows.Add();
long fI = Convert.ToInt64(dr["thefind_id"]);
//if (!findId.Exists(p => p.Item1 == fI))
findId.Add(new Tuple<long>(fI));
decimal findPrice = Convert.ToDecimal(dr["price"]);
decimal tpmPrice = Convert.ToDecimal(dr["priceTPM"]);
if (findPrice > tpmPrice)
{
dataGridView2.Rows[cnt].Cells[4].Style.ForeColor = Color.Green;
dataGridView2.Rows[cnt].Cells[4].Style.Font = new Font(dataGridView2.DefaultCellStyle.Font.FontFamily, 9, FontStyle.Regular);
}
else if (findPrice < tpmPrice)
{
dataGridView2.Rows[cnt].Cells[4].Style.ForeColor = Color.Red;
dataGridView2.Rows[cnt].Cells[4].Style.Font = new Font(dataGridView2.DefaultCellStyle.Font.FontFamily, 10, FontStyle.Bold);
}
dataGridView2.Rows[cnt].Cells[0].Value = Image.FromFile(dr["image_tpm"].ToString());
dataGridView2.Rows[cnt].Cells[1].Value = Image.FromFile(dr["image_thefind"].ToString());
dataGridView2.Rows[cnt].Cells[2].Value = dr["name"].ToString();
dataGridView2.Rows[cnt].Cells[3].Value = dr["product_url"].ToString();
dataGridView2.Rows[cnt].Cells[4].Value = dr["price"].ToString();
dataGridView2.Rows[cnt].Cells[5].Value = dr["image_accuracy"].ToString();
cnt++;
}
foreach (DataGridViewRow row in dataGridView2.Rows)
{
row.Height = 60;
}
dr.Close();
}
Now, the outofexception does not comes on first time of the click, but it comes after 5-8 clicks on the VIEW column of DGV1.
How can i clear up the memory?
Try to dispose and create datagridview manually. The Code can be like this:
dgv.Dispose();
dgv = new DataGridView();
DataGridViewColumn col1 = new DataGridViewTextBoxColumn();
DataGridViewColumn col2 = new DataGridViewTextBoxColumn();
DataGridViewColumn col3 = new DataGridViewTextBoxColumn();
DataGridViewColumn col4 = new DataGridViewTextBoxColumn();
DataGridViewColumn col5 = new DataGridViewTextBoxColumn();
col1.HeaderText = "COl1";
col2.HeaderText = "COl2";
col3.HeaderText = "COl3";
col4.HeaderText = "COl4";
col5.HeaderText = "COl5";
dgv = new System.Windows.Forms.DataGridView();
dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dgv.Location = new System.Drawing.Point(59, 101);
dgv.Name = "dataGridView1";
dgv.Size = new System.Drawing.Size(240, 150);
dgv.TabIndex = 2;
dgv.Columns.Add(col1);
dgv.Columns.Add(col2);
dgv.Columns.Add(col3);
dgv.Columns.Add(col4);
dgv.Columns.Add(col5);
this.Controls.Add(dgv);
dgv.ColumnCount = 5;
dgv.Visible = true;

Columns get combined in .Net Column charts

I am working in .Net Charts. I am trying to generate a Column chart. I am having two rows in my dataset. Here is my code.
DataTable DT1 = new DataTable();
DT1 = chartViewSummaryList;
DataView DV = DT1.DefaultView;
DV.ToTable(false, new string[] { "REVENUE_TOTAL", "WEEK_END_DATE" });
DataSet ds = new DataSet();
ds.Tables.Add(DT1.Copy());
ds.Tables[0].Rows[0]["MARGIN"] = "0";
ds.Tables[0].Rows[0]["REVENUE_TOTAL"] = "3776169.61";
ds.Tables[0].Rows[0]["MARGIN_PCT"] = "0";
ds.Tables[0].Rows[0]["VISIT_REVENUE_AVG"] = "29.28";
ds.Tables[0].Rows[0]["VISIT_COUNT"] = "614041";
ds.Tables[0].Rows[0]["REVENUE_SALE"] = "1840387.18";
ds.Tables[0].Rows[0]["REVENUE_REGULAR"] = "1935782.43";
ds.Tables[0].Rows[0]["WEEK_END_DATE"] = "1/1/2012 12:00:00 AM";
ds.Tables[0].Rows.Add();
ds.Tables[0].Rows[1]["MARGIN"] = "1";
ds.Tables[0].Rows[1]["REVENUE_TOTAL"] = "5776169.61";
ds.Tables[0].Rows[1]["MARGIN_PCT"] = "0";
ds.Tables[0].Rows[1]["VISIT_REVENUE_AVG"] = "49.28";
ds.Tables[0].Rows[1]["VISIT_COUNT"] = "814041";
ds.Tables[0].Rows[1]["REVENUE_SALE"] = "3840387.18";
ds.Tables[0].Rows[1]["REVENUE_REGULAR"] = "3935782.43";
ds.Tables[0].Rows[1]["WEEK_END_DATE"] = "1/1/2012 12:00:00 AM";
Chart1.DataSource = ds;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Chart1.Titles.Add(storeLevelCaption).Font = new System.Drawing.Font("Verdana", 11, FontStyle.Bold);
Chart1.ChartAreas["ChartArea1"].AxisX.Title = "Weeks";
Chart1.ChartAreas["ChartArea1"].AxisX.TitleFont = new System.Drawing.Font("Verdana", 10, FontStyle.Bold);
Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Font = new Font(new FontFamily("Verdana"), 7.25F, FontStyle.Bold);
string series = "Series" + i;
Chart1.Series.Add(series);
Chart1.Series[series].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Column;
Chart1.Series[series].XValueMember = "WEEK_END_DATE";
Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
Color color = System.Drawing.ColorTranslator.FromHtml("#B93B8F");
Chart1.Series[series].Color = color;
Chart1.ChartAreas["ChartArea1"].AxisY.Title = "Total Revenue";
Chart1.ChartAreas["ChartArea1"].AxisY.TitleFont = new System.Drawing.Font("Verdana", 10, FontStyle.Bold);
Chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Font = new Font(new FontFamily("Verdana"), 7.25F, FontStyle.Bold);
Chart1.Series[series].YValueMembers = "REVENUE_TOTAL";
Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
Chart1.Series[series].ToolTip = "Total Revenue ($) , " + ds.Tables[0].Rows[i]["WEEK_END_DATE"].ToString() + " , " + ds.Tables[0].Rows[i]["REVENUE_TOTAL"].ToString();
Chart1.Series[series].Font = new Font(new FontFamily("Verdana"), 7.25F, FontStyle.Bold);
//Chart1.Series[series].Name = "Total Revenue";
}
Chart1.ChartAreas[0].AxisY.Interval = 1;
Chart1.DataBind();
I am getting the chart, where two column combined together and displayed as one column. Where i had gone wrong...
I can't reproduce your problem using the WinForm charting assemblies. However you may want to try using distinct dates since they are bound to your X values.
ds.Tables[0].Rows[0]["WEEK_END_DATE"] = "1/1/2012 12:00:00 AM";
ds.Tables[0].Rows[1]["WEEK_END_DATE"] = "8/1/2012 12:00:00 AM"; // a different date
FYI, I changed your code minimaly
// DT1 = chartViewSummaryList;
// replace unknown object with this code
DT1.Columns.Add(new DataColumn("MARGIN"));
DT1.Columns.Add(new DataColumn("REVENUE_TOTAL"));
DT1.Columns.Add(new DataColumn("MARGIN_PCT"));
DT1.Columns.Add(new DataColumn("VISIT_REVENUE_AVG"));
DT1.Columns.Add(new DataColumn("VISIT_COUNT"));
DT1.Columns.Add(new DataColumn("REVENUE_SALE"));
DT1.Columns.Add(new DataColumn("REVENUE_REGULAR"));
DT1.Columns.Add(new DataColumn("WEEK_END_DATE"));
and also added a row manually
ds.Tables.Add(DT1.Copy());
ds.Tables[0].Rows.Add(); // Added this
and got two columns from your plotting code.

Why is the SqlDatasource I am using not returning a calculated value when the same query does in SQL server? C#.net 4.0

Query that works in Sql Server.
Declare #from datetime, #to datetime, #status int, #SupervisorID uniqueidentifier
SELECT #to = '09-12-2012', #from = '02-02-2012', #status = 0, #SupervisorID = '2EB087F0-A419-4421-861A-6EBDFED9449A'
select nums.date as DayOff, [RequestID], [EmployeeName], [AbsenceType], [AbsenceBundle], [DateRequested], [FirstDay], [LastDay], [ReturnDay], [SupervisorName], [DaysHoursDesc] as DaysAbsent, [Description], Hours from
(select dateadd(day, number, #from) as date
from
(select distinct number from Numbers
) num
where dateadd(day, number, #from) < #to) nums right outer join [AbsenceRequests].[dbo].[AbsenceRequestWithDescriptions] a on (DateDiff(Day, a.FirstDay, nums.date) >= 0 and DateDiff(Day, a.LastDay, nums.date) <=0)
where
(([SupervisorID] = #SupervisorID) or ([EmployeeID] = #SupervisorID)
or
([SupervisorID] in (select SupervisorID from Viewers where [viewerID] = #SupervisorID)))
and((#status = StatusID) or (#status = '0'))
order by SupervisorName, EmployeeName, FirstDay, Hours
Results I am getting from this query
2012-06-06 00:00:00.000 515 apptest1 Vacation 55 - Vacation 2012-06-28 00:00:00.000 2012-06-06 00:00:00.000 2012-06-07 00:00:00.000 2012-06-08 00:00:00.000 apptest3 16 Hour(s) Pending 16
SqlDatasource definition
<asp:SqlDataSource ID="EmployeeAbsenceRequestsSql" runat="server"
ConnectionString="<%$ ConnectionStrings:AbsenceRequestsConnectionString %>"
SelectCommand="
select nums.date as DayOff, [RequestID], [EmployeeName], [AbsenceType], [AbsenceBundle], [DateRequested], [FirstDay], [LastDay], [ReturnDay], [SupervisorName], [DaysHoursDesc] as DaysAbsent, [Description], Hours from
(select dateadd(day, number, #from) as date
from
(select distinct number from Numbers
) num
where dateadd(day, number, #from) < #to) nums right outer join [AbsenceRequests].[dbo].[AbsenceRequestWithDescriptions] a on (DateDiff(Day, a.FirstDay, nums.date) >= 0 and DateDiff(Day, a.LastDay, nums.date) <=0)
where
(([SupervisorID] = #SupervisorID) or ([EmployeeID] = #SupervisorID)
or
([SupervisorID] in (select SupervisorID from Viewers where [viewerID] = #SupervisorID)))
and ((#status = StatusID) or (#status = '0'))
order by SupervisorName, EmployeeName, FirstDay, Hours "
onselecting="EmployeeAbsenceRequestsSql_Selecting" >
<SelectParameters>
<asp:FormParameter DefaultValue=" " FormField="Fromtxt" Name="from" />
<asp:FormParameter DefaultValue=" " FormField="Totxt" Name="to" />
<asp:SessionParameter DefaultValue="""" Name="SupervisorID"
SessionField="EmployeeID" Type="Object" />
<asp:ControlParameter ControlID="Statusddl" DefaultValue="0" PropertyName="SelectedValue" Name="status" />
</SelectParameters>
</asp:SqlDataSource>
I am getting results with this when I call the select method of the datasource but the First Column DayOff is returning blank(I have verified this by setting a watch and checking the DataView). Below is the code that I am using to execute and read the results of the select query.
protected void RefreshTreeview()
{
this.EmployeeAbsenceRequestsSql.SelectParameters["from"].DefaultValue = SafeDateString(this.Fromtxt.Text);
this.EmployeeAbsenceRequestsSql.SelectParameters["to"].DefaultValue = SafeDateString(this.Totxt.Text);
DataView dv = (DataView) this.EmployeeAbsenceRequestsSql.Select(new DataSourceSelectArguments());
FillTreeView(dv);
}
private void FillTreeView(DataView dv)
{
TreeNode CurrentSupervisorNode = null;
TreeNode CurrentEmployeeNode = null;
foreach (DataRow row in dv.Table.Rows)
{
String SupervisorName = SafeString(row["SupervisorName"]);
if ((CurrentSupervisorNode == null) || !CurrentSupervisorNode.Text.Equals(SupervisorName))
{
CurrentSupervisorNode = new TreeNode(SupervisorName);
this.AbsencesTV.Nodes.Add(CurrentSupervisorNode);
CurrentEmployeeNode = null;
}
String EmployeeName = SafeString(row["EmployeeName"]);
if (CurrentEmployeeNode == null || !CurrentEmployeeNode.Text.Equals(EmployeeName))
{
CurrentEmployeeNode = new TreeNode(EmployeeName);
CurrentSupervisorNode.ChildNodes.Add(CurrentEmployeeNode);
}
String DayOffSummary = SafeString(row["DayOff"]) + " " + SafeString(row["AbsenceBundle"]) +" " + SafeString(row["Description"]);
CurrentEmployeeNode.ChildNodes.Add(new TreeNode(DayOffSummary));
}
}
Does anyone have any debugging advice or even better the answer to why this is happening?
Thanks to the great comment by simon I was able to find out that the default blank value for #to was being passed instead of a default I was trying to use. When I specified a date for the #to value I got the results I was expecting.

SubSonic SubSonic.SqlQuery & Dates

Does SubSonic.SqlQuery have a between/and for date ranges? If not, what would be the best way to get a range.
Try something like this:
SqlQuery query = new SqlQuery().From("Table")
.WhereExpression("Column")
.IsBetweenAnd("1/1/2008", "12/31/2008");
DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need
Another way to query with SubSonic.
TableCollection data = new TableCollection();
Query q = Table.CreateQuery()
.BETWEEN_AND("Column", "1/1/2008", "12/31/2008");
data.LoadAndCloseReader(q.ExecuteReader());
// loop through collection
Combined Northwind answer:
SqlQuery query = new SqlQuery().From("Orders")
.WhereExpression("OrderDate")
.IsBetweenAnd("1996-07-02", "1996-07-08");
DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need
#region PresentResultsReplaceResponseWriteWithConsole.WriteLineForConsoleApp
DataTable dt = dataSet.Tables[0];
Response.Write("<table>");
foreach ( DataRow dr in dt.Rows )
{
Response.Write("<tr>");
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write("<td>");
Response.Write(dr[i].ToString() + " ");
Response.Write("<td>");
} //eof for
Response.Write("</br>");
Response.Write("</tr>");
}
Response.Write("<table>");
#endregion PresentResultsReplaceResponseWriteWithConsole.WriteLineForConsoleApp

Resources