|
It's for a control software for a product with an ARM-processor with an embedded USB-controller that resets (and thus drops the USB-connection) when the ARM-processor is reset and when it jumps from application mode to bootloader mode and vice versa.
I'm not so fond of the idea to turn the C++ code into a dll and then call it from C# because my C++ skills are non-existent. Also, I foresee problems passing string arrays (I don't know the needed array size in the C# code) and avoiding memory leaks due to not handling de-allocation of the string arrays in the C++ code properly.
modified 5-Jun-18 16:39pm.
|
|
|
|
|
My reference to dll's was to "system / .NET" dll's that require "load time" when first called.
In my case, I need to maintain connections to "IOT" devices (real time control and data collection).
I have a separate thread that checks the last status of each connection, and "reconnects" if that's what's called for (With a sample rate of 10 seconds, I check each connection every 10 seconds).
(I use C# dlls extensively to abstract API's of all sorts; passing data in different "representations" has never been as issue. XML or Binary Writer / Reader are your friends.)
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
The first part of the C++ code is enumerating the port names like SerialPort.GetPortNames() does. So there is no need to convert that. It is also not recommended to use the registry directly because it may change with the used Windows version while SerialPort.GetPortNames() is guaranteed to provide the correct information.
I don't know why your WMI query is so slow. Maybe you have used an improper search query (should be "SELECT * FROM Win32_SerialPort").
If you want to use the SetupApi with C# see Enumerate All COM Ports and Find Their Name and Description in C#.
Note also that you only need to update the list when a port has been added or removed. This can be handled by registering for device change events.
|
|
|
|
|
Thank you, that link made my life a lot easier.
|
|
|
|
|
Hey, I learned C# roughly a month ago, and I've kinda run out of ideas for projects. I would say I'm a beginner, but don't hesitate to come with your more advanced projects, maybe some of which you've made in the past. I have made programs such as Snake, Tic Tac Toe, Soundboard, Soccer Game, Duck Shooter, Ping Pong and a couple of smaller projects. You don't have to come with a solution for the project, I would like to try to figure it out myself.
So please, if you've got any project ideas or thoughts, list them in the comment. Thanks in advance.
|
|
|
|
|
1) DON'T SHOUT. Using all capitals is considered shouting on the internet, and rude (using all lower case is considered childish). Use proper capitalization if you want to be taken seriously.
2) We can't really recommend much, because we have no idea of your interests let alone your abilities. One month of C# isn't a lot, but if you have a previous solid background in C++ say, then it could be enough to do some complicated projects.
So there are simple things like a calculator, or an address book, up to more complicated things like a password vault that uses encryption and stores details in a DB. For the really advanced version, make it multi device and sync changes from multiple sources ... trust me, that isn't something for beginners at all!
Have a think about your own interests, and take a good critical look at your abilities: then think of something that fits the former, and which aims to fill in the weaknesses in the later.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I'd like to suggest you get some (recent edition) good books on more advanced topics in C#, and study their content, code, and examples. Try authors like Skeet, Troelsen, Michaelis: [^], [^], [^]
Perhaps write a personal information app with alarms/e-mail notifications, calendar, appointments, etc., using a database; get familiar with using Linq for query, and WCF DataContract/DataMember for serialization in XML.
cheers, Bill
«... thank the gods that they have made you superior to those events which they have not placed within your own control, rendered you accountable for that only which is within you own control For what, then, have they made you responsible? For that which is alone in your own power—a right use of things as they appear.» Discourses of Epictetus Book I:12
modified 5-Jun-18 11:39am.
|
|
|
|
|
Your own crypto / blockchain currency: KFCoin.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
If you started up with C# a month ago, by no means have you "learned" it.
When I want to learn a language or framework, I find an app that is interesting, and try to duplicate it in terms of appearance and functionality. IMHO, that's the absolute best way to actually learn coding.
BTW, duplicating bugs that exist in the app you're duplicating would earn you extra points.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013
|
|
|
|
|
Hi everybody,
I have a big problem with a little code sequence.
I have to return JSON data through a REST service.
Here is the Interface:
using System.ServiceModel;
using System.ServiceModel.Web;
namespace PERFoRM_LhnetRESTServiceHost
{
[ServiceContract()]
interface IRestService
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare) ]
string GetJson();
}
}
Here is the implementation:
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Activation;
namespace PERFoRM_LhnetRESTServiceHost
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
class RestService : IRestService
{
public string GetJson()
{
string retJson = "{\"firstname\": \"Georg\", \"name\": \"Clooney\"}";
using (StreamWriter sw = new StreamWriter(new FileStream(@"D:\Temp\Json.txt", FileMode.OpenOrCreate)))
{
sw.Write(retJson);
sw.Flush();
}
return retJson;
}
}
}
The JSON data in the string and in the file is correct:
{"firstname": "Georg", "name": "Clooney"}
The JSON data in the web browser is WRONG! WHY?:
"{\"firstname\": \"Georg\", \"name\": \"Clooney\"}"
It must be a little thing, but I couldn't find it.
Thank you very much for your help!
BR, Manfred
|
|
|
|
|
Returning raw json (string) in wcf - Stack Overflow[^]
WCF "Raw" programming model (Web) – Carlos Figueira MSDN blog[^]
When you return a string with ResponseFormat = Json , the string will be JSON-encoded, and the client will receive a string.
If you want to send raw JSON, the simplest option is to return a Stream instead.
[ServiceContract()]
interface IRestService
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare) ]
System.IO.Stream GetJson();
}
...
public Stream GetJson()
{
string retJson = "{\"firstname\": \"Georg\", \"name\": \"Clooney\"}";
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
return new MemoryStream(Encoding.UTF8.GetBytes(retJson));
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I need to send sms from c# windows application.i try some gateways to send but its not working
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Web;
using System.Net;
namespace SMS_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnsent_Click(object sender, EventArgs e)
{
String result;
string apiKey = txtapi.Text;
string numbers = numtxt.Text; // in a comma seperated list
string message = msgtxt.Text;
string send = txtseder.Text;
String url = "https://api.textlocal.in/send/?apikey=" + apiKey + "&numbers=" + numbers + "&message=" + message + "&sender=" + send;
//refer to parameters to complete correct url string
StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
objRequest.ContentLength = Encoding.UTF8.GetByteCount(url);
objRequest.ContentType = "application/x-www-form-urlencoded";
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(url);
}
catch (Exception ex)
{
//return e.Message;
MessageBox.Show(null,"the error is"+ex.Message,MessageBoxButtons.OK,MessageBoxIcon.Information);
}
finally
{
myWriter.Close();
}
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
//return result;
MessageBox.Show(null, "the message is" + result, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
|
|
|
|
|
"It's not working" is one of the most useless problem descriptions we get: it tells us absolutely nothing about the problem. We don't know if you get an error message, or the wrong data, or even that that code compiles successfully!
Remember that we can't see your screen, access your HDD, or read your mind - we only get exactly what you type to work with.
So tell us what happens when you run that code, what you expected to happen, how you checked what happened. Help us to help you!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Dear Good People of this Forum,
Please assist with C sharp code for both Objective and subjective questions for CBT Exam.
Your urgent feedback will be highly appreciated
|
|
|
|
|
|
Dear poster,
No.
Yours,
The Good People of this Forum. Why not?
Well, probably because good people don't cheat in exams...
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
It's really hard ... you will fail miserably. I wouldn't be able to eat or sleep ...
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Hi all, I'm developing a serial monitor for my application in WPF, programming in C#.
I have trouble managing the DataReceived event, because i want a real time monitor like HyperTerminal or TeraTerm for example (I'm not using them because I want my terminal to be a part of an ethernet communication tool, wich I already developed using winPcap).
I have to read some data from my microcontroller, display it on the textBox (It just prints a menu and the list of commands available) and when it finishes the loading sequence I would like to interact with it, nothing special, just send a "flash-" command to program the fpga of the board.
My application goes in exception when I try to update the textbox.text with the data received. I tried to search everywhere but despite a lot of examples, I didn't catch something which is explaining the code properly.
Here is the code, thanks in advance
namespace WpfApplication1 {
public partial class SerialMonitor : Window {
public SerialPort comPort = new SerialPort();
public SerialMonitor() {
InitializeComponent();
scanPorts();
}
private void scanPorts() {
textBoxIndata.Clear();
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports) {
comboBoxPorts.Items.Add(port);
}
}
private void openComBtn_Click(object sender , RoutedEventArgs e) {
comPort.Parity = Parity.None;
comPort.DataBits = 8;
comPort.ReadTimeout = 500;
comPort.StopBits = StopBits.One;
if (comboBoxPorts.SelectedItem != null && comboBoxPorts.SelectedItem != null) {
comPort.PortName = comboBoxPorts.SelectedItem.ToString();
comPort.BaudRate = Convert.ToInt32(comboBoxBaud.Text);
try {
comPort.Open();
comPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
if (comPort.IsOpen) {
label1.Content = "COM PORT OPEN";
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
}
private void updateUI (string s) {
}
private void closeComBtn_Click(object sender , RoutedEventArgs e) {
if (comPort.IsOpen) {
comPort.Close();
label1.Content = "COM PORT CLOSED";
}
}
private void exitBtn_Click(object sender , RoutedEventArgs e) {
if (comPort.IsOpen) {
comPort.Close();
}
this.Close();
}
}
}
|
|
|
|
|
Member 13688816 wrote: My application goes in exception when I try to update the textbox.text What exception, and where does it occur?
|
|
|
|
|
"The calling thread cannot access this object because a different thread owns it."
I got it using
Application.Current.Dispatcher.Invoke(new Action(() => { textBox.AppenText(inData) }));
But now I have the problem that when I send my command by using serialPort.Write(cmd), I can't get the answer back
|
|
|
|
|
The data receive event is execute in it's own thread. You have to take care when updating UI elements from other threads. See How to: Make Thread-Safe Calls to Windows Forms Controls | Microsoft Docs[^].
A possible (untested) implementation:
private void updateUI (string s) {
if (this.InvokeRequired) {
this.Invoke(new Action( d => updateUI(d) ));
return;
}
} Then call updateUI() from your DataReceivedHandler .
|
|
|
|
|
Your "data received handler" is "empty"; what do you expect to happen?
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
FIXED EVERYTHING
I had to do a bit more of research and implement the dispatch function. Now everything works fine
and I'm able to communicate with my microprocessor
|
|
|
|
|
Hello!
We got this project that requires us to build data structures into a hierachical text structure ( like xml, or json).
When i search for json and .net, the libraries i find seem to be really good for serializing. But serializing isn't what i need. I need something like the System.Xml.Linq.XElement class. Just create a node and put other nodes inside. Supersimple.
I will try the most common libraries out there of course, but i would love to hear your experiences with it. Have you done something like that? Do yoo have recommendations for me?
|
|
|
|
|
Json.NET has support for LINQ to JSON. Providing you aren't looking to do anything mind blowingly complex, this should help. Introduction[^]
This space for rent
|
|
|
|
|