physical com port and API in same time c#
I want to create windows service to call the API and physical ComPort simultaneously And Wait for response from one of them
I just want to know how to make it simultaneously And Wait for response from one of them
See also questions close to this topic
-
Filter items in a listbox that have been added with json
Well I'm trying to list items that are from listbox created with UserControl and the text properties are defined with a json file.
This is my .json file:
{ "Games": { "Quantity": 2, "Title0": "SomeGame1", "Description0": "Fps game", "Image0": "Some image link", "Link0": "GameStore.com/Somegame1", "Title1": "SomeGame2", "Description1": "RPG game", "Image1": "Some image link", "Link1": "GameStore.com/Somegame2", } }
This is the code to load the games as items in the listbox:
string JsonFile = Environment.CurrentDirectory @"\Test.json"; dynamic jasonfile = JsonConvert.DeserializeObject(JsonFile); GameUserControl[] Games = new GameUserControl[jasonfile["Games"]["Quantidade"]]; for (int quantity= 0; quantity < Games.Length; quantity++) { Games[quantity] = new GameUserControl(); Games[quantity].Descrição.Content = (jasonfile["Games"]["Title" + quantity]); Games[quantity].jog = (jasonfile["Games"]["Titulo" + quantity]); Games[quantity].lin = (jasonfile["Games"]["Link" + quantity]); string image = jasonfile["Games"]["Image" + quantity]; Games[quantity].imag = new ImageBrush(new BitmapImage(new Uri(image, UriKind.Absolute))); GamesListBox.Items.Add(Games[quantity]); }
This is the code I used in a textbox to try to filter:
if (CollectionViewSource.GetDefaultView(GamesListBox.Items) != null) CollectionViewSource.GetDefaultView(GamesListBox.Items).Filter = (o) => { return o.ToString().ToLower().Contains(Search.Text.ToLower()); };
But it didn't work, the item names are always GameUserContro.Can someone help me?
-
Advantage of .Net Core over WCF for RESTful APIs
We are currently using WCF to create RESTful APIs, it is working fine and has an added advantage that it can be consumed via SOAP too if we ever need to. We have all our systems using Microsoft technologies.
There is no active development on WCF but the current functionality is working fine for us. However, I believe the recommended approach is to start using .Net core for RESTful services. What are the additional advantages .Net core offers over WCF (apart from being platform independent)?
-
Generic class type constraint with a generic class having another constraint
Let's say I have a generic class
public class G<T> { }
and I want to declare final class as
public class F<T> where T : G<T> { }
that seems to be possible, but what if I want to complicate the task and add a constraint to the class G like that
public class A { } public class DA : A { } public class DB : A { } public class G<T> where T : A { }
and finally I want to do this
public class F<T> where T : G<T> { }
that does not work, it says T has to be of type A which is understandable and it looks like I can rewrite it like this
public class F<T, U> where T : G<U> where U : A { }
but in this case the usage has a redundant declaration
public class DF : F<G<DA>, DA> { }
I have to repeat DA twice when using class F even though it is quite clear if I use G as a generic type the generic type of G is DA. Is there a way to avoid this redundancy?
-
Cascading databound <ajaxtoolkit:combobox> and <asp:dropdownlist> in asp.net
I have an
asp.net
search form that includes anajaxToolkit Combobox
and a standardasp DropDownList
. Both controls are bound to two separatedSqlDatasource
components.Something like this:
<ajaxToolkit:ComboBox ID="cbConvenzionato" runat="server" AutoCompleteMode="SuggestAppend" DropDownStyle="DropDownList" DataSourceID="sdsConvenzionati" DataTextField="nome" DataValueField="id" AutoPostBack="true" OnSelectedIndexChanged="cbConvenzionato_SelectedIndexChanged" /> <asp:DropDownList ID="ddlVeicoli" DataSourceID="sdsVeicoli" DataTextField="targa" DataValueField="id" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlVeicoli_SelectedIndexChanged" AppendDataBoundItems="true"> <asp:ListItem Text="TUTTI" Value="" Selected="True" /> </asp:DropDownList> <asp:SqlDataSource ID="sdsConvenzionati" runat="server" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, nome FROM anag_convenzionati ORDER BY nome;" /> <asp:SqlDataSource ID="sdsVeicoli" runat="server" EnableCaching="false" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, targa FROM veicoli_contratti WHERE ((@id_convenzionato IS NULL) OR (id_convenzionato = @id_convenzionato)) ORDER BY targa;"> <SelectParameters> <asp:ControlParameter Name="id_convenzionato" ControlID="cbConvenzionato" PropertyName="SelectedValue" Direction="Input" ConvertEmptyStringToNull="true" DbType="Int32" DefaultValue="" /> </SelectParameters> </asp:SqlDataSource>
There's also a third
sqldatasource
(sdsNoleggi
) that feeds agridview
but this's not a problem right now.In code behind I have two event handlers:
protected void cbConvenzionato_SelectedIndexChanged(object sender, EventArgs e) { sdsVeicoli.Select(DataSourceSelectArguments.Empty); Search(); } protected void ddlVeicoli_SelectedIndexChanged(object sender, EventArgs e) { Search(); } private void Search() { sdsNoleggi.Select(DataSourceSelectArguments.Empty); }
I tought in this way I should filter
ddlVeicoli
items after selecting an item incbConvenzionato
... but it's not working... why?If I look into
sdsVeicoli
SelectParameters
in debug I can seeid_convenzionato
being correctly set to selected value (id coming fromcbConvenzionato
) I bet also thatsdsNoleggi
dataset wiil be correctly updated with new values since I did this many times before. So why bound control it's not? I tried also to force addlVeicoli.DataBind()
aftersdsVeicoli.Select()
call ... but this had no effect. -
Swagger UI not working for REST API (asp.net web api2) application
I have asp.net mvc project with .NET Framework 4.7.2 and the same project contains asp.net web api2 controller in a separate folder : Controllers. The solution is legacy. The API are already in use in the PRODUCTION environment. Now I added the Swagger nuget package (Install-Package Swashbuckle -Version 5.6.0) to this existing project. Post that I see a SwaggerConfig.cs added to the App_Start folder of the Solution Explorer.
Here the asp.net mvc controllers are used by App1 pointing to the server: www.app1.com and asp.net web api2 controllers are used by another frontend angular app: App2 pointing to the server : www.app2.com
The complete deployment package for both App1 and App2 are hosted in IIS
Any request related to App1 is handled by www.app1.com and any api request related to App2 (Angular frontend) is handled by App1 only using IIS Rewrite rules at App2 level which redirect any api request to App1 only.
Now in this case when I tried to navigate to www.app1.com/swagger , I see it is loading the SwaggerUI for me, but when I tried to navigate to www.app2.com/swagger it is not working and instead of that it is loading the Angular frontend application
Here goes the App1 and App2 at IIS level:
Can anyone help me here by providing their guidance to fix this issue?
-
Cors error missing allow origin header. MailKit
I have
cors error missing allow origin header
error only on ONE post request. My CORS Policypublic void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
Every request work fine, but one POST request fails, it's really weird. Code in controller action which failed use MailKit and SMTP to send email, maybe that's cause
-
Asyncio Loop in Daemon Thread
I have an app that downloads data and then does transformations/calculations on it. The API connectors/database has code using aiohttp / asyncpg. But async isn't appropriate for calculations.
So I've tried to invert the typical pattern and let the eventloop run in a daemon Thread (so I can submit aiohttp or asyncpg tasks to it). Please let me know if this implementation is correct or is missing anything! (I checked if daemon thread handles sigterm correctly.)
class AsyncioWorkerThread(Thread, metaclass=Singleton): """This class is a singleton, to enforce only one eventloop per process.""" def __init__(self, *args, daemon=True, loop=None, **kwargs): super().__init__(*args, daemon=daemon, **kwargs) self.loop = loop or asyncio.new_event_loop() self.running = False def run(self): """Start this AsyncioWorkerThread.""" self.running = True self.loop.run_forever() def submit(self, coro): """Submit a coroutine to this worker thread.""" print('in') return asyncio.run_coroutine_threadsafe(coro, loop=self.loop).result() def stop(self): """Stop this worker thread.""" self.loop.call_soon_threadsafe(self.loop.stop) self.join() self.running = False
References:
run infinite loop in asyncio event loop running off the main thread
https://linw1995.com/en/blog/Run-Asyncio-Event-Loop-in-another-thread/
Why does using threading.Event result in SIGTERM not being caught?
-
Running an application with multiple processes in a docker container
Assuming I have a main application that runs by itself multiple sub-applications. Is it possible to run that main application inside a container? Currently only the main application starts but the others doesn't.
-
Redirecting thread to custom stdout hangs
I am trying to provide user-friendly access for some equipment automation to my colleagues. The method I'm currently implementing provides a simple GUI for the user to select an automation script, run it, and have the output print to a Tkinter Text object.
I am implementing custom classes to redirect stdout and to generate the thread so that I can abort the script if desired.
My test files are below (I apologize for the monoliths). The stdout redirection is based on this answer, and the custom thread class is based on this post.
# console_redirect.py class StdOutRedirector(object): def __init__(self, widget): self.widget = widget def write(self, str): self.widget.configure(state = 'normal') self.widget.insert(END, str) self.widget.see(END) self.flush() # sleep(1) self.widget.configure(state = 'disabled') def flush(self): self.widget.update_idletasks() class ScriptThread(threading.Thread): def __init__(self, sName, dArgs, dEquip, func): threading.Thread.__init__(self) self.sName = sName self.dArgs = dArgs self.dEquip = dEquip self.func = func def run(self): # target function of the thread class self.func(self.dArgs, self.dEquip) def get_id(self): # returns id of the respective thread if hasattr(self, '_thread_id'): return self._thread_id # for id, thread in threading._active.items(): for id, thread in threading._active.items(): if thread is self: return id def raise_exception(self): thread_id = self.get_id() res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit)) if res > 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0) print('Exception raise failure')
I have a button in the GUI that will import test_script using importlib, redirect stdout (
sys.stdout = StdOutRedirector(text_widget)
), and run theauto
function.# test_script.py def auto(dArgs, dEquip): try: for i in range(20): print(i) time.sleep(0.1) except: print(traceback.format_exc()) finally: print('Finally') return True
If I don't redirect
stdout
, everything prints to powershell just fine. However, if I am redirecting the stdout, it only ever prints out the first statement before the whole program stops responding.I have, in the past, sucessfully seen a full printout in my Text widget by using a subprocess, rather than a thread. However, I will typically have to pass objects to the script being called, and I can't do this with subprocesses (I've tried pickling, but apparently the objects I'm passing contain pointers, which is prohibited by pickle).
Clearly, something is wrong with the
StdOutRedirector
class, but I'm having a hard time figuring out what.Any suggestions as to how i can debug what is happening would be greatly appreciated.
-Sean
-
Azure Devops: installing a Windows Service
I am trying to automate installing windows service using Azure DevOps pipeline. I installed Windows Service Manager from here: https://marketplace.visualstudio.com/items?itemName=MDSolutions.WindowsServiceManagerWindowsServiceManager and added it to the pipeline as a task. The windows service should be installed on the virtual machine where the pipeline is, so I provided "LocalSystem" as Run As Username, and nothing for password. The service was not installed with the following error: Service ' (MyServiceName)' cannot be created due to the following error: The account name is invalid or does not exist, or the password is invalid for the account name specified
I tried also the credentials I use to get to the virtual machine, but it gave the same error. How can this be solved? Added: The service can be installed without problems using installutil.
-
Need to disable EventLogging which is enabled default by UseWindowsService()
I have below code which I have used to run my windows app as a service using UseWindowsService() (Microsoft.Extensions.Hosting.WindowsServices.dll) but this method by default enables EventLogging and I want to disable the event logging as I am logging those messages to a text file using Serilog. Please let me know how can I disable the event logging feature which is set by UseWindowsService() without affecting Serilog logging and Console logging functionalities.
Please note that my application is running on .Net 4.7.2 framework.
private static IHostBuilder ConfigureRequest() { var host = new HostBuilder() .UseWindowsService() .ConfigureServices(service => { service.AddSingleton(BuildLogger); }) .ConfigureLogging((context, factory) => { factory.SetMinimumLevel(LogLevel.Trace); factory.AddConsole(); factory.AddSerilog( factory.Services.BuildServiceProvider().GetRequiredService<Serilog.ILogger>(), dispose: true ); }); return host; }
-
Getting Any Windows Service's Error Information via ServiceController or WMI in C#
I have been given the task of creating a Windows Service monitoring tool using C#. After researching I have found I can use either the
ServiceController
class or WMI. Through these I can determine things like the status, owner, etc. However, I have not found a way to get error information. Is there any way to get error code/message information from any Windows Service (through theServiceController
class, WMI, or any other method) regardless if we have access to the service's code?