|
I am new to C# and .net core , I am building billing program to read data from PBX which send on defined TCP port.
It does work , I receive the data but randomly tcp port stop listening and when I check window resource monitor I can see under Network --> Listening Ports --> it doesn't show .
But window service is running, then after restart window service i can see port start listening again.
There is no conflict of ports that I am sure of.
My code logic is as below :
using CDR.Models;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace CDR.Helpers
{
public class CDRServer
{
public static void Listen()
{
Logger.Log("Starting 3cX Listener");
TcpListener server = null;
try
{
Int32 port = 5015;
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
server = new TcpListener(ipAddress, port);
server.Start();
Byte[] bytes = new Byte[1024];
String data = null;
while (true)
{
Console.WriteLine($"Waiting for a connection... on {ipAddress.ToString()} and {port.ToString()}");
Logger.Log($"Waiting for a connection... on {ipAddress.ToString()} and {port.ToString()}");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
Logger.Log("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
Logger.Log($"Received: {data}");
try
{
CDRModel cdr = new CDRModel();
var datasplit = data.Split(',');
cdr.historyidofthecall = datasplit[0];
cdr.callid = datasplit[1];
cdr.duration = datasplit[2];
Logger.Log($"Before Date: {DateTime.Parse(datasplit[3]).ToString()}");
cdr.timestart = DateTime.Parse(datasplit[3]);
Logger.Log($"After Date: {cdr.timestart.ToString()}");
if (!string.IsNullOrEmpty(datasplit[4]))
{
cdr.timeanswered = DateTime.Parse(datasplit[4]);
}
cdr.timeend = DateTime.Parse(datasplit[5]);
cdr.reason_termination = datasplit[6];
cdr.from_no = datasplit[7];
cdr.to_no = datasplit[8];
cdr.from_dn = datasplit[9];
cdr.to_dn = datasplit[10];
cdr.dial_no = datasplit[11];
cdr.reason_changed = datasplit[12];
cdr.final_number = datasplit[13];
cdr.final_dn = datasplit[14];
cdr.from_type = datasplit[15];
cdr.missed_queue_calls = datasplit[16];
cdr.chain = datasplit[17];
Logger.Log(JsonConvert.SerializeObject(cdr));
if (!File.Exists("Db.txt"))
Console.WriteLine("Db.txt file not found");
var url = File.ReadAllText(@"Db.txt");
Logger.Log(url);
RestClient client2 = new RestClient(url);
RestRequest request = new RestRequest(Method.POST);
request.AddParameter("application/json", JsonConvert.SerializeObject(cdr), ParameterType.RequestBody);
var response = client2.Execute(request);
}
catch (Exception ex)
{
Logger.Log(ex);
}
}
client.Close();
Logger.Log("Client Closed");
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
Logger.Log(e);
}
finally
{
server.Stop();
Logger.Log("Server Stopped");
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}
|
|
|
|
|
You may well have an unhandled exception killing your application. For instance, you use DateTime.Parse, but what happens if you don't receive a valid date? Use TryParse instead.
|
|
|
|
|
Hello I have the following problem:
We have embedded different visuals from a PBIX file onto a asp.net core razor view.
We have achieved that when a user clicks on a row in a table visual, detect the item and corssfilter the other embedded visuals as the user clicks.
On the Power BI environment you can do the same, but by pressing the CTRL key, you can select multiple rows and then it will filter the whole visuals on that page.
As we achieved the crossfiltering selecting just one we thought it would do the same by pressing CTRL, the problem is that PowerBI Embedded visual is not detecting the CTRL key and it is not actually detecting that we are selecting more than one row and it changes the whole filters to the first selected row.
|
|
|
|
|
I`m going to ask a question the answer to which everybody knows for at least a decade but how does the net framework works? I know that it works like most libraries. You attach the library headers to your project and when the program is run on the target computer it will expect to find the binaries (dll etc.) of the library, the headers of which were previously added to the program. But how is the Net library different from a library granting access to containers, math functions or graphical capabilities. In other words what capabilities does the Net library is adding to your program? Thanks for feedback.
|
|
|
|
|
ok, I`ll start from the other end. What is the difference between a MFC App and a WinForms App? What you`re presented on screen by windows is achieved through binary code, a unique windows frame and windows controls displaying format. So it`s really only about the convenience in coding (which programming language you find easier), after compilation the programs will fit to the same rules regardless if their binary was created from C# (WinForms) code or C++ code (MFC).
If I think about it a windows app bust me like a script even if it`s in a binary form. Several scripts can reside along side each other, this is what it must have been like since windows 95.
The obvious flow in a program would be to call and update the hierarchy/chain of windows from within the main function but that`s not what is taking place in practice, the hierarchy is hidden away, all you can have is feedback when the user is interacting with a control.
modified 18-Feb-22 1:30am.
|
|
|
|
|
That is either too simplistic or too broad or something else.
A library, any library, in any language, provides functionality defined by the library.
A library that provides a method that does math might provide a method that does a maximum of two numbers. It would do that because that is a mathematical operations.
A library that provides a method that returns the size of a file on the file system does that because the library does file system operations. And the size of a file is something that people like to know when the do stuff with the file system.
If you want to know how the maximum function is written then you
1. Learn math
2. Learn the programming language.
3. Code the function
If you want to know how to get the file size then
1. You learn exactly what that means (learn more about file systems.)
2. You will need to research core abilities in other libraries associated with the target file system.
3. Learn the programming language
4. Code the function.
Now you might want to know more about 3 in the prior case. You need to learn about the Microsoft (not .Net) Windows API. And then learn how C# interacts with libraries that are not other C# libraries.
If you want more information than that then it will require books (plural) to fully describe it.
|
|
|
|
|
In essence they are all the same, and the difference is in what the developer actually sees. In C/C++ you make direct calls to the functions in the Win32 libraries. In MFC most of those calls are wrapped in a class that is instantiated, and then called through the objects methods. In C#/VB.NET the Win32 calls are wrapped in the .NET framework classes. In Python they are wrapped in Python libraries. And all the libraries make this work by using the system calls provided by the operating system. The real issue is how these frameworks make the developer's job easier, by hiding the (often complicated) system interface.
|
|
|
|
|
Thanks Richard
Quote: In MFC most of those calls are wrapped in a class that is instantiated
Someone like me find this statement to be revealing
|
|
|
|
|
Hello and thank you for any help you may provide. I have a problem that is in my head for the past week and that I can't resolve and I will appreciate any help in resolving it.
In my head I would like to classify objects by category and sub-category, and have the sub-category have object properties according to the subtype... for example
OBJECT : Motorcycle => have name like "Harley Davidson 500 Street", etc
> Category : Automotive > Subcategory : Motorcycle > THEN subcategory has a set of sub-properties like: Engine, Brand, Color, Price,
OBJECT Handbag => have name like "Gucci Guapisima Wherever Edition", etc
> Category : Clothing and Apparel > Subcategory : Brand Handbags > THEN subcategory has a set of sub-properties like: Material, Size, Color, Price,
Not the way I see it is... Most of object share the majority of this structure, like all objects have name, all of them belong to a category and a sub-category, now the problem comes on how to setup properties for each sub-category... for example both objects share the Color and Price but not the other properties. How to make this non-hard-coded? in other words, we know some of the properties are shared between objects, how can we do a model like this and then put this into a form?
I could do a dictionary but in the end, how do I validate them in the form?
Thanks for any help you could provide me.
|
|
|
|
|
You are referring to Classes. In example 1 your base class is Automotive , and the derived class is MotorCycle . You could also have another derived class named Car , etc. See Classes | Microsoft Docs[^] for full details.
|
|
|
|
|
Guillermo Perez wrote: How to make this non-hard-coded?
If you mean that the complete list of properties aren't / can't be known "up front" when you're compiling your code, then you'll need something like an Entity–attribute–value model[^].
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you mr Richard, this is more a realistic approach to what I'm looking for, thank you again!
|
|
|
|
|
using System.Diagnostics;
namespace cpu_performance
{
internal class Class1
{
static void Main(string[] args)
{
PerformanceCounter cpuCounter;
PerformanceCounter ramCounter;
cpuCounter = new PerformanceCounter
{
CategoryName = "Processor",
CounterName = "% Processor Time",
InstanceName = "_Total"
};
cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
Console.WriteLine("Computer CPU Utilization rate:" + cpuCounter.NextValue() + "%");
Console.WriteLine("The computer can use memory:" + ramCounter.NextValue() + "MB");
Console.WriteLine();
while (true)
{
System.Threading.Thread.Sleep(1000);
DateTime localDate = DateTime.Now;
Console.WriteLine("Computer CPU Utilization rate:" + cpuCounter.NextValue() + " %");
Console.WriteLine("The computer can use memory:" + ramCounter.NextValue() + "MB");
Console.WriteLine("Local date and time: {0}, {1:G}", localDate.ToString(), localDate.Kind);
Console.WriteLine();
if ((int)cpuCounter.NextValue() > 80)
{
System.Threading.Thread.Sleep(100 * 60);
}
}
}
}
}
|
|
|
|
|
Few questions for you to think about
- Which database - relational, graph, document?
- What is the database design like - tables, columns, FKs etc.
Then, find a suitable library which allows you to connect to the database and writes to it. For example if you choose SQL or any other relational database, you could make use of ADO.Net and write the database through dataset or direct queries.
"It is easy to decipher extraterrestrial signals after deciphering Javascript and VB6 themselves.", ISanti[ ^]
|
|
|
|
|
1. Learn the basics of how databases work. Both design and actually using one.
2. Choose a database to use
3. Learn how C# interfaces with databases in general and specifically how the database in 2 works with C#.
4. Design a table that will hold the data. This follows from 1.
5. Put all of the above together.
|
|
|
|
|
I know this may seem arbitrary to some, but the nature of the project that I am currently working on makes this capability an easy way to solve several problems.
I want an efficient, seamless way to integrate values into a stream of characters. I have done this in the past by just converting byte values into chars or even using value.tostring() but it would be more efficient if the characters could be read directly from the memory containing the values. (Examples: an integer is read as 2 characters, a long is read as 4 characters and a GUID is read as 8 characters). This would be really simple in C++. In c# it is turning out to be a huge challenge.
I tried using a generic with using StructLayout.Explicit but I got a runtime error stating that this is not supported. Using non-generics doesn't work either because strings and arrays are classes while values are structs and mixing them also doesn't work for the simple reason that the non zero terminated strings used in .NET track data that is probably inconsistent with this layout.
Is there any way to directly read (or even copy) data from numeric value bytes into a string? I can think of one possibility using unsafe copying but was wondering if I had any other better (more efficient) options.
|
|
|
|
|
I was unable to create a structure that did this. However, I was able to create a generic extender that uses "unsafe" copying to perform the task. The code is below. Still not sure this is the most efficient way to accomplish the task, but it works. The code requires using System.Runtime.InteropServices
public unsafe static string ToBytewiseString<T>(this T item) where T : struct
{
Type t = typeof(T);
int size = t.GetSize();
GCHandle pinnedHandle = GCHandle.Alloc(item, GCHandleType.Pinned);
IntPtr ptr = pinnedHandle.AddrOfPinnedObject();
StringBuilder result = new StringBuilder();
int increment;
if ((size % 2) == 1)
increment = 1;
else
increment = 2;
for (int offset = 0; offset < size; offset += increment)
{
char* c = (char*)((byte*)ptr + offset);
if (increment == 1)
{
ushort c_ = *c;
result.Append((char)(c_ >> 4));
--offset;
increment = 2;
}
else
result.Append(*c);
}
pinnedHandle.Free();
return result.ToString();
}
modified 29-Dec-21 2:32am.
|
|
|
|
|
I am tempted to suggest that you switch to C/C++.
If I understand your question right, you are asking for a C# equivalent of C/C++ 'union'. In my opinion, not offering unions is one of the strong arguments for C# over C/C++.
For the oldtimers: union is a C variant of FORTRAN COMMON blocks, which is one of the craziest ideas of language design! Also, it was one of the greatest threats ever to software robustness.
Doing a simple search for 'C# union' I hit upon C# equivalent to C "union"[^]. I never was aware of StructLayout(LayoutKind.Explicit) and FieldOffset(). Honestly: I haven't been missing out on anything valuable. I may try to forget that I have ever seen it. But maybe you can make use of it.
|
|
|
|
|
trønderen wrote: union is a C variant of FORTRAN COMMON blocks No, COMMON blocks were there so you could share memory between modules. A C union does not provide any sharing capability.
|
|
|
|
|
The common property between unions and common blocks is that they both provide to different users a common blob, telling: Here is a binary blob - interpret it any way you want!
Details in accessability are different; in C you may have somewhat better control over which modules have access to the union definition. And you have collected all the different interpretations of that binary blob in one place (at least until you start casting pointer types).
Yet, the basic concept is the same: A binary blob that can be interpreted in any way that the accessor would like to. Sure, it must be one of the alternatives in the union definition. Just like an interpretation of a Fortran COMMON block must be according to one of the alternative source code definitions that COMMON block in the modules that may access it.
You may argue that collecting the COMMON block definitions / union alternatives in a single place is an improvement. Yes, it is, but the basic idea of a binary blob providing multiple interpretations is the same.
You may argue that while any Fortran module might access that binary COMMON blob, only those C modules including the definition of the union, and knowing the address of (if you like: a pointer to) a union instance, this doesn't give any sort of protection against the uncontrolled interpretation of the binary blob.
Even Fortran COMMON block had some accessability control: You had not only the plain, anonymous COMMON blocks but also named COMMON blocks - sort of comparable to letting only selected modules #include the union type definition: If you didn't know the name of the blob, you didn't have access to it. Sure, it was a poor kind of protection, but lots of protection is based on the (lack of) knowledge of how to access it. C/C++ provides a somewhat better protection.
In this case, considering how easily any C pointer can be cast into a pointer of any other type - and note: the definition of the target type is arbitrary; it doesn't have to be any centrally managed type definition - the type control of C/C++ lies much closer to the weak Fortran type check than to that of C#.
|
|
|
|
|
Whilst you could use COMMON (in FORTRAN) to 'union' data in separate routines, you could not redefined the same COMMON block in the same routine. However, you could use another statement called EQUIVALENT (IIRC - it is some decades since I last wrote any FORTRAN) which does do 'union's - it was often used to remap data in COMMON blocks, but it was not restricted solely to data in COMMON blocks although that was its most frequent use in programs that I inherited in the 1980s.
|
|
|
|
|
Geesh. Did you read my OP? Considering the rest of your post, I guess I shouldn't be that surprised. I already tried an Explicit layout. From my OP: "I tried using a generic with using StructLayout.Explicit but I got a runtime error stating that this is not supported". In other words currently, .NET doesn't allow using explicit layouts with generics. And just because YOU don't find anything valuable doesn't mean it isn't. You apparently don't understand the nature of efficient memory management; nor "robustness"; and your disregard for "oldtimers" is very revealing about both your experience and nature. I would change that attitude before you spend your life eating your words. FYI, my reply above to my own topic is a solution to the problem. What is more robust than not having to introduce a new data type?
modified 30-Dec-21 2:48am.
|
|
|
|
|
primem0ver wrote: ou apparently don't understand the nature of efficient memory management; nor "robustness"; and your disregard for "oldtimers" is very revealing about both your experience and nature.
Hmmmm...
I have 15 years in C/C++. And probably 10 in assembly. I worked on systems with 4k memory.
I have written heap management replacement systems for C and C++ specifically implemented to improve performance for specific applications.
And I have spent decades doing bit twiddling. And I have used the union mechanism in C/C++.
I also have more than a decade in Java. And more than a decade in C#. Each.
In contrast to that I specialize in large systems built to handle millions of customers with sustained throughput of thousands of TPS. I have friends who work with hundreds of thousands of sustained TPS.
I have profiled applications extensively in C++, C# and Java. Not to mention decades of designing applications.
Just wanted to establish what my actual experience is before commenting on what you said.
Presumably this is based on an actual documented design or actual profiling of an existing application under realistic loads and on realistic hardware.
Given that is the case then I would suggest is that if you have a project which actually requires a micro optimization at that level that you should seriously think of using a different language than C#. Such as C/C++. You can create a library with the required functionality and link it in to your C# application. Or even create a stand alone application which handles requests from the C# app. If I had that actual need I would go with the stand alone server. It is going to make maintenance and implementation a lot easier.
|
|
|
|
|
trønderen wrote: I am tempted to suggest that you switch to C/C++.
That is what I was thinking also.
trønderen wrote: I may try to forget that I have ever seen it. But maybe you can make use of it.
lol. Probably a good idea. Tricks like that in C/C++ were to, presumably, to squeeze extra performance out of some small system. Large systems are not impacted by micro optimizations and so one should focus on real performance solutions rather than attempting stuff like this.
|
|
|
|
|
I use MemoryStreams and BinaryReaders / BinaryWriters for handling "binary" data; "characters" being something that depends on the encoding.
"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
|
|
|
|