|
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
|
|
|
|
|
That's pretty slick!
I converted all my database calls, and upgraded all the forms, in how I call them.
Converted all my repository files.
And built some services.
Got the hang of it now.
This is the way making a Windows app should be.
For me at least, because I've already wrote so many of the services I need with Direct Injection.
Thanks Richard for the point in the right direction.
[edit]
This .Net Core Win App is really cool.
I like it so far. I have no clue how to make an install app for it, and wonder if it really works on MacOS and Linux.
So far so good.
I had to use VS2019 Preview to get the form designer, it's a little bumpy and rough. Doesn't have the rename intellisense.
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|
|
With autofac I'm to add a parameter to the constructor and even more, the parameter can be optional
Builder
.RegisterAssemblyTypes(assemblies)
.Where(t => typeof(T).IsAssignableFrom(t))
.SingleInstance()
.AsSelf()
.WithParameter(new ResolvedParameter(
(pi, ctx) => pi.ParameterType == typeof(IMyService),
(pi, ctx) => ctx.ResolveOptional<IMyService>() ));
Could you help do this with the default MS dependency container and Scrutor?
What should I add here:
<pre lang="c#">
Builder
.Scan(s =>
s.FromAssemblies(assemblies)
.AddClasses(c => c.AssignableTo(typeof(T)))
.AsSelf()
.WithTransientLifetime() );
Thank you in advance for help and answer
|
|
|
|
|
If the constructor parameter is optional, it should just work:
public class Foo
{
public IBar Bar { get; }
public IBaz Baz { get; }
public Foo(IBar bar = default, IBaz baz = default) (Bar, Baz) = (bar, baz);
}
...
IServiceCollection services = new ServiceCollection();
services.AddTransient<IBaz, Baz>();
services.AddTransient<Foo>();
IServiceProvider provider = services.BuildServiceProvider();
Foo foo = provider.GetRequiredService<Foo>();
Debug.Assert(foo != null);
Debug.Assert(foo.Baz != null);
Debug.Assert(foo.Bar == null); It doesn't matter whether you register the services manually or use Scrutor.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi. I created a user control which has a textbox and a combobox. Depending on the state of the screen (navigation, creation or editing) one of them is visible and the other is invisible. This user control works with a database. Now what I need is to create a method for this component which should work the same way as the SelectedItemChanged of the combobox.
Can anyone help me?
Thanks.
|
|
|
|
|
It would help to know what UI you are using.
Never underestimate the power of human stupidity -
RAH
I'm old. I know stuff - JSOP
|
|
|
|
|
Hi, Mycroft (nice name).
Please see the answer to Ralf, in this same post.
Thank you.
|
|
|
|
|
It would also help if you describe what EXACTLY should happen.
I suppose you are using FORMS.
Perhaps ... basicly you should take a look to the functionality of Events ... that could be a way for you ...
|
|
|
|