|
I always thought await returns back to the caller, so at the first await, the rest are not fired until the previous one completed
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
Sorry - I didn't see the "in parallel" bit in your original post.
"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!
|
|
|
|
|
NP, so what's the best way to run them in parallel and wait for results from each one separatly?
If it's not broken, fix it until it is.
Everything makes sense in someone's mind.
Ya can't fix stupid.
|
|
|
|
|
|
As in:
private void Bar()
{
Task.Run(() => { Thread.Sleep(2000); Console.WriteLine("1 done"); Thread.Sleep(2000); }).ContinueWith((x) => { Console.WriteLine("1 complete"); });
Console.WriteLine("one done");
Task.Run(() => { Thread.Sleep(2000); Console.WriteLine("2 done"); Thread.Sleep(2000); }).ContinueWith((x) => { Console.WriteLine("2 complete"); }); ;
Console.WriteLine("two done");
Task.Run(() => { Thread.Sleep(2000); Console.WriteLine("3 done"); Thread.Sleep(2000); }).ContinueWith((x) => { Console.WriteLine("3 complete"); }); ;
Console.WriteLine("all done");
}
"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!
|
|
|
|
|
In this case you can just do:
var companyTask = _apiProxy.GetNavigationItems(NavigationItemType.Company);
var employeeTask = _apiProxy.GetNavigationItems(NavigationItemType.Employee);
var projectTask = _apiProxy.GetNavigationItems(NavigationItemType.Project);
var companies = await companyTask;
var employees = await employeeTask;
var projects = await projectTask;
Of course it is up to the apiProxy (or any method it calls) if it will actually run concurrently.
modified 7-Apr-23 8:29am.
|
|
|
|
|
Kevin Marois wrote: I want to run a these commands in parallel and get the results as each finishes.
First of course you need to figure out how exactly you are going to collect the results. Additional to that you might also consider what you are going to do with the results.
Collecting the results itself has nothing to do with running them in parallel but it does impact how you encapsulate what it is exactly that you want each 'task' to do.
For example if each task just returned a boolean and you wanted to return that to the caller then you need a structure that holds a boolean and something that tells you which task returned which boolean. It can get way more complicated than that. For example if each one returns data in a different format.
Probably a really good idea also to consider what happens if there is an error. Could be an expected error or an unexpected error.
|
|
|
|
|
Assuming you have a list of tasks which return the same type, and you want to process the task results in the order in which they complete, then Stephen Toub has you covered:
Processing tasks as they complete - .NET Parallel Programming[^]
For a small number of tasks, using Task.WhenAny is probably good enough:
var tasks = new List<Task<T>>
{
_apiProxy.GetNavigationItems(NavigationItemType.Company),
_apiProxy.GetNavigationItems(NavigationItemType.Employee),
_apiProxy.GetNavigationItems(NavigationItemType.Project)
};
while (tasks.Count != 0)
{
var t = await Task.WhenAny(tasks);
tasks.Remove(t);
T result = await t;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi,
How can I have a regex for my .NET app's user password with the following:
Password MUST be a minimum of 10 AND maximum of 50
It should NOT contain space.
It should be MIXED alphabet (upper + lower), numeric and following special characters !@#$%^&*-_+=~
Thanks,
Jassim
www.softnames.com
|
|
|
|
|
RegEx is not a good fit for password rules. You'd be much better off coding each rule separately.
|
|
|
|
|
The problem with using a regex for this is that it gets very, very complex - and that means that when the rules change (and they always do) a horribly complicated and difficult to understand string has to be modified, tested, fixed, tested, and finally released. Which makes maintenance difficult and prone to error.
Instead, use .NET string operations (or individual Regexes) to pick up each individual part:
int numLoCase = ...
int numUpCase = ...
int numSpaces = ...
int numNumeric = ...
int numSpecial = ...
int len = ... And then apply a single if statement to apply the rules:
if (len >= 10
&& len <= 50
&& numSpaces == 0
&& ... You get much more readable code, and more reliable maintenence.
"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!
|
|
|
|
|
Jassim Rahma wrote: Password MUST be a minimum of 10 AND maximum of 50
It should NOT contain space.
It should be MIXED alphabet (upper + lower), numeric and following special characters !@#$%^&*-_+=~ Tell management to f*** off.
A horse staple is better. Let's do a Zoom where I can explain that fine detail. I will be recording for training purposes only.
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.
|
|
|
|
|
probe the next function:
bool IsValidPassword(string password,
int minLength=10,
int maxLength=50,
bool requireLowercase=true,
bool requireUppercase=false,
bool requireNumber=false,
bool requireSimbol=false)
{
if (string.IsNullOrEmpty(password))
{
return false;
}
if (password.Length < minLength || password.Length > maxLength)
{
return false;
}
if (requireUppercase && !Regex.IsMatch(password, "[A-Z]"))
{
return false;
}
if (requireLowercase && !Regex.IsMatch(password, "[a-z]"))
{
return false;
}
if (requireNumber && !Regex.IsMatch(password, "[0-9]"))
{
return false;
}
string pattern= @"[!@#$%^&*()_+\-=\[\]{};':" + "\"" + @"\\|,.<>\/? ~]";
if (requireSimbol && !Regex.IsMatch(password, pattern))
return false;
return true;
}
|
|
|
|
|
What's a simbol?
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.
|
|
|
|
|
|
Apart from the above-mentioned problem with the readability of Regex, another problem is that Regex is quite computation-heavy, and due to the fact that it builds underlying state-machine[^] performance penalty is heavier for big strings.
|
|
|
|
|
Hi All,
I want to create my own unit testing framework using C#.
Can anybody please suggest me any websites or articles for creating our own unit testing framework using C#.
Thank you All
|
|
|
|
|
Why? Visual Studio includes a UT framework already ... you are reinventing the wheel and adding a layer of possible bugs to the testing environment as well as spending some considerable time developing what already exists.
"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!
|
|
|
|
|
I doubt such a thing exists.
The idea itself is fairly obvious so I am not sure what you would need to know other than having used one at one time.
Now lets say you want to hook it into VS itself. That is not trivial. But you can't do that until you create the rest of it anyways.
Best thing I can suggest it so look at source code for log4net. And maybe read through questions and bugs for that.
|
|
|
|
|
Yes ... go for NUnit2. NUnit4.
NUnit.org
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
above is correct answer. search public Unit test project. Like NUnit in this case.
GitHub - nunit/nunit: NUnit 3 Framework[^]
I think you do not begin from scratch but if you confident with your abilities, you contact original writer and suggest yourself as contributor on NUnit project in example.
Regards
Toha
|
|
|
|
|
Hello,
first of all I just need a hint on how to approach this topic in the most sensible way.
I have an older application that can only determine its coordinates correctly when it is running on only one monitor. Now the application needs to run in environments with multiple screens with different resolutions. Example: Notebook with 1920x1080 + 3840×2160 + 1920x1200 (main screen). In addition, screens with a scaling other than just 100% can be run (e.g. 175%). As you can see here, a colourful mixture.
I would like to determine the exact position and window size of the program.
I am primarily a backend developer, so I have never had anything to do with this topic before. For this reason, I am turning to you in the hope of getting a push before I go the wrong direction.
Many thanks in advance and best regards
René
|
|
|
|
|
Hi René!
You are going to have to give more detail as to what exactly you need help with - I have three monitors here, all different resolutions (1920x1080, 1080x1920, and 1280x1024 @ 100%), plus my Surface Go 2 (1920x1280 @ 150%) which I can write / test apps on (plus gawd knows what once the software is released) and generally it's not a problem.
Why does you app need to "know where it is"? What is it doing that it needs this? What will it do with the info? What's the problem in finding out?
My apps generally "remember" where they were, and restore their position on that particular system:
#region Event Handlers
#region Form
private void FrmMain_Load(object sender, EventArgs e)
{
if ((ModifierKeys & Keys.Shift) == 0)
{
this.LoadLocation();
}
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
if ((ModifierKeys & Keys.Shift) == 0)
{
this.SaveLocation();
}
}
Is part of my standard "new form" code, along with the support methods:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Data;
using System.Drawing;
using System.Diagnostics;
namespace OneOffJobs
{
public static class Storage
{
#region Constants
private const int SW_RESTORE = 9;
#endregion
#region DLL Imports
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
#endregion
#region Fields
#region Internal
#endregion
#region Property bases
#endregion
#endregion
#region Properties
public static Guid AppGuid
{
get
{
Assembly asm = Assembly.GetEntryAssembly();
object[] attr = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
return new Guid((attr[0] as GuidAttribute).Value);
}
}
public static Guid AssemblyGuid
{
get
{
Assembly asm = Assembly.GetExecutingAssembly();
object[] attr = (asm.GetCustomAttributes(typeof(GuidAttribute), true));
return new Guid((attr[0] as GuidAttribute).Value);
}
}
public static string UserDataFolder
{
get
{
Guid appGuid = AppGuid;
string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper());
return CheckDir(dir);
}
}
public static string UserRoamingDataFolder
{
get
{
Guid appGuid = AppGuid;
string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper());
return CheckDir(dir);
}
}
public static string AllUsersDataFolder
{
get
{
Guid appGuid = AppGuid;
string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper());
return CheckDir(dir);
}
}
public static string LocationsStorageFile { get; private set; }
#endregion
#region Regular Expressions
#endregion
#region Enums
#endregion
#region Constructors
static Storage()
{
LocationsStorageFile = UserDataFolder + "control.storage.locations";
}
#endregion
#region Events
#region Event Constructors
#endregion
#region Event Handlers
#endregion
#endregion
#region Public Methods
public static void SaveLocation(this Control control, string instance = null)
{
string controlName = control.GetType().Name;
if (!File.Exists(LocationsStorageFile))
{
CreateBlankLocationFile();
}
if (!(control is Form f) || (f.Visible && f.WindowState == FormWindowState.Normal))
{
DataTable dt = ReadXML(LocationsStorageFile);
if (dt.Columns.Count >= 6)
{
bool ignoreInstance = string.IsNullOrWhiteSpace(instance);
DataRow current = dt.NewRow();
current["ControlName"] = controlName;
current["Instance"] = instance ?? "";
foreach (DataRow row in dt.Rows)
{
if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance))
{
dt.Rows.Remove(row);
break;
}
}
current["LocationX"] = control.Location.X;
current["LocationY"] = control.Location.Y;
current["SizeW"] = control.Size.Width;
current["SizeH"] = control.Size.Height;
dt.Rows.Add(current);
WriteXML(dt, LocationsStorageFile);
}
}
}
public static void LoadLocation(this Control control, string instance = null)
{
string controlName = control.GetType().Name;
if (!File.Exists(LocationsStorageFile))
{
CreateBlankLocationFile();
}
DataTable dt = ReadXML(LocationsStorageFile);
if (dt.Columns.Count >= 6)
{
bool ignoreInstance = string.IsNullOrWhiteSpace(instance);
DataRow current = dt.NewRow();
current["ControlName"] = controlName;
current["Instance"] = instance ?? "";
current["LocationX"] = control.Location.X;
current["LocationY"] = control.Location.Y;
current["SizeW"] = control.Size.Width;
current["SizeH"] = control.Size.Height;
foreach (DataRow row in dt.Rows)
{
if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance))
{
current = row;
if (int.TryParse(current["LocationX"].ToString(), out int x) &&
int.TryParse(current["LocationY"].ToString(), out int y) &&
int.TryParse(current["SizeW"].ToString(), out int w) &&
int.TryParse(current["SizeH"].ToString(), out int h))
{
control.Location = new Point(x, y);
control.Size = new Size(w, h);
}
break;
}
}
}
}
public static void SingleInstance(this Process thisProcess)
{
foreach (Process proc in Process.GetProcessesByName(thisProcess.ProcessName))
{
if (proc.Id != thisProcess.Id)
{
ShowWindow(proc.MainWindowHandle, SW_RESTORE);
SetForegroundWindow(proc.MainWindowHandle);
thisProcess.Kill();
}
}
}
#endregion
#region Overrides
#endregion
#region Private Methods
private static string CheckDir(string dir)
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
return dir;
}
private static DataTable ReadXML(string file)
{
using (DataSet ds = new DataSet())
{
ds.ReadXml(file);
DataTable dt;
if (ds.Tables.Count > 0)
{
dt = ds.Tables[0];
ds.Tables.Remove(dt);
}
else
{
dt = new DataTable("Empty");
}
return dt;
}
}
private static void WriteXML(DataTable dt, string file)
{
using (DataSet ds = new DataSet())
{
ds.Tables.Add(dt);
ds.WriteXml(file);
ds.Tables.Remove(dt);
}
}
private static void CreateBlankLocationFile()
{
DataTable dtNew = new DataTable("Locations");
dtNew.Columns.Add("ControlName", typeof(string));
dtNew.Columns.Add("Instance", typeof(string));
dtNew.Columns.Add("LocationX", typeof(int));
dtNew.Columns.Add("LocationY", typeof(int));
dtNew.Columns.Add("SizeW", typeof(int));
dtNew.Columns.Add("SizeH", typeof(int));
DataRow dr = dtNew.NewRow();
dr["ControlName"] = "%%SAMPLE%%";
dr["Instance"] = "%%INSTANCE%%";
dr["LocationX"] = 0;
dr["LocationY"] = 0;
dr["SizeW"] = 200;
dr["SizeH"] = 200;
dtNew.Rows.Add(dr);
WriteXML(dtNew, LocationsStorageFile);
}
#endregion
}
}
"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!
|
|
|
|
|
Hello "OriginalGriff"
first of all, thank you for your post. With my poor English, I'll try to explain the problem a little better.
We have an application that was programmed with SAL. SAL is a programming language developed by the Gupta company in the 90s. Gupta has a colourful history: first it was called Gupta, then Centura, later Unify and today it is owned by OpenText.
As far as window management is concerned, SAL applications unfortunately only work correctly with one screen. Working with several different screens causes SAL applications major problems.
Now SAL can integrate and use .NET DLLs developed with Framework 4.8. This is where I would like to start in order to take over the window management myself. I want to be able to determine and restore the window position and size of the SAL application on any screen, regardless of resolution and scaling.
Thank you again and best regards
René
|
|
|
|
|
THe screen resolutions and DPI settings don't matter. All you need is the Top, Left, Width, and Height properties of the window. That's it.
How you do that is a custom programming language nobody has ever heard of is entirely on you. You may be able to use .NET DLL's, but the windows are not being created by those DLL's, I assume? In that case, you're going to have to get the window handle of your apps main window somehow, then use that to call the GetWindowRect function[^] to get the screen coordinates and size rectangle.
|
|
|
|
|