|
One of our teachers in C# has asked us why this code is generating error:
class MainClass {
public static void Main (string[] args) {
int a, b;
int soma;
a = 10;
b = 5;
soma = a + b;
Console.WriteLine("Soma ="soma);
}
}
__________
The error it returns is:
main.cs(15,26): error CS1525: Unexpected symbol `soma'
Which means there is something wrong in the "Console.WriteLine" line (line 15 in my code).
Thing is, I can't understand what is missing. Can any seniors point out to me?
|
|
|
|
|
You are trying to combine a string with a variable, your console.writeline needs to display a string it cannot work out what Console.WriteLine("Soma ="soma); is. Take a look at the .ToString() method on the variable.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
I'm sorry, so my console.writeline should be Console.WriteLine.Tostring("Soma =" soma) ???
Or if not, could you post the correct sequence?
I just realized... all we need is a comma, right? Between the string side and the Variable side.
does
Console.WriteLine("Soma =", soma);
works?
modified 4-Sep-20 21:46pm.
|
|
|
|
|
You did not understand what was written, apply the ToString() method to the variable soma. Then you need to concatenate the strings.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
So the concatenation was the thing I wasn't doing... aha.
Console.WriteLine("Soma =" + soma);
I got it now. I needed the + symbol between the string and the variable. Now the code worked on my console at least.
|
|
|
|
|
Concatenation is just one way to fix it:
Console.WriteLine("Soma = " + soma); There is also formatting:
Console.WriteLine("Soma = {0}", soma); Where "{0} " says "use the first (or zeroth since C# indexes are zero based) parameter value here".
Or interpolation:
Console.WriteLine($"Soma = {soma}"); Where the "$ " prefix enables interpolation, and then the "{" and "} " characters delimit the actual values to be used in the string.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
On naming; the result variable is not "som of a", but "som of a and b". So, something like "SomAB" might be more appropriate. It'd also be preferable to use English in source, as that makes your code more accessible. Hence, "SumOfAandB".
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
I have this function
private async Task<int> SearchForAllNumbers(int num = -1)
{
if (num == -1)
DisplayLoadingMessage(true, GetString(Resource.String.Common_SearchTitle), GetString(Resource.String.Common_SearchMessage));
dates = DateFunctions.GetSelectedDates(DateFrom, DateTo);
var list = string.Empty;
var klirwseis = ", Κληρωσεις: ";
if (num == -1)
list = ListTextView.Text;
else
list = num.ToString();
var nums = list.Split(',').Select(Int32.Parse).ToList();
if (seperateCheckBox.Checked)
{
DisplayLoadingMessage(false);
seperateCheckBox.Checked = false;
for (int k = 0; k < nums.Count; k++)
{
await SearchForAllNumbers(nums[k]);
}
return -1;
}
var totalCoutner = 0;
for (int datesPos = 0; datesPos <= dates.Count; datesPos++)
{
... Do some calculations
}
HistoryTextView.Text = "Ημερομηνία: " + dates[datesPos] + ", Λίστα: " + list + ", Κληρώθηκε: " + totalCoutner + " φορές" + HistoryTextView.Text;
if (showListsCheckBox.Checked)
HistoryTextView.Text = klirwseis + HistoryTextView.Text;
}
DisplayLoadingMessage(false);
HistoryTextView.Text = ".\n" + HistoryTextView.Text;
return totalCoutner;
return 0;
}
And i want to be able to cancel it when its running so i have created this function
private async Task SearchFoNumbersAsync()
{
ActiveCancellationTokenSource = new CancellationTokenSource();
DrawResultsTypeEnum searchType = (DrawResultsTypeEnum)ShowResultsSpinnerPosition;
var task = Task.Run(async () =>
{
if (searchType == DrawResultsTypeEnum.AllNumbers)
await SearchForAllNumbers();
else if (searchType == DrawResultsTypeEnum.AnyWinningCombination)
await SearchAnyWinningCombination();
SaveHistory();
}, ActiveCancellationTokenSource.Token);
try
{
await task;
}
catch (System.OperationCanceledException e)
{
Console.WriteLine($"{nameof(System.OperationCanceledException)} thrown with message: {e.Message}");
DisplayLoadingMessage(false);
}
finally
{
ActiveCancellationTokenSource.Dispose();
DisplayLoadingMessage(false);
}
}
To be able to run it from Task.Run and to be able to cancel it. The code doesnt work however
I have debug it and when it reach the
try
{
await task;
}
Stays there forever, the
SearchForAllNumbers() or
SearchAnyWinningCombination() are not accessed at all.
i'm not sure what i have done wrong.
|
|
|
|
|
Keep taking code out until it works, then start adding it back in. If nothing works, start over.
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
|
|
|
|
|
thanks, this helped, i found the reason of that but now i see that if i cancel the task, all the already running functions will keep running. im not sure if the best approach is to add some if (token.iscancellationrequested) or to make all the functions to tasks that can take a token
|
|
|
|
|
|
I was reading this today but it looks to me like a worst idea of having a task that can take a cancellation token so i will try to find more approaches on how to cancel task and its childrends
|
|
|
|
|
If you don't "like" MS samples, you're going to be in for a lot of headaches.
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
|
|
|
|
|
a general sample might not be the best solution for every situation. my code in the first post also is based on MS samples
|
|
|
|
|
I decided write a .Net Core Windows App to track my Amazon and EBay sales.
Choose .Net Core 3.1, and the app works pretty damn good. It's suppose to be new, with all these benefits. I can't remember the benefits, maybe one of them being your app runs in a container sort of like docker, and can run on other platforms such as MacOs, Linux.
Also chose Mongo as the DB.
I'm fuzzy on the DB stuff here. I wrote a respository using .Net Core Web techniques, in which I created IOrdersRespository and OrdersRepository, which might of been a mistake. In a .Net Core web app, you register the respository in startup, and use the repository in the controller. But I have no clue if I'm suppose to do sort of the same thing in a Windows app.
I searched around on Google, but it pulls up all the web subjects.
I was thinking of going back and dumping the IOrdersRespository and just use a straight class, and make the functions static.
But then I have to call up the context in every db function.
Any insight would be helpful.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Mongo DB is a "document" database I think you would be better served using a relation DB, you are not storing documents you are parsing and storing data!
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
I thought about that. It's really just data that doesn't get updated. Except for cost, so I can calculate profit.
Each order is a document. Each product is a document. Each inventory order I send to Amazon fulfillment is a document.
I just need data for a year, then I can dump it. Like I need to know how much sales tax was collected for CA when I file my sales tax. Or a running total of how many I sold, which can be placed on a single document. Monitor lost or stolen items. Monitor depletion rates.
I thought using NoSQL or documents matched up quite nice. I considered SQL or SQLite, But I hate / dislike SQL Server.
And there's nothing relational in this. Just flat files downloaded and converted to documents.
Mongo is pretty lightweight, small size, fast processing. I already wrote code to download and install it within a Windows app.
If it backfires on me I'll let you know, but I'm thinking documents in the design.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Ah I was under the impression you were parsing the data from the CSV question
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
To "like" SQLite and dislike SQL Server is not logical since from a "client" point point of view they are virtually identical; and with an ORM indistinguishable.
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
|
|
|
|
|
I like SQLite, but don't like the database creation part of it.
I don't like having SQL server or Express running on my machine.
And I haven't tried the new Linux version of SQL server that can run in a container and I think is open source. That's something I might like.
I was audited by the BSA recently, Microsoft came after me, and we came to an agreement that is fair for all parties. So I just stay away from their server products now. I don't like SQL Server from a business point of view.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Quote: I like SQLite, but don't like the database creation part of it.
using ( SqlCeEngine engine = new SqlCeEngine( "connection string" ) ) {
engine.CreateDatabase();
}
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
|
|
|
|
|
Your question seems to be whether you should continue to use DI in a Windows application, or whether you should fall back to tightly-coupled classes.
Stick with DI. It will make your code easier to test. You just need to add the boilerplate code for registering the services yourself if the project template doesn't already include it.
Add a reference to Microsoft.Extensions.DependencyInjection , and modify the Main method to build and populate the service provider.
using Microsoft.Extensions.DependencyInjection;
static class Program
{
public static IServiceProvider ServiceProvider { get; private set; }
private static void ConfigureServices(IServiceCollection services)
{
...
}
static void Main()
{
var services = new ServiceCollection();
ConfigureServices(services);
ServiceProvider = services.BuildServiceProvider();
...
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
That's what I was trying to achieve.
The example is a little fuzzy, but I'll give it a try, and do some searching on DI for Windows app
Thanks!
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
It works, pretty fast speed.
But it's kind of weird.
Dependency Injection in Win Forms or Desktop Application .NET Core | TheCodeBuzz
I set up the forms, and used my main Form.
And then from the main form, passed it to the menu form, and next to the Amazon form, deep down to dialog forms.
I kind of thought the forms would just pick up respository or service.
private static void ConfigureServices(IServiceCollection services)
{
services.AddScoped<MainForm>();
services.AddScoped<MenuForm>();
services.AddScoped<AmazonForm>();
services.AddScoped<AmazonDownloadForm>();
services.AddScoped<AmazonOrderDialogForm>();
services.AddScoped<AmazonViewOrdersForm>();
services.AddScoped<DownloadFileProcessorDialog>();
services.AddScoped<EBayForm>();
services.AddScoped<EBayDownloadForm>();
<pre>
services.AddTransient<IOrdersRepository, OrdersRepository>();
services.AddSingleton<IGmailSender, GmailSender>();
}
Called the main form
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
var mainForm = serviceProvider.GetRequiredService<MainForm>();
mainForm.Shown += Main_Shown;
mainForm.FormClosed += Main_FormClosed;
Application.Run(mainForm);
}
Main form loads the menu form
var menuForm = new MenuForm(_ordersRepository)
{
MdiParent = this,
Dock = DockStyle.Fill
};
menuForm.Show();
Menu Form loads the Amazon Form
private void Btn_Amazon_Click(object sender, EventArgs e)
{
for (var i = Application.OpenForms.Count - 1; i >= 1; i += -1)
{
var form = Application.OpenForms[i];
if (form.Name != "MainForm")
form.Close();
}
var amazonForm = new AmazonForm(_ordersRepository)
{
MdiParent = MainForm.ActiveForm,
Dock = DockStyle.Fill
};
amazonForm.Show();
Application.DoEvents();
}
Well at least I got first working.
I'll play around with the 2nd part, and do lots or reading on the subject.
But the orderRepository works, my test example. I have 10 db respositories and don't want to pass them all up the chain.
I thought is was hard to understand how it works for web projects, this is probably more simple, but I just don't get it yet.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
Figured how to open more forms down the line
I was passing parameters to forms
like var dbCredentialsFormDI = new DbCredentialsForm(false);
Now I have ...
var dbCredentialsFormDI = serviceProvider.GetRequiredService<DbCredentialsForm>();
dbCredentialsFormDI.firstTime = false;
dbCredentialsFormDI.Dock = DockStyle.None;
dbCredentialsFormDI.StartPosition = FormStartPosition.CenterScreen;
var result = dbCredentialsFormDI.ShowDialog();
if (result == DialogResult.OK)
{
Application.DoEvents();
}
I changed this form from this
public partial class DbCredentialsForm : Form
{
private readonly bool _firstTime;
public DbCredentialsForm(bool firstTime)
{
InitializeComponent();
_firstTime = firstTime;
OK_Button.Enabled = false;
}
To this, I don't it's right.
public partial class DbCredentialsForm : Form
{
public bool firstTime { get; set; }
public DbCredentialsForm()
{
InitializeComponent();
OK_Button.Enabled = false;
}
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|