|
Por favor me ajude a resolver este problema amigos, ja tentei e não consigo.
using System;
using System.Globalization;
namespace _1002
{
class Program
{
static void Main(string[] args)
{
double R = Convert.ToDouble(Console.ReadLine());
double A = Math.PI * Math.Pow(R, R);
Console.WriteLine("A = " +A.ToString("F4",CultureInfo.InvariantCulture));
}
}
}
|
|
|
|
|
You can't "solve" an input string format problem: it says what it means: the user typed a value that cannot be interpreted as a valid double
You can prevent your app from crashing though:
double R;
while (true)
{
Console.Write("Please enter the radius of the circle :");
string input = Console.ReadLine();
if (double.TryParse(input, out R))
{
break;
}
Console.WriteLine($"\"{input}\" is not a valid number.");
}
double A = Math.PI * Math.Pow(R, R);
Console.WriteLine("A = ", A.ToString("F4",CultureInfo.InvariantCulture));
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
OriginalGriff wrote: You can't "solve" an input string format problem: it says what it means: the user typed a value that cannot be interpreted as a valid double This could be a culture issue. In many languages, the decimal point is a decimal comma; the point is used as the thousands separator.
The simple form of TryParse (or Convert.ToDouble) use the "Digit grouping symbol" and "Decimal symbol" specified in the regional settings. I am not familiar with Spanish conventions (and maybe in varies among Spanish speaking countries): If the local convention is to uses comma as a decimal symbol, but the regional settings have not been set properly to reflect this entering e.g. 1.234.567,89 will cause a format error.
Alternately, if regional settings are set to the local culture, but the user is accustomed to having to follow English conventions when working with computers, and enters 1,234,567.89, it will fail as well.
ToDouble and TryParse have overloads allowing the specification of a format, so that you can override the regional setting. If you want to accept either, you must scan the string: If both comma and point appears in the string, whichever appears first is likely to be the digit grouping symbol, not a decimal symbol. If only one of them appears, but multiple times, it is likely to be a digit grouping symbol.
If only one of them apppears, once, the format is ambiguous. You might guess that if the number of digits following the symbol is anything but 3, it is a decimal symbol. Or the context may indicate which is the most probable interpretation - usually, one value is more likely than thousand times larger or smaller. Or, if you in the same application activation have had other numbers input, containing both comma and point, you may assume that the same numeric format is used, in ambiguous cases.
Once you have determined the proper comma/point interpretation, you can call the TryParse function with the proper format indicator.
|
|
|
|
|
I made from a database get and created in HDD. But how to read by axAcroPDF1.src (Adobe Reader)
|
|
|
|
|
If it is on-disc, than you can simply launch the document as if it is an executable; the application associated with its extension would be used to open it.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
i'm new to C# and i'm just doin a test proj... i wonder why this happened?
using System;
namespace test_cs
{
class Program
{
static double calc(double n, double m)
{
return (n * m);
}
static void Main(string[] args)
{
Console.WriteLine("Welcome to calculator 1.0");
Console.Write("Enter calculations:");
double num1, num2;
char oper;
num1 = Convert.ToInt32(Console.Read());
oper = Convert.ToChar(Console.Read());
num2 = Convert.ToInt32(Console.Read());
Console.WriteLine("{0} {1} {2}", num1, oper, num2);
Console.ReadLine();
Console.ReadLine();
}
}
}
the result is:
Imgur: The magic of the Internet[^]
anybody can explain why?
also, i actually wanna make input streaming like C++
std::cin >> num1 >> oper >> num2;
but haven't know how to do it in C#
modified 14-Feb-20 12:25pm.
|
|
|
|
|
Simple: COnsole.Read fetches a single character from eth input types by the user, and you are converting that to an integer - but Convert changes type, not value. The character '3' is not the same a a number 3 - it's a character with a particular value within a character set, which is actually 51 in decimal: http://www.asciitable.com/
What I'd suggest is you read it as a line:
string input = Console.ReadLine(); And then "break" that into separate token strings:
Match m = Regex.Match(input, @"^(\d+)([^\d])(\d+)$");
if (m.Success)
{
int a = int.Parse(m.Groups[1].Value);
string op = m.Groups[2].Value;
int b = int.Parse(m.Groups[3].Value);
Console.WriteLine($"{a} {op} {b}");
}
This also means that it will work if you enter 123+456
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
is there any simpler ways like C++?
i can typed 9+3 and make input stream like this:
int num1, num2;
char opr;
std::cin >> num1 >> opr >> num2;
|
|
|
|
|
No. Using the Console to interface with the user is "old fashioned" and you won't be doing it for long anyway.
C# was born into a Windows world, and was primarily designed to work in Windows apps. C++ was the child of C, and was born into a world where Windows was new and unpopular, so it was given much more text based user input focus, because it needed it way back then.
In the modern world, even C++ apps very rarely use cin at all now!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
51 is "3" in the ASCII table, 52 is "4".
Console.Read reads a character and returns its ASCII value as an integer.
Returns Int32
The next character from the input stream, or negative one (-1) if there are currently no more characters to be read.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
<pre lang="c#"> plese help me solve this problem i am trying to make a auto fill button by using 3 layer architecture in asp.net c# on windows form
<pre>BELayer:
public string quantity { get; set; }
public string prod_id { get; set; }
public string party_id { get; set; }
DALayer page code:
public SqlDataReader autofillparty_id(BEL beobj)
{
try
{
cmd = new SqlCommand("select * from product where prod_id='" + beobj.prod_id + "'", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spsearchpartyid";
cmd.Parameters.AddWithValue("@prod_id", beobj.prod_id);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return sdr;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
BALayer code
public SqlDataReader autofillquantity(BEL beobj)
{
try
{
return daobj.autofillparty_id(beobj);
}
catch (Exception ex)
{
throw ex;
}
}
Main Page code::
private void button1_Click(object sender, EventArgs e)
{
if (baobj.autofillquantity(beobj).Read())
{
txtboxpartyidquant.Text = (beobj.party_id.ToString());
}
}
this code is not working i know problem is in my main page but i don't know how can i solve this problem please help me ...
|
|
|
|
|
Look, it really doesn't matter where you post this: as long as you are not listening to us, you will still be vulnerable to sQL injection.
So I'll say it for the third time in two days:
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.
When you concatenate strings, you cause problems because SQL receives commands like:
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood' The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable; Which SQL sees as three separate commands:
SELECT * FROM MyTable WHERE StreetAddress = 'x'; A perfectly valid SELECT
DROP TABLE MyTable; A perfectly valid "delete the table" command
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.
So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
If you don't listen to what we tell you, there really isn't any point in talking to you ...
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hi,
What is the correct way to do Business Validation on entities with Entity Framework 6. By business Validation I mean validation that require more than one entity in process with, sometime, a little more complex rules that involve all these entities. A validation that require the system to call he database.
I already checked this post:
ScottGu's Blog - Class-Level Model Validation with EF Code First and ASP.NET MVC 3
But, like most example about EF and validation all validations are limited to simple check that consider only the current entity. I need to do some check based on other entities.
Example: I have a order entity that contain a quantity of product but this quantity must be a multiple of a variable stored in my item entity. This is what I call the business validation. To perform this validation on order I need to go in database and check the item selected for this order.
public class Order : IValidateObject
{
public int Id { get; set; }
public int ItemId { get; set; }
public int Quantity { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var item = DbContext.Items.Find(ItemId);
if (Quantity % item.Multiple != 0)
yield return new ValidationResult("Quantity not multiple of item", new[] {Quantity});
}
}
public class Item
{
public int Id { get; set; }
public int Multiple { get; set; }
}
How should I implement this kind of business validation that require other entities? I'm more looking for a good tutorial about this subject. I search but each time I think I find the subject the tutorial is limited to classic validation with Data Annotation or other type of classic validation.
Maybe you will juste tell me there is no problem to class my context in the Validate method. It is just that most of tutorial separate the entity layer from the context layer suggesting entities must only be simple POCO with no behavior. I most and most disagree with this but I feel alone.
|
|
|
|
|
The "Enumerable" makes no sense. "Validation" is an all or nothing proposition. If you want to return multiple error / messages, return a list. If the list is "empty", you might consider things valid and then do a "save".
Other than that, you've provide no information about the environment: online, batch, whatever.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
|
So, instead of "one" call, he does multiple calls to get all the errors "because there may be multiple properties". Sorry, I fail to see the connection. The interface is at the "class level", not the property level.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
No, there's one call to get the list of validation errors. Each error can be associated with one or more properties, by specifying the member names in the ValidationResult .
The interface is designed for validation rules on a class which need access to other properties of the class. Validation attributes on a property only get access to that property's value. That's fine for simple validation rules like "required" or "greater than zero", but it doesn't work for things like "confirm password must be equal to password".
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Still doesn't answer why an enumerable is "better" than a list in this case. All you're doing is trading a yield for an Add (and making it more complicated for some … as indicated by OP's post).
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
The interface defines the method as returning IEnumerable<ValidationResult> .
If you wanted to return a List<ValidationResult> instead of using an iterator method, you could certainly do that. But I don't see how it would make things significantly simpler.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Gerry Schmitz wrote: Still doesn't answer why an enumerable is "better" than a list in this case. No one ever said it is "better".
This is just how the interface is built. Implementers are free to return whatever they want, provided it implements IEnumerable .
"Five fruits and vegetables a day? What a joke!
Personally, after the third watermelon, I'm full."
|
|
|
|
|
Finally. Thanks for that.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
In this case, you could probably implement the validation by adding a navigation property:
public class Order : IValidateObject
{
public int Id { get; set; }
public int ItemId { get; set; }
public int Quantity { get; set; }
public virtual Item Item { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Quantity % Item.Multiple != 0)
{
yield return new ValidationResult("Quantity not multiple of item", new[] { Quantity });
}
}
} However, you'd need to test to make sure the property was always set.
Alternatively, you could override the ValidateEntity method on your DbContext :
DbContext.ValidateEntity(DbEntityEntry, IDictionary<Object,Object>) Method (System.Data.Entity) | Microsoft Docs[^]
NB: This wouldn't work with EF Core - it no longer tries to validate the entities before saving them. If you wanted to validate the entities before trying to save them, you would have to write your own validation logic - for example:
Improving Model Validation for Entity Framework Core 2.0 | Ballard Software[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello,
I really appreciate some assistance in explaining how to create a collection property of the same class, as in the following example:
public class Person
{
public int PersonId { get; set; }
public int ParentId { get; set; }
public virtual ICollection<Person> People { get; set; }
}
Note: I am using EF-Code First ..
Many Thanks
|
|
|
|
|
That should work if you make the ParentId property nullable.
public class Person
{
public int PersonId { get; set; }
public int? ParentId { get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> People { get; set; }
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I think you don't need the ParentId property. You just need the Person Parent line and EF takes care of setting it up.
Of course, it's been a few years since I did this crap in EF, so YMMV.
|
|
|
|