how to make display to console text - console

I am beginner at C# and I am trying like welcome message like as
Console.WriteLine(" Enter Your Name:");
Console.Write(new string(' ', Console.WindowWidth));
Console.Write("first name:");
string name = Console.ReadLine();
I need after entering the first name to clear the window and go for next output like:
Console.Write("last name:");
string lastname = Console.ReadLine();
How do I do this?

You can clear the console window with
Console.Clear()
If you put this in between your two blocks of code you should have what you need.
You can also make a blank line by doing
Console.Writeline();
Instead of
Console.Write(new string(' ', Console.WindowWidth));

Did you try this...
Console.WriteLine(" Enter Your Name:");
Console.WriteLine("first name:");
string firstName = Console.ReadLine();
Console.WriteLine("last name:");
string lastName = Console.ReadLine();
Please feel free to use Console.Clear() to clear the console.
You may further print/see the values using
Consile.WriteLine("Your First Name is " + firstName + " and last name is " + lastName);

Related

Getting unspecified error while Reading CSV file using OleDbDataAdapter

Update 1 : I think schema.ini is incorrect. Please refer to below question.
The file (dsTextFile) has just one row of data but record count is zero. So it means it is not reading at all. This is with removing FMT altogether or with Delimi. I still get error if FMT is fixed though. So, how do I create SCHEMA.ini or make sure schema.ini is correct?
private bool LoadTextFile(string textFilePath, out string errorInfo) {
errorInfo = String.Empty;
try {
string textFileFolder = (new System.IO.FileInfo(textFilePath)).DirectoryName;
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Fixed\";";
OleDbConnection textConnection = new OleDbConnection(textConnectionString);
textConnection.Open();
textFilePath = (new System.IO.FileInfo(textFilePath)).Name;
string selectCommand = "select * from " + textFilePath;
OleDbCommand textOpenCommand = new OleDbCommand(selectCommand);
textOpenCommand.Connection = textConnection;
OleDbDataAdapter textDataAdapter = new OleDbDataAdapter(textOpenCommand);
Console.WriteLine("Trying to set textDataAdapter");
int rows = textDataAdapter.Fill(dsTextFile); //This is where error is coming.
Console.WriteLine("detail rows being filled");
textConnection.Close();
textConnection.Dispose();
return true;
}
catch (Exception ex_load_text_file) {
Console.WriteLine("error in loadTextFile is " + ex_load_text_file.Message.ToString());
return false;
}
}
Please find the above source where I am getting error 'UnSpecified" for below line.
UnSpecified Error is coming at below line
int rows = textDataAdapter.Fill(dsTextFile)
What could be the issue? I have checked user permissions on c:\windows\temp but no success.
This is a console application and I have even tried to add below code in app.config but no success yet.
<system.web>
<identity imperonate = "false"/> </system.web>
This is a legacy application but needs to run on windows server 2012 setup.
You are using FMT=Fixed on the connection string, if you are not using a schema.ini, change it to FMT=Delimited and it will work.
i.e.:
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Delimited\";";

DynamicSQL with ASP.NET Parameters not being set

I use this dynamicSQL piece of code.
Problem is, the #ID_USER and #SEARCH stays raw in the SQL query when I check the cmd.CommandText value at runtime, it reads
"SELECT Comment FROM Comments WHERE UserId = #ID_USER AND Comment like '% #SEARCH %'"
so the syntax is correct and the cmd.Parameters ResultView .SqlValuein VS2012 gives me the correct input values for #USER_ID and #SEARCH
Thanks.
{
List<string> searchResults = new List<string>();
//Get current user from default membership provider
MembershipUser user = Membership.Provider.GetUser(HttpContext.User.Identity.Name, true);
if (user != null)
{
if (!string.IsNullOrEmpty(searchData))
{
// SqlCommand cmd = new SqlCommand("Select Comment from Comments where UserId = '" + user.ProviderUserKey + "' and Comment like '%" + searchData + "%'", _dbConnection);
/**********************************************/
_dbConnection.Open();
const string QUERY =
#"SELECT Comment" +
#" FROM Comments" +
#" WHERE UserId = #ID_USER" +
#" AND Comment like '% #SEARCH %'";
var cmd = new SqlCommand(QUERY, _dbConnection);
cmd.Parameters.AddWithValue("#ID_USER", user.ProviderUserKey.ToString());
cmd.Parameters.AddWithValue("#SEARCH", searchData.ToString());
/**********************************************/
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
searchResults.Add(rd.GetString(0));
}
rd.Close();
_dbConnection.Close();
}
}
return View(searchResults);
}
No, it is correct that the parameters remain in the command text.
This is because what is actually passed to the server is something like the below:
exec sp_executesql N'SELECT Comment FROM Comments WHERE UserId = #ID_USER AND Comment like ''% + #SEARCH %''',
N'#ID_USER int,#SEARCH nvarchar(max)',
#ID_USER=1,
#SEARCH=N'some search text';
So your parameters remain in place even when it is passed to the server. This is why you can still see them in your command text.
As an aside your query will not work as expected, in this line:
AND Comment like '% #SEARCH %'
You are looking for where Comment actually contains "#Search" rather than the value assigned to the parameter. What you need is:
AND Comment like '%' + #SEARCH + '%'
Another, slightly unrelated point is that there is no need to, nor is it useful to reuse SqlConnections. Define a new one for each connection. .NET is smart enough to reuse connections by pooling them, don't reinvent the wheel. Also use using blocks to ensure your disposable class are disposed of:
So I would make your whole reader block as follows:
string sql = "SELECT Comment FROM Comments WHERE UserID = #ID_USER AND Comment LIKE '%' + #Search + '%'";
using (var connection = new SqlConnection(YourConnectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#ID_USER", user.ProviderUserKey.ToString());
command.Parameters.AddWithValue("#SEARCH", searchData.ToString());
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
searchResults.Add(rd.GetString(0));
}
}
}

Is it possible to append text to a textbox using a for each statement?

I am using the code below to read through each record and get the data. Is there a way I can append the text eachtime to my summarytextbox so it will show all the records/add them one by one?
Dim str As String = Session("List")
For Each s As String In str.Split(","c)
SummaryTextBox.Text = Session("FirstName") & " " & Session("LastName")
Next
I like to use the StringBuilder:
Dim str As String = Session("List")
Dim sb As New Text.StringBuilder()
For Each s In str.Split(","c)
sb.Append(s)
Next
SummaryTextBox.Text = sb.ToString()
... and of course, you can use whatever format you want to display the concatenated results.
EDIT: Like Tim alluded to, I'm not sure what the difference between the List and FirstName and LastName session variables, so I'm just appending the s until further clarification is made by the OP.
Yes.
Dim str As String = Session("List")
For Each s As String In str.Split(","c)
SummaryTextBox.Text &= Session("FirstName") & " " & Session("LastName") & ", "
Next
I'm not sure how that list is related to the firstname and lastname. However, this might give you an idea:
Dim firstName = DirectCast(Session("FirstName"), String)
Dim lastName = DirectCast(Session("LastName"), String)
Dim query = From s In DirectCast(Session("List"), String).Split(","c)
Select String.Format("{0} {1}: {2}", firstName, lastName, s)
SummaryTextBox.Text = String.Join(Environment.NewLine, query)
Stringbuilder is the preferred method. String is immutable, therefor every time a string is appended with & " ", a new string is created. StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed on it.

Increment a database value using asp.net

I am working on a project - online movie ticketing system....
In this when the user enters the number of seats he wants to book, he goes to payment page. On click of payment button, how can I decrement the number of seats entered by the user in SQL Server.
SqlConnection con;
SqlCommand cmd;
private void update()
{
string a, b;
int c;
con = new SqlConnection("server=.;uid=sa;pwd=mayank;database=movie");
a = Session["timings"].ToString();
b = Session["seats"].ToString();
c = Convert.ToInt32(b);
con.Open();
cmd = new SqlCommand("update bodyguard set silver_class = silver_class ' " + - c + " 'where timings = ' " + a + "' ", con);
cmd.ExecuteNonQuery();
con.Close();
}
With this code it is raising an exception....so please help me out.
Your SQL command is wrong, what you produce is this:
update bodyguard set silver_class = silver_class ' -[valueC] 'where timings = ' [valueA]'
You forgot a space before where for example, and I am not sure how the silver_class part is supposed to look, because it's not clear what you are trying to achieve there.
You had some single quotes around your integer value. try this
"update bodyguard set silver_class = (silver_class - " + c + ") where timings = '" + a + "'"
A little advice, you should use a try{}catch{} blocks to handle potential errors in your code. When you convert a number with Convert.toInt32(), you should try to catch a FormatException. And from con.open() to con.close you can try to catch the SQLException
Don't use concatenated strings to create your SQL statment, its really bad form. Do it this way:
cmd = new SqlCommand("update bodyguard set silver_class = silver_class - #c where timings = #a", con);
cmd.Parameters.AddWithValue("#c", c);
cmd.Parameters.AddWithValue( "#", a);
I recommend Parameterized Query instead of string concatenation which is vulnerable to SQL Injection. And I suggest that you should use Stored Procedure instead of Inline SQL.

ATT00006.dat file autmatically attached in mail attachment

I have a page that have fileupload control, on the submission of the form, when the fileupload control has file, file is sent via attachment in a mail and working absulutly fine, but when the fileupload control does not have file, ATT00006.dat file is automatically sent via email attachment.
Reference URL: http://nextech.pk/Enquiry.aspx?Enq=cu
Advance Thanks for any help
Edit -- Code:
hpf = fup1.PostedFile;
String toEmail = "test#hotmail.com";
String fromEmail = "mailer#hotmail.com";
MailMessage objMail = new MailMessage(fromEmail, toEmail);
objMail.IsBodyHtml = true;
StringBuilder MailBody = new StringBuilder();
MailBody.Append("<html><head></head><body> <br>");
MailBody.Append("<br>" + "An enquiry is filed <br><br>");
MailBody.Append("<strong><u>Enquirer Information</u></strong>" + "<br><br>");
MailBody.Append("<strong>Contact Name:</strong> " + txtFirstName.Text + "<br>");
MailBody.Append("<strong>Email:</strong> " + txtEmail.Text + "<br>");
MailBody.Append("<strong>Institute:</strong> " + txtInstitute.Text + "<br>");
MailBody.Append("<strong>Phone #:</strong> " + txtPhone.Text + "<br>");
MailBody.Append("<br><strong>Description:</strong><br>         " + txtEnquiry.Text + "<br>");
if (hpf != null)
{
MailBody.Append("<br>" + "This email also contains an attachment:- <Strong>(" + hpf.FileName + ")</Strong><br>");
}
MailBody.Append("</body></html>");
objMail.Body = MailBody.ToString();
if (hpf != null)
{
System.IO.Stream inputStream = hpf.InputStream;
String fileName = hpf.FileName;
Attachment attach = new Attachment(inputStream, fileName);
objMail.Attachments.Add(attach);
}
SmtpClient SmtpClnt = new SmtpClient();
SmtpClnt.Send(objMail);
I don't know if you ever got an answer to this, but I've recently studied the problem in detail. The problem occurs because you did not provide an explicit name for the attachment. ASP.NET will always attach as .DAT unless the name is explicitly defined.
The problem is that people assume ASP.NET will use the Filename as the attachment name, which doesn't happen!
In your code, you should create an instance of the attachment, then provide the name explicitly using the FileUpload.FileName property:
Dim att As New System.Net.Mail.Attachment(fu.PostedFile.InputStream, System.Net.Mime.MediaTypeNames.Application.Octet) ' use Octet for binary files '
att.Name = fu.FileName ' get the file name and type automatically '
mm.Attachments.Add(att)
A full explanation of ASP.NET attaching .DAT files is available here
Its a mis-match in the attachment type that the system doesn't understand. Please post your code and what you do when there is not file as an attachment.
I think the mail server you are using (or antivirus software used by the mail server) is automatically adding this file.
Does the file in question contain anything, or is it empty?

Resources