Skip to content

C#

C# discussions

This category can be followed from the open social web via the handle c-065f1d12@forum.codeproject.com

93.7k Topics 383.1k Posts
  • Gawd but I hate the way MS changed null handling...

    2
    0 Votes
    2 Posts
    119 Views
    No one has replied
  • I need to convert a string to a float....

    visual-studio data-structures question
    9
    0 Votes
    9 Posts
    170 Views
    C
    With this extension we can parse strings directly to a numeric type static bool Fail<T>(this object _, out T item) where T : struct { item = default; return false; } static bool Pass<T>(this object obj, out T item) where T : struct { Type conversionType = typeof(T); item = (T)Convert.ChangeType(obj, conversionType); return true; } const string System_Int16 = "System.Int16"; const string System_UInt16 = "System.UInt16"; const string System_Int32 = "System.Int32"; const string System_Int64 = "System.Int64"; const string System_UInt32 = "System.UInt32"; const string System_Single = "System.Single"; const string System_Double = "System.Double"; const string System_UInt64 = "System.UInt64"; const string System_Byte = "System.Byte"; const string System_Decimal = "System.Decimal"; const string System_SByte = "System.SByte"; const string System_Numerics_BigInteger = "System.Numerics.BigInteger"; public static bool TryParse<T>(this string value, out T item) where T : struct { var conversionType = typeof(T); var floatType = typeof(float); var doubleType = typeof(double); var decimalType = typeof(decimal); if(conversionType != floatType && conversionType != doubleType && conversionType != decimalType && value.Contains('.')) { //we're not converting to float, double or decimal //there's no rounding, we just drop everything from the "." value = value.Remove(value.LastIndexOf('.')); } return conversionType.FullName switch { System_Int16 => short.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_UInt16 => ushort.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Decimal => decimal.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Int32 => int.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Int64 => long.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_UInt64 => ulong.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_UInt32 => uint.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Single => float.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Double => double.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Byte => byte.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_SByte => sbyte.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), System_Numerics_BigInteger => BigInteger.TryParse(value, out var result) ? result.Pass(out item) : value.Fail(out item), _ => conversionType.Fail(out item) } ; }
  • 2 tera term application process within winform

    algorithms help tutorial question
    2
    0 Votes
    2 Posts
    70 Views
    S
    The easiest way is not to try to “type” into Tera Term, just use its macro support. From your DataGridView click event, generate a .ttl file like: sendln "your command here" Then run it with: Process.Start("ttpmacro.exe", "myscript.ttl"); That’ll send the command straight into the right Tera Term session. If you don’t need Tera Term at all, just use SerialPort.WriteLine() in C# instead.
  • Augmented reality project

    2
    0 Votes
    2 Posts
    138 Views
    S
    If you want to drop a virtual object into video frames in C#, you’ll need two parts: Frame handling - use EmguCV (OpenCV wrapper for C#) to read/write video. Rendering - either fake it with Graphics (draw shapes + shadows) or go full 3D with Unity/HelixToolkit, where you can match light and cast shadows. Here’s a tiny fake example with EmguCV to show the idea (draws a ball + shadow on each frame): var cap = new VideoCapture("input.mp4"); var writer = new VideoWriter("output.mp4", FourCC.H264, 30, cap.Width, cap.Height, true); Mat frame = new Mat(); while (cap.Read(frame)) { var img = frame.ToImage<Bgr, byte>().ToBitmap(); using (var g = Graphics.FromImage(img)) { g.FillEllipse(Brushes.Gray, 260, 260, 100, 100); // shadow g.FillEllipse(Brushes.Blue, 250, 250, 100, 100); // object } writer.Write(new Image<Bgr, byte>(img).Mat); } That’s the basic overlay idea. For real lighting/shadows, you’ll need a 3D engine (Unity + C#) where you can match scene light and render the object properly.
  • Remembering the state of a property.

    question design
    3
    0 Votes
    3 Posts
    131 Views
    OriginalGriffO
    I do a similar thing for forms: each "generic" form remembers it's own position on screen, and will open there regardless of which application caused it to be created (so a "move files" project displays a status screen which appears in the same place from multiple apps). The way I do it is to create an ini file under the %Appdata% folder, and read that in my Load handler, then when teh form closes I check and if neccessary update the ini file: /// <summary> /// Restore size and location (if the user doesn't /// override it) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void frmMain_Load(object sender, EventArgs e) { //TODO: Remove this code to not save and restore your form location and size if ((ModifierKeys & Keys.Shift) == 0) { this.LoadLocation(); } } /// <summary> /// Save the size and location (if the used doesn't /// override it) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { //TODO: Remove this code to not save and restore your form location and size if ((ModifierKeys & Keys.Shift) == 0) { this.SaveLocation(); } } /// <summary> /// Get the current user data folder /// </summary> public static string UserDataFolder { get { Guid appGuid = AppGuid; string folderBase = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string dir = string.Format(@"{0}\{1}\", folderBase, appGuid.ToString("B").ToUpper()); return CheckDir(dir); } } /// <summary> /// Fill out the static properties /// </summary> static Storage() { LocationsStorageFile = UserDataFolder + "control.storage.locations"; } /// <summary> /// Save the control location /// (Because a Form is derived from Control, it works /// for them as well) /// </summary> /// <param name="control">Form to save location of</param> /// <param name="instance">Instance identifier (for use with multiple instances)</param> public static void SaveLocation(this Control control, string instance = null) { string controlName = control.GetType().Name; if (!File.Exists(LocationsStorageFile)) { CreateBlankLocationFile(); } DataTable dt = ReadXML(LocationsStorageFile); if (dt.Columns.Count >= 6) { bool ignoreInstance = string.IsNullOrWhiteSpace(instance); DataRow current = dt.NewRow(); // Assume new row or instance. current["ControlName"] = controlName; current["Instance"] = instance ?? ""; foreach (DataRow row in dt.Rows) { if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance)) { // Found it! //current = row; dt.Rows.Remove(row); break; } } current["LocationX"] = control.Location.X; current["LocationY"] = control.Location.Y; current["SizeW"] = control.Size.Width; current["SizeH"] = control.Size.Height; dt.Rows.Add(current); WriteXML(dt, LocationsStorageFile); } } /// <summary> /// Load the Control location /// (Because a Form is derived from Control, it works /// for them as well) /// </summary> /// <param name="control">Form to save location of</param> /// <param name="instance">Instance identifier (for use with multiple instances)</param> public static void LoadLocation(this Control control, string instance = null) { string controlName = control.GetType().Name; if (!File.Exists(LocationsStorageFile)) { CreateBlankLocationFile(); } DataTable dt = ReadXML(LocationsStorageFile); if (dt.Columns.Count >= 6) { bool ignoreInstance = string.IsNullOrWhiteSpace(instance); DataRow current = dt.NewRow(); // Assume new row or instance. current["ControlName"] = controlName; current["Instance"] = instance ?? ""; current["LocationX"] = control.Location.X; current["LocationY"] = control.Location.Y; current["SizeW"] = control.Size.Width; current["SizeH"] = control.Size.Height; foreach (DataRow row in dt.Rows) { if (row["ControlName"] as string == controlName && (ignoreInstance || row["Instance"] as string == instance)) { // Found it! current = row; int x, y, w, h; if (int.TryParse(current["LocationX"].ToString(), out x) && int.TryParse(current["LocationY"].ToString(), out y) && int.TryParse(current["SizeW"].ToString(), out w) && int.TryParse(current["SizeH"].ToString(), out h)) { control.Location = new Point(x, y); control.Size = new Size(w, h); } break; } } } }
  • 0 Votes
    22 Posts
    397 Views
    B
    Your BUTTON_LIST_str array contains the class System.String Your APPLY_BUTTON_CFG method needs the class System.Windows.Forms.Button as the parameter Theres is no way to convert a string to a button.
  • Should 0.5 round up or down?

    question
    21
    0 Votes
    21 Posts
    481 Views
    B
    I learned in school: "When you have a 5 to round from; the number to round to shall be even." Let me give you some examples: Rounding to no decimals: 0.5 --> 0 1.5 --> 2 2.5 --> 2 3.5 --> 4 Rounding to one decimal: 0.35 --> 0.4 0.45 --> 0.4 0.55 --> 0.6 0.65 --> 0.6
  • 0 Votes
    7 Posts
    95 Views
    B
    I would use switch statements, multiple switch statements inside switch statements! Sounds complicated? Bare with me. Start with a a TryParse to find out if your input contains numbers-only or not. (not digits-only) You might need to handle different decimal signs, period or comma. Now you can call two different switches: Inside the numbers-only switch there probably wouldn't be many 'case' statements. Use TryParse or ConvertTo to get a Double. Examine the value you got so it is within reason. Convert the Double to a suitable integer or keep it as is depending on what you need. Inside the digits+char switch you may use String.Contains('some char') to branch out one of these: 1) More switches depending on what character was found - Maybe branch even further depending on what position the character was found... (maybe not, but you get what I'm saying?) 2) Different methods (with good names explaining what they do) Inside some of these methods it might be useful to use even more switches for readability purposes. Then you start using TryParse/ConvertTo as I descibed above. What I'm saying is: One step at a time, Keep It Simple, and branch out to more specifics on the way. Using Interfaces or RegEx or whatever to "parse" your data in "one" line... and you will end up in some completely unreadable and non-maintainable code. Best regards The K.I.S.-guy
  • C# and Excel

    csharp visual-studio com question
    9
    0 Votes
    9 Posts
    160 Views
    I
    Thanks, Dave. I'll consider it.
  • Interface with a default implementation

    debugging help question
    13
    0 Votes
    13 Posts
    209 Views
    C
    It may be worth pointing out that as the code stands Port interface has no access to FooData1 or FooData2. public class Foo : Foo.Port { private Foo() { } public int FooData1 { get; set; } public int FooData2 { get; set; } public interface Port { static Port Default = new Foo(); protected int FooData1 { get; } protected int FooData2 { get; } static (int, int) Action() { return (Default.FooData1, Default.FooData2); } } } Now we have access to FooData1 and FooData2. Foo is private and the only instance of Foo or Port is Foo.Port.Default and we can access it as such. var bar = Foo.Port.Default; var foobar = (Foo)bar; foobar.FooData1 = 10; foobar.FooData2 = 20; Console.WriteLine(Foo.Port.Action()); If we want more than the single instance of Foo we need a Clone() method in Foo which can be easily done like this. public object Clone() { var (X, Y) = Foo.Port.Action(); return new Foo() { FooData1 = X, FooData2 = Y }; }
  • 0 Votes
    1 Posts
    38 Views
    No one has replied
  • How to Fix a NullReferenceException in C#?

    help csharp com tutorial question
    6
    0 Votes
    6 Posts
    116 Views
    OriginalGriffO
    Can I replace the egg with a sausage? :-D "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!
  • Game

    csharp game-dev tutorial
    4
    0 Votes
    4 Posts
    90 Views
    C
    bool playing = true; public Form1() { InitializeComponent(); } private Button[] Cells => new Button[] { //top row button1, button2, button3, //middle row button4, button5, button6, //bottom row button7, button8, button9 }; private bool IsBoardFull { get { bool result = true; foreach (Button btn in Cells) { if (btn.Enabled) { result = false; break; } } return result; } } //This tells our CheckForWinner if their is a winner private bool IsThreeInRow { get { //rows if (Cells[0].Text == "X" && Cells[1].Text == "X" && Cells[2].Text == "X" || Cells[0].Text == "O" && Cells[1].Text == "O" && Cells[2].Text == "O" || Cells[3].Text == "X" && Cells[4].Text == "X" && Cells[5].Text == "X" || Cells[3].Text == "O" && Cells[4].Text == "O" && Cells[5].Text == "O" || Cells[6].Text == "X" && Cells[7].Text == "X" && Cells[8].Text == "X" || Cells[6].Text == "O" && Cells[7].Text == "O" && Cells[8].Text == "O" || //columns Cells[0].Text == "X" && Cells[3].Text == "X" && Cells[6].Text == "X" || Cells[0].Text == "O" && Cells[3].Text == "O" && Cells[6].Text == "O" || Cells[1].Text == "X" && Cells[4].Text == "X" && Cells[7].Text == "X" || Cells[1].Text == "O" && Cells[4].Text == "O" && Cells[7].Text == "O" || Cells[2].Text == "X" && Cells[5].Text == "X" && Cells[8].Text == "X" || Cells[2].Text == "O" && Cells[5].Text == "O" && Cells[8].Text == "O" || //Diagional Cells[0].Text == "X" && Cells[4].Text == "X" && Cells[8].Text == "X" || Cells[0].Text == "O" && Cells[4].Text == "O" && Cells[8].Text == "O" || Cells[2].Text == "X" && Cells[4].Text == "X" && Cells[6].Text == "X" || Cells[2].Text == "O" && Cells[4].Text == "O" && Cells[6].Text == "O") return true; return false; } } //This is for the computer play. It just returns all //the possible plays that are currently available. It //chooses one of these at random, better computer play //logic should be thought out. private IEnumerable PossibleMoves() { return Cells.Where((button) => button.Enabled); } private void CheckForWinner() { string draw = "Sorry, it was a draw."; string playAgain = "Another Game?"; string sorry = "Sorry, you los
  • 0 Votes
    6 Posts
    109 Views
    J
    Presumably you have a well designed understanding of what the additional functionality is in general. There are a number of design patterns that might be useful in structuring the code. - Chain of responsibility - Fly weight - Decorator - Composite - Template As suggested other response you use reflection to load classes dynamically. Those will need either an interface or base class for your code to interact with it. You will need to at least consider dependencies (other dlls required by the dll that is loaded) in that they must be located somewhere. Either load those also dynamically or insure that the application can find them. AtaChris wrote: with reduced functionality That is a design and business consideration which cannot be addressed generically. For example perhaps you want to switch out your database driver. But the application cannot operate without any database. Same thing with supporting multiple card card processor interfaces. If you expect two but only find one then that is ok. But if you find none then the application probably cannot continue. There are ways around failure cases but they add significant complexity and even business risk.
  • button event handler where it drops it?

    question
    14
    0 Votes
    14 Posts
    178 Views
    RaviBeeR
    Yes. /ravi My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com
  • 0 Votes
    3 Posts
    74 Views
    Richard Andrew x64R
    Ah! Makes sense. Thanks! The difficult we do right away... ...the impossible takes slightly longer.
  • Would this be a valid Extension?

    question
    6
    0 Votes
    6 Posts
    78 Views
    C
    Thanks for the hint on the using the SemaphoreSlim. This works much better than the original extension I was using.
  • 0 Votes
    3 Posts
    56 Views
    C
    You're going to need to add a manifest to your project. Add -> Item -> Application Manifest File. Change the line that says requestedExecutionLevel from level="asInvoker" to level="requireAdministrator"
  • 0 Votes
    4 Posts
    59 Views
    C
    Have you read this? Complete basic operations using SharePoint client library code | Microsoft Learn[^]
  • Converting ulaw to alaw

    question
    6
    0 Votes
    6 Posts
    83 Views
    C
    Thanks for the link. The error was in fact in the Ulaw to Alaw Encoding, The output audio now sounds identical although the samples are different. I will have to look into this I assume it could be do to endianness.