|
Apologies for the shouting but this is important.
When answering a question please:
- Read the question carefully
- Understand that English isn't everyone's first language so be lenient of bad spelling and grammar
- If a question is poorly phrased then either ask for clarification, ignore it, or mark it down. Insults are not welcome
- If the question is inappropriate then click the 'vote to remove message' button
Insults, slap-downs and sarcasm aren't welcome. Let's work to help developers, not make them feel stupid..
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
For those new to message boards please try to follow a few simple rules when posting your question.- Choose the correct forum for your message. Posting a VB.NET question in the C++ forum will end in tears.
- Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
- Keep the subject line brief, but descriptive. eg "File Serialization problem"
- Keep the question as brief as possible. If you have to include code, include the smallest snippet of code you can.
- Be careful when including code that you haven't made a typo. Typing mistakes can become the focal point instead of the actual question you asked.
- Do not remove or empty a message if others have replied. Keep the thread intact and available for others to search and read. If your problem was answered then edit your message and add "[Solved]" to the subject line of the original post, and cast an approval vote to the one or several answers that really helped you.
- If you are posting source code with your question, place it inside <pre></pre> tags. We advise you also check the "Encode "<" (and other HTML) characters when pasting" checkbox before pasting anything inside the PRE block, and make sure "Use HTML in this post" check box is checked.
- Be courteous and DON'T SHOUT. Everyone here helps because they enjoy helping others, not because it's their job.
- Please do not post links to your question into an unrelated forum such as the lounge. It will be deleted. Likewise, do not post the same question in more than one forum.
- Do not be abusive, offensive, inappropriate or harass anyone on the boards. Doing so will get you kicked off and banned. Play nice.
- If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums.
- No advertising or soliciting.
- We reserve the right to move your posts to a more appropriate forum or to delete anything deemed inappropriate or illegal.
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
Hello everybody, I pretty new to programming, what I want to do is a C# program that will send a message to a Microsoft teams group via a webhook connector of this group.
I was able to achieve it with a Desktop code(with form),but I need it to be a console program, I have pretty much copy/paste the code from my Desktop project to my console project, but there something that don't work. Here is my code from my desktop project:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test_team_2
{
public partial class Form1 : Form
{
string[] cmdLineMe = Environment.GetCommandLineArgs();
string webhookPdfTermine = "uri to my team groups;
HttpClient client = new HttpClient();
Message body = new Message();
string finalMessage = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < cmdLineMe.Length; i++)
{
finalMessage = cmdLineMe[i];
}
sendMsg();
}
public class Message
{
public string text { get; set; }
}
private async Task SendMsgAsync()
{
MessageBox.Show(finalMessage);
client.BaseAddress = new Uri(webhookPdfTermine);
body.text = finalMessage;
string serializeJson = JsonSerializer.Serialize(body);
StringContent content = new StringContent(serializeJson, Encoding.UTF8, "application/json");
_ = await client.PostAsync(client.BaseAddress, content);
}
void sendMsg()
{
MessageBox.Show("hello");
_ = SendMsgAsync();
}
}
}
And here is my code for my console project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
namespace TeamBots
{
class Program
{
string[] cmdLineMe = Environment.GetCommandLineArgs();
string webhookPdfTermine = "uri to my team groups";
HttpClient client = new HttpClient();
Message body = new Message();
string finalMessage = "";
static void Main(string[] args)
{
Program myprog = new Program();
for (int i = 0; i < myprog.cmdLineMe.Length; i++)
{
myprog.finalMessage = myprog.cmdLineMe[i];
}
myprog.sendMsg();
}
private async Task SendMsgAsync()
{
Console.WriteLine(finalMessage);
client.BaseAddress = new Uri(webhookPdfTermine);
body.text = finalMessage;
string serializeJson = JsonSerializer.Serialize(body);
StringContent content = new StringContent(serializeJson, Encoding.UTF8, "application/json");
_ = await client.PostAsync(client.BaseAddress, content);
}
void sendMsg()
{
_ = SendMsgAsync();
}
public class Message
{
public string text { get; set; }
}
}
}
Like I said before, I pretty new to programming, the code was taken from website there and there...
If anyone can help it will be very appreciated.
Thank you
|
|
|
|
|
We have a system that uses Wonderware AOS objects with quite a bit of AOS scripting which interacts with a Sql Server database.
The scripting exists to access data from PLC's, add additional information from a Sql Server database, then write the combined data to a Sql Server table.
I'm wondering if anyone has converted this to a .net app (prefer C#), that would interrogates the PLC's with OPC, and performs the same functionality as above (as regards Sql Server).
The desired result is to stop using AOS objects and exit from Mobileframe.
Thanks.
|
|
|
|
|
I have a data table with around 13000 rows. I want to add all of them to the database. Which method has the best performance, using C# and EF Core or using SQL Server stored procedures?
|
|
|
|
|
You're neglecting the specifics; e.g. SQL Server / EF Bulk Insert.
"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
|
|
|
|
|
Hi, i am using HZH_Controls.Controls.UCTextBoxEx to embed a UCTextBoxEx into a DataGridView control's TextBox field. The program is like below:
private HZH_Controls.Controls.UCTextBoxEx uctextBox1=null;
uctextBox1 = new HZH_Controls.Controls.UCTextBoxEx();
this.uctextBox1.Leave += new EventHandler(uctextBox1_Leave);
this.uctextBox1.TextChanged += new EventHandler(uctextBox1_TextChanged);
this.uctextBox1.Visible = false;
this.uctextBox1.KeyBoardType = HZH_Controls.Controls.KeyBoardType.UCKeyBorderNum;
private void uctextBox1_Leave(object sender, EventArgs e)
{
this.uctextBox1.Visible = false;
}
private void uctextBox1_TextChanged(object sender, EventArgs e)
{
this.dataGridViewAxisDefine.CurrentCell.Value = ((HZH_Controls.Controls.UCTextBoxEx)sender).Text;
this.uctextBox1.Visible = false;
}
private void DataGridViewAxisDefine_CurrentCellChanged(object sender, EventArgs e)
{
if ( this.dataGridViewAxisDefine.CurrentCell.ColumnIndex == 2)
{
Rectangle rectangle = dataGridViewAxisDefine.GetCellDisplayRectangle(dataGridViewAxisDefine.CurrentCell.ColumnIndex, dataGridViewAxisDefine.CurrentCell.RowIndex, false);
string value = dataGridViewAxisDefine.CurrentCell.Value.ToString();
this.uctextBox1.Text = value;
this.uctextBox1.Left = rectangle.Left;
this.uctextBox1.Top = rectangle.Top;
this.uctextBox1.Width = rectangle.Width;
this.uctextBox1.Height = rectangle.Height;
this.uctextBox1.Visible = true;
}
else
{
this.uctextBox1.Visible = false;
}
}
i just want people to click the TextBox field that is on the DataGridView to display a soft number pad and edit the numbers on it.
Now the error apears onto the line "
this.dataGridViewAxisDefine.CurrentCell.Value = ((HZH_Controls.Controls.UCTextBoxEx)sender).Text; ", saying "'
HZH_Controls.Controls.TextBoxEx ' object cannot cast to '
HZH_Controls.Controls.UCTextBoxEx ' "
The TextBoxEx is also a control of
HZH_Controls.Controls
, but i never use it.
The error message is translated from Chinese and may not precisely decribe the original meaning since i am using a Chinese version VS 2017.
So, my question is what's the problem cause this error and how to solve this problem? Many thanks in advance!
|
|
|
|
|
There is some code that you are not showing, but at a guess the sender variable is an instance of HZH_Controls.Controls.TextBoxEx which is not compatible with HZH_Controls.Controls.UCTextBoxEx . You need to check the documentation, or ask for help from, the people who write the HZH_Controls library.
|
|
|
|
|
When i change the "HZH_Controls.Controls.UCTextBoxEx" to "HZH_Controls.Controls.TextBoxEx", the program still works fine. The soft number pad can still pass numbers onto the Textbox field.
Yes, i need to check the documentation of HZH_Controls library.
Anyway thank you very much for your kind help!!!
|
|
|
|
|
Looking at the source code[^], the UCTextBoxEx is a user control which wraps a TextBoxEx instance.
When the TextBoxEx instance raises its TextChanged event, the parent UCTextBoxEx instance raises its own TextChanged event. But it passes the original sender through unchanged, which means the sender is the wrapped TextBoxEx instance, not the UCTextBoxEx instance.
This feels like a bug in the library, but there might be a reason for it. You could try reporting an issue[^], but bear in mind the author is Chinese and claims to have poor English.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you very much for your kind help!!! yes, it still works fine after changing "UCTextBoxEx" to "TextBoxEx". And i also need to check the source code that you provided and may reporting an issue on it.
|
|
|
|
|
Hello,
I am new using a token, but i have to use it in a little WCF.
I found this code here.
As i can see, this generate a token, but i have a few questions:
1. What is Payload and it is each variable?
2. After generate de Token, how to i use in my WCF?
3. Do i have to put the CODE in the WCF?
CODE
static void Main(string[] args)
{
Console.WriteLine("");
string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b372742
9090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
var securityKey = new Microsoft
.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
(securityKey, SecurityAlgorithms.HmacSha256Signature);
var header = new JwtHeader(credentials);
var payload = new JwtPayload
{
{ "some ", "hello "},
{ "scope", "http://dummy.com/"},
};
var secToken = new JwtSecurityToken(header, payload);
var handler = new JwtSecurityTokenHandler();
var tokenString = handler.WriteToken(secToken);
Console.WriteLine(tokenString);
Console.WriteLine("Consume Token");
var token = handler.ReadJwtToken(tokenString);
Console.WriteLine(token.Payload.First().Value);
Console.ReadLine();
}
|
|
|
|
|
I am getting this error when I try to compile the below code:
string key = "mykey";
byte[] buf = Decrypt(key, payload);
unsafe
{
fixed(byte* ptr = buf)
{
IntPtr memoryAddress = (IntPtr)ptr;
VirtualProtect(memoryAddress, (UIntPtr)buf.Length, (UInt32)Protection.PAGE_EXECUTE_READWRITE, out uint lpfOldProtect);
ShellcodeDelegate func = (ShellcodeDelegate)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(ShellcodeDelegate));
func();
}
Errors:
pi.cs(60,124): error CS1525: Invalid expression term 'uint'
pi.cs(60,138): error CS1002: ; expected
pi.cs(60,138): error CS1525: Invalid expression term ')'
ooooo
modified 3 days ago.
|
|
|
|
|
Check your C# version - the syntax Foo(out type varName) was only added at C#7.0
"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!
|
|
|
|
|
Thanks for your answer. It was a version issue.
ooooo
|
|
|
|
|
You're welcome!
"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!
|
|
|
|
|
Complex class from Numerics does not have any Parse method
How to write parse method
public static bool TryParse(string s,out Complex z)
{
}
|
|
|
|
|
And?
What have you tried?
Where are you stuck?
What help do you need?
"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!
|
|
|
|
|
Member 15634071 wrote: in CE (Central Europe) where I live it is comma Yes, that makes it 'interesting' if parsing the (a,b) format as you have no idea whether the ',' is a dec point or a value separator. e.g. (1,2,3,4) could only be 1.2+3.4i but (1,2,3) could be 1.2+3i or 1+2.3i Just to make it even more fun, US / UK / other countries have numbers where a comma can be a thousands separator e.g. (234.567,999,888.000) could be one of several complex numbers. e.g. 234.567+999888.0i, 234.567999+888.0i, or 234.567999888+0i.
Have you looked at how Point objects are parsed (they too can have an (x,y) format where x and y are decimal numbers)?
|
|
|
|
|
Can you write en example ?
Normally not in the comment section
|
|
|
|
|
 There doesn't seem to be a Point.Parse() / Point.TryParse() so that did not get very far!
Normally, we don't give working answers, just rough pointers. However, I had wanted to create a Point.Parse() / Point.TryParse() for a different project, but had not got around to it; so this was a good excuse to write one .
This version allows (x-yi) and (x-yb) as well as your formats plus you can use (x, y) [with a space after the real/imaginary separator] to disambigute for cultures that use ',' as a decimal point.
My basic functions look like:
public static class Complex2
{
public static Complex ComplexParse(string text)
{
string[] parts;
string parsedText = text.Trim();
if (parsedText.StartsWith("(") && parsedText.EndsWith(")"))
{
parsedText = parsedText.Substring(1, parsedText.Length - 2).Trim();
if (parsedText.Contains("+") && (parsedText.EndsWith("i") || parsedText.EndsWith("j")))
{
parts = parsedText.Split('+');
if (parts.Length == 2)
return
new Complex(
real: double.Parse(parts[0].Trim()),
imaginary: double.Parse(parts[1].Substring(0, parts[1].Length - 1).Trim())
);
throw new ArgumentException("Complex number format not recognised (multiple '+' chars)");
}
else if (parsedText.Substring(1).Contains("-") && (parsedText.EndsWith("i") || parsedText.EndsWith("j")))
{
parts = parsedText.Substring(1).Split('-');
if (parts.Length == 2)
return
new Complex(
real: double.Parse(parsedText.Substring(0, 1) + parts[0].Trim()),
imaginary: -double.Parse(parts[1].Substring(0, parts[1].Length - 1).Trim())
);
throw new ArgumentException("Complex number format not recognised (multiple '+' chars)");
}
else if (parsedText.Contains(","))
{
parts = parsedText.Split(',');
if (parts.Length == 2)
return
new Complex(
real: Double.Parse(parts[0].Trim()),
imaginary: Double.Parse(parts[1].Trim())
);
int ix = parsedText.IndexOf(", ");
if (ix < 1)
throw new ArgumentException("Complex number format not recognised (ambiguous use of commas)");
return
new Complex(
real: double.Parse(parsedText.Substring(0, ix).Trim()),
imaginary: double.Parse(parsedText.Substring(ix + 1).Trim())
);
}
else
throw new ArgumentException("Complex number format not recognised");
}
else
throw new ArgumentException("Complex number not enclosed in parentheses");
}
public static bool ComplexTryParse(string text, out Complex ComplexOut)
{
try
{
ComplexOut = ComplexParse(text);
return true;
}
catch (Exception)
{
ComplexOut = new Complex(0.0, 0.0);
return false;
}
}
}
and to use as extension methods for string:
public static class StringExtensions
{
public static Complex ComplexParse(this string fromText) =>
Complex2.ComplexParse(fromText);
public static bool ComplexTryParse(this string fromText, out Complex result) =>
Complex2.ComplexTryParse(fromText, out result);
}
Sample testing:
class Program
{
static void Main(string[] args)
{
TryComplex("(1.0,0.5)");
TryComplex("(1.1+0.55i)");
TryComplex(" ( 1.023 + 0.512 j ) ");
TryComplex("(0, -1)");
TryComplex("(0-1i)");
TryComplex("(-10-2j)");
TryComplex("(-10,-3)");
TryComplex(" ( 1.8-1i ) ");
TryComplex(" ( 1.9+1i ) ");
TryComplex("(1,4, 2,5)");
TryComplex(" ( 1,1i ) ");
TryComplex("(1,4,2,5)");
TryComplex(" ( 1.023 + 0.512 + j ) ");
TryComplex(" ( 1.023, 0.512 j ) ");
TryComplex(" ( 1.023i 0.512 j ) ");
Console.ReadKey();
}
static void TryComplex(string text)
{
Console.Write($"Trying {text}: ");
try
{
Complex result = text.ComplexParse();
Console.WriteLine($"({result.Real}, {result.Imaginary})");
}
catch (Exception ex)
{
Console.WriteLine($"*** Failed: {ex.Message} ***");
}
}
}
Note: For these to work, I have used
using System.Numerics;
using static ComplexParser.Complex2;
to save having to use namespace prefixes
Hope this is of some use.
|
|
|
|
|
There's a few edge cases that would break that code - including complex numbers shown in the Microsoft docs. For example:
TryComplex("(-8.98846567431158E+307, -8.98846567431158E+307)"); That's probably why Microsoft doesn't support the X+Yi syntax by default.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
There's probably a lot of edge cases that would break the code. It uses the QAD design model (Quick And Dirty) aka "just good enough".
|
|
|
|
|
I've just tried your example (plus its x+yi and x-yi equivalents) with the code that I wrote yesterday and the results are not as bad as one might have expected:
Trying (-8.98846567431158E+307, -8.98846567431158E+307): (-8.98846567431158E+307, -8.98846567431158E+307)
Trying (-8.98846567431158E+307,-8.98846567431158E+307): (-8.98846567431158E+307, -8.98846567431158E+307)
Trying (-8.98846567431158E+307+-8.98846567431158E+307i): *** Failed: Complex number format not recognised (multiple '+' chars) ***
Trying (-8.98846567431158E+307-8.98846567431158E+307i): *** Failed: Complex number format not recognised (multiple '+' chars) *** The sample you cited works! As does dropping the space after the comma.
The x+yi and x-yi equivalents do throw an exception, but the exception message is reasonably explicit as to where the problem is. If the OP wants to check for + after an E/e followed by zero or more spaces then I'll leave it as an exercise ... it isn't rocket science to do, but could get a bit messy.
|
|
|
|
|
If you are not familiar with this technique, I will publish a Tip/Trick soon.
Assuming you know how a nested inner class (which implements an Interface) can be declared 'private, and still be accessed by public methods in the enclosing outer class: which does make direct access to inner classes of the OuterClass prohibited.
Do you think the technique shown here is evil, undesirable, or ... ?
usage:
OuterClass1 oc1 = new OuterClass1();
var cat1 = oc1.AddSomething(new Cat("cat1", "meow"));
var cat2 = oc1.AddSomething(new Cat("cat2", "hiss"));
var dog1 = oc1.AddSomething(new Dog("dog1"));
var cat1instance = oc1.GetSomething("cat1"); class:
using System;
using System.Collections.Generic;
using System.Linq;
namespace NestedClassExample1
{
public interface ISomething1
{
string Name { get; }
}
public class OuterClass1
{
private List<ISomething1> Somethings = new List<ISomething1>();
internal ISomething1 AddSomething(ISomething1 newsomething)
{
Somethings.Add(newsomething);
return newsomething;
}
internal ISomething1 GetSomething(string name)
{
return Somethings.FirstOrDefault(smtng => smtng.Name == name);
}
}
public class Cat : ISomething1
{
public Cat(string name, string sound = "")
{
Name = name;
CatSound = sound;
}
public string Name { get; }
public string CatSound { set; get; }
}
public class Dog : ISomething1
{
public Dog(string name, string sound = "")
{
Name = name;
DogSound = sound;
}
public string Name { get; }
public string DogSound { set; get; }
}
public class Tiger : ISomething1
{
public Tiger(string name) { Name = name; }
public string Name { get; }
}
}
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
modified 12-May-22 6:18am.
|
|
|
|
|