|
First, use int.TryParse (or double.TryParse if appropriate) to convert each value to an numeric:
double t1;
if (!double.TryParse(textBox1.Text, out t1))
{
... Report problem to user - he typed a bad number ...
return;
} When you have the four values, it's trivial:
TextBox4.Text = (t1 / (t2 * t3 * 60 ) * 100).ToString();
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
What happened to "We do not do your homework?"
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
It's a fine line between "doing the homework" and "giving enough so they can finish it", isn't it?
I didn't think just pointing him at the TryParse documentation would be enough, he is a beginner after all - and thoroughly lost by the look of it!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
On second thought, I think you're right. Your mentality is not "throw 'em to the wolves", but do what you can to help.
There is a difference between asking for a clue and asking for it to be done for you. Your post embodies the teaching spirit.
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
Thank you.
I think that's the nicest thing anyone has said to me all week.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I am writing a C# application with Visual Studio Express 2005 and I need to query the available com ports and their friendly names. The first part is easy, I can simply call SerialPort.GetPortNames(). In order to get the friendly names, I found the following code on the internet:
for (int i = 0; i < availableComPorts.Length; i++)
{
try
{
string temp = "(" + availableComPorts[i] + ")";
foreach (ManagementObject queryObj in searcher.Get())
{
if ((queryObj["Name"] != null) && (queryObj["Name"].ToString().EndsWith(temp)))
{
ComPortInfo comPortsInfo = new ComPortInfo();
comPortsInfo.officalName = availableComPorts[i];
comPortsInfo.userfriendlyDescription = queryObj["Caption"].ToString().Replace("(" + availableComPorts[i] + ")", "").Trim();
comPortsInfo.manufacturer = queryObj["Manufacturer"].ToString();
comPortInfoArrayList.Add(comPortsInfo);
}
}
}
catch (Exception)
{
}
}
The problem with the code above is that it takes about 1.5 seconds(!) to execute on my computer which is too slow. After further investigations I found the following post [winapi - How do I get a list of available serial ports in Win32? - Stack Overflow](https://stackoverflow.com/questions/1388871/how-do-i-get-a-list-of-available-serial-ports-in-win32) which refers to the following project: [CEnumerateSerial v1.34](http://www.naughter.com/enumser.html). This project seems very promising, especially the "Device Manager (SetupAPI - GUID_DEVINTERFACE_COMPORT)" method, which executes extremely quickly on my computer:
_Return_type_success_(return != 0) BOOL CEnumerateSerial::QueryRegistryPortName(_In_ ATL::CRegKey& deviceKey, _Out_ int& nPort)
{
BOOL bAdded = FALSE;
LPTSTR pszPortName = nullptr;
if (RegQueryValueString(deviceKey, _T("PortName"), pszPortName))
{
const size_t nLen = _tcslen(pszPortName);
if (nLen > 3)
{
if ((_tcsnicmp(pszPortName, _T("COM"), 3) == 0) && IsNumeric((pszPortName + 3), FALSE))
{
nPort = _ttoi(pszPortName + 3);
bAdded = TRUE;
}
}
LocalFree(pszPortName);
}
return bAdded;
}
_Return_type_success_(return != 0) BOOL CEnumerateSerial::QueryUsingSetupAPI(const GUID& guid, _In_ DWORD dwFlags, _Inout_ CPortsArray& ports, _Inout_ CNamesArray& friendlyNames)
{
#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
ports.clear();
friendlyNames.clear();
#else
ports.RemoveAll();
friendlyNames.RemoveAll();
#endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
HDEVINFO hDevInfoSet = SetupDiGetClassDevs(&guid, nullptr, nullptr, dwFlags);
if (hDevInfoSet == INVALID_HANDLE_VALUE)
return FALSE;
BOOL bMoreItems = TRUE;
int nIndex = 0;
SP_DEVINFO_DATA devInfo = { 0 };
while (bMoreItems)
{
devInfo.cbSize = sizeof(SP_DEVINFO_DATA);
bMoreItems = SetupDiEnumDeviceInfo(hDevInfoSet, nIndex, &devInfo);
if (bMoreItems)
{
BOOL bAdded = FALSE;
ATL::CRegKey deviceKey;
deviceKey.Attach(SetupDiOpenDevRegKey(hDevInfoSet, &devInfo, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_QUERY_VALUE));
if (deviceKey != INVALID_HANDLE_VALUE)
{
int nPort = 0;
if (QueryRegistryPortName(deviceKey, nPort))
{
#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
ports.push_back(nPort);
#else
ports.Add(nPort);
#endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
bAdded = TRUE;
}
}
if (bAdded)
{
ATL::CHeapPtr<BYTE> byFriendlyName;
if (QueryDeviceDescription(hDevInfoSet, devInfo, byFriendlyName))
{
#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
friendlyNames.push_back(reinterpret_cast<LPCTSTR>(byFriendlyName.m_pData));
#else
friendlyNames.Add(reinterpret_cast<LPCTSTR>(byFriendlyName.m_pData));
#endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
}
else
{
#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
friendlyNames.push_back(_T(""));
#else
friendlyNames.Add(_T(""));
#endif //#ifndef CENUMERATESERIAL_MFC_EXTENSIONS
}
}
}
++nIndex;
}
Now, the problem is that I don't know how to convert this to C#. I was able to convert some of it into C# using P/Invoke, for example:
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetupDiGetClassDevs(
ref Guid ClassGuid,
[MarshalAs(UnmanagedType.LPTStr)] string Enumerator,
IntPtr hwndParent,
uint Flags);
[StructLayout(LayoutKind.Sequential)]
struct SP_DEVINFO_DATA
{
public UInt32 cbSize;
public Guid ClassGuid;
public UInt32 DevInst;
public IntPtr Reserved;
}
[DllImport("setupapi.dll", SetLastError = true)]
static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
uint MemberIndex,
ref SP_DEVINFO_DATA DeviceInfoData);
but I'm unable to figure out how to convert the calls to ATL. Can anybody please advice on how I can convert the code to C#?
|
|
|
|
|
You should first figure out why your first solution was "slow" before jumping to a "new" solution.
And "slow" is relative.
Perhaps you're not accounting for dll load time; or should be doing your "port query" at startup as a "parallel" task.
And what do you mean by "friendly names"?
The port names are "COMx"; what do you expect to see?
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
I usually link in my dll into the .exe file to speed up the loading, but in this case I would prefer to not have to use a dll, instead I want to translate the C++ code into c# but I run into trouble with the ATL stuff. I need to enumerate com ports several times during runtime, it's not enough to do it only once.
Slow is more than 50 ms, less than that is fast. Here are some measurements from a StackOverflow forum thread that I apparently am not allowed to link to:
"SetupAPI1" using calls to SETUPAPI.DLL
Found com0com ports, also reported "friendly names", took 15ms.
"SetupAPI2" using calls to SETUPAPI.DLL
Did not find com0com ports, reported "friendly names", took 32ms.
Here are examples of friendly names:
Com1 "USB Serial Port"
Com2 "USB Serial Device"
Com3 "STMicroelectronics STLink Virtual COM Port"
|
|
|
|
|
Users perceive "lag" above 100ms.
My experience with users and com ports is that you burden them at (app) "install" time, when they also need to refer to the Control Panel Settings, you save their settings, and then let them forget about "COM" ports.
Any "refreshes" are done on demand. It's not repetetive.
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
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!
|
|
|
|
|