Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Tuesday, November 25, 2025

c++ - How to make .dll and call it from c#

c++ DLL cpp:
extern "C" __declspec( dllexport )
int math_add( int const d1, int const d2 ) {
    return d1 + d2;
}
Test c++ console app:
#include 

extern "C" __declspec( dllimport ) int math_add( int, int );

int main( int argc, char* argv[] )
{
    int i = math_add( 4, 5 );

    std::cout << '\n' << i << '\n';
    
    std::cout << "Press any key..";

    std::cin.get();

    return 0;
}
C# class:
using System.Runtime.InteropServices;

namespace test {
    public class PILib {

        [DllImport( "piMath.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern int math_add( int _v1, int _v2);

    }
}
Calling in c#:
private void button1_Click( object sender, EventArgs e ) {
    int i = PILib.math_add( 3, 5 );

    MessageBox.Show( i.ToString() );
}
Output:

Tuesday, November 4, 2025

c# - How to call Min(), Max() on generic List

DateTime minStartTime = 
ListOfProcesesForKilling.Min( p => {        
  return p.StartTime;
} );
value += $"Min starttime: {minStartTime};";

c# - How to force JSON enum to save as TEXT instead of a NUMBER

This enum property:
public enum MinimizeActionEnum {
  NONE = 0,
  CLEAR = 1
}
    
public MinimizeActionEnum MinimizeAction { get; set; } = MinimizeActionEnum.NONE;
It is saved as INT by default:
"ReportParams": [
{
  "Name": "pProdId",
  "Description": "",
  "MinimizeAction": 0
},
With using that attribute:
[JsonConverter(typeof(JsonStringEnumConverter))]
public MinimizeActionEnum MinimizeAction { get; set; } = MinimizeActionEnum.NONE;
the enum value will be stored as TEXT:
"ReportParams": [
{
  "Name": "pProdId",
  "Description": "",
  "MinimizeAction": NONE
},

Monday, October 13, 2025

c# - How to solve JSON deserialization problem

JSON deserialization returns this error:
Each parameter in the deserialization constructor on type 
'cieb_AXReportPrintDLG.ReportParamComboValues' must bind 
to an object property or field on deserialization. Each 
parameter name must match with a property or field on the 
object. Fields are only considered when 
'JsonSerializerOptions.IncludeFields' is enabled. 
The match can be case-insensitive.
All fields looks like OK. The problem is in the parameter names in the constructor. This version returns error:
public class ReportParamComboValues {

  /* description - for text */
  public string Description { get; set; }

  /* returned value for SSRS report param */
  public string Value { get; set; }

  public ReportParamComboValues( string _description, string _value ) {  
    this.Description = _description;
    this.Value = _value;
  }

}
This is working:
public class ReportParamComboValues {

  /* description - for text */
  public string Description { get; set; }

  /* returned value for SSRS report param */
  public string Value { get; set; }

  public ReportParamComboValues( string Description, string Value ) {  
    this.Description = Description;
    this.Value = Value;
  }

}

Monday, September 29, 2025

c# - How to solve problem with convension date into string with char "/" in format mask

This result can be obtained when trying to convert a date to a string using a format mask containing the character '/'.
DateTime dt = DateTime.Now;
MessageBox.Show( dt.ToString( "yyyy/MM/dd", CultureInfo.GetCultureInfo( "de-DE" ) ) );
Output:
2025.09.29
The solution is to change the Culture:
DateTime dt = DateTime.Now;
MessageBox.Show( dt.ToString( "yyyy/MM/dd", CultureInfo.GetCultureInfo( "en-US" ) ) );
Output:
2025/09/29

Tuesday, September 2, 2025

c# - How to add items to combobox with text description from attribute

Define new enum with attributes:
/* types for printing type combobox */
public enum PrintingTypeEnum
{
  [Description( "On screen" ) ]
  TO_SCREEN,
  [Description( "On printer" ) ]
  TO_PRINT
}
Fill the combobox with items:
CPrintingType.Items.Clear();
foreach (  PrintingTypeEnum item in Enum.GetValues( typeof( PrintingTypeEnum ) ) )
{
    string description = GetEnumDescription( item );
    CPrintingType.Items.Add( description );

    /* -- default value */  
    if ( item == PrintingTypeEnum.TO_PRINT )
    {
    	CPrintingType.SelectedIndex = CPrintingType.Items.Count - 1;
    }
}

private string GetEnumDescription( Enum _value )
{
    FieldInfo field = _value.GetType().GetField( _value.ToString() );
    DescriptionAttribute attribute = field?.GetCustomAttribute<DescriptionAttribute>();
    return attribute == null ? _value.ToString() : attribute.Description;
}
Output:

Tuesday, May 13, 2025

c# - EF - How to call storedproc with OUTPUT param

You have this stored proc:
ALTER PROCEDURE [dbo].[TEST]
	-- Add the parameters for the stored procedure here
( @Param1 int, @Message varchar(50) output )
AS
BEGIN
  set @Message = 'xxx';

  return '-1';
END
For calling it use this code:
var param1 = new SqlParameter( "Param1", System.Data.SqlDbType.Int );
param1.Direction = System.Data.ParameterDirection.Input;
param1.Value = iYear;

var message = new SqlParameter( "Message", System.Data.SqlDbType.VarChar, 50 ); 
message.Direction = System.Data.ParameterDirection.InputOutput;
message.Value = "";

var ret = context.Database.ExecuteSqlRaw(
  "EXEC TEST @Param1 = @param1, @Message = @message OUTPUT", param1, message
);

MessageBox.Show( message.Value.ToString() );
MessageBox.Show( ret.ToString() );

c# - EF - How to refresh existing DB into EF model

If you have DB and if you want to refresh it`s model into MODEL directory, call this:
dotnet ef dbcontext scaffold "Server=(LocalDB)\MSSQLLocalDB;
AttachDbFilename=C:\_projects\vs\FioTax\FioTax\db.mdf;
Integrated Security=True;Connect Timeout=30" Microsoft.EntityFrameworkCore.SqlServer 
--output-dir Models --context AppDbContext --force

Tuesday, January 16, 2024

c# - How to use LINQ aggregate() function

This calling performs SUM on Population (with starting value = 0.)
    
public List<Country> Countries = new();
...
this.Countries.Add( new Country( "Czech", Country.ContinentEnum.EUROPE, 10 ) );
this.Countries.Add( new Country( "Poland", Country.ContinentEnum.EUROPE, 40 ) );
this.Countries.Add( new Country( "China", Country.ContinentEnum.ASIA, 1100 ) );
this.Countries.Add( new Country( "USA", Country.ContinentEnum.AMERICA, 340 ) );
...
int total = this.Countries.Aggregate( 0, (total,b) => total + b.Population );

MessageBox.Show( total.ToString() );  // -> 1490

Thursday, November 30, 2023

c# - How to call custom event

1) Custom event without parameters:
public Action OnBeforeEvaluationEvent;
...
if ( OnBeforeEvaluationEvent != null ) OnBeforeEvaluationEvent();
2) Custom event with parameter(s):
public delegate void OnAfterEvaluatingDelegate( CodeConditionGroup _conditionGroup );    
public event OnAfterEvaluatingDelegate OnAfterEvaluationgEvent;

if ( OnAfterEvaluationgEvent != null ) OnAfterEvaluationgEvent( condition );

Friday, November 24, 2023

c#, devexpress - How to make master-detail relation on non-DB objects (List generic )

List<TmpParent> list = new List<TmpParent>();

List<TmpChild> listChildExternal = new List<TmpChild>();
Initial data filling:
var p = new TmpParent( "A", "A", true );
p.listInner.Add( new TmpChild() );
list.Add( p );
list.Add( new TmpParent( "B", "B", false, TypeEnum.OPERATOR ) );
list.Add( new TmpParent( "C", "C", true ) );
list.Add( new TmpParent( "D", "D", false ) );

listChildExternal.Add( new TmpChild() { str1="C", str2 = "child1" } );
listChildExternal.Add( new TmpChild() { str1="C", str2 = "child1.1" } );
listChildExternal.Add( new TmpChild() { str1="B", str2 = "child1.2" } );

gridParent.DataSource = list;	// master
Find and show detail data:
  • First detail list for inner list.
  • Second detail list for external list connected with relation.
private void gridViewParent_FocusedRowChanged( object sender, 
  DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e ) {
   
  if ( e.FocusedRowHandle >= 0 ) {        
    TmpParent master = gridView1.GetRow( e.FocusedRowHandle ) as TmpParent;
    if ( master != null ) {          
      /* A] try to find in inner list */
      gridDetail.DataSource = master.listInner;

      /* B] try to find in external list */           
      gridChildExternal.DataSource = 
        listChildExternal.Where( x => x.str1 == master.str1 ).ToList();
    }
  }
}
First grid=master, second grid=detail internal list, third grid=detail external list.

Tuesday, November 14, 2023

c#, devexpress - How to use attributes in GridControl (devexpress)

The attributes in the class can be used as metadata for generated GridControl (devexpress) columns. 

Class for rows:
public enum TypeEnum {
   [Display(Name = "Type is expression.")]  
   EXPRESSION = 0,
   [Display(Name = "Type is operator.")]  
   OPERATOR = 1
}    

public class TmpParent
{            
   [Display(
     ShortName = "Company", 
     Name = "Company Name", 
     Description = "The amount of currently available product", 
     AutoGenerateFilter = false)
   ]
  public string str1 { get; set; }
  [DataType(DataType.Text), StringLength(20, MinimumLength = 3)]
  public string str2 { get; set; }
  public bool bool1 { get; set; }
  public TypeEnum enum1 { get; set; }
  [DisplayFormat(DataFormatString = "MMMM/yyyy")]
  public DateTime date1 { get; set; }
  [DisplayFormat(DataFormatString = "p", ApplyFormatInEditMode = true)]
  public float value1 {  get; set; }
  [DataType(DataType.Currency), Range(200, 5000), Required]    
  public float value2 { get; set; }
        
   public TmpParent( string _s1, string _s2, bool _b, TypeEnum _enum = TypeEnum.EXPRESSION )
   {
     str1 = _s1;
     str2 = _s2;
     bool1 = _b;
     enum1 = _enum;
     date1 = DateTime.Now;
     value1 = 100.1f;
     value2 = 300.5f;
   }
}
Grid fillings:
var p = new TmpParent( "A", "A", true );
list.Add( p );
list.Add( new TmpParent( "B", "B", false, TypeEnum.OPERATOR ) );
list.Add( new TmpParent( "C", "C", true ) );
list.Add( new TmpParent( "D", "D", false ) );

gridParent.DataSource = list;
Output:

Wednesday, July 12, 2023

Friday, April 14, 2023

c# - How to solve problem on TEST project with error on referenced project

The problem with the referenced project error can be solved with this change: 

 Set "Target OS" from "None" to something else.

Monday, January 30, 2023

c# - How to save List into text file

public List CodeLogOnlyList = new();
...
await System.IO.File.WriteAllLinesAsync( _filename, this.CodeLogOnlyList );

Friday, January 20, 2023

Friday, July 22, 2022

c# - How convert string array into one string

If you use this code on string array:
string[] args = Environment.GetCommandLineArgs();      
Console.Write( args.ToString() );
you will get:
System.String[]
But better way in this case is to use string.Join() function (where you can set used delimiter):
string[] args = Environment.GetCommandLineArgs();      
Console.Write( string.Join( ",", args ) );
Then:
C:\app.dll,layoutdir=C:/app/bin

Friday, June 24, 2022

c# - How get important system informations

Sometimes you need for example width of the standard scrollbar. For getting it you can use SystemInformation class (WinForms). Here is a list of supported properties and their values.
Type t = typeof( System.Windows.Forms.SystemInformation );            
PropertyInfo[] property = t.GetProperties();

for( int i = 0; i < property.Length; i++ )
  richTextBox1.Text += property[ i ].Name + " = " + 
  property[ i ].GetValue( null, null ).ToString() + "\n";        
Output:
DragFullWindows = True
HighContrast = False
MouseWheelScrollLines = 3
PrimaryMonitorSize = {Width=1920, Height=1080}
VerticalScrollBarWidth = 17
HorizontalScrollBarHeight = 17
CaptionHeight = 23
BorderSize = {Width=1, Height=1}
FixedFrameBorderSize = {Width=3, Height=3}
VerticalScrollBarThumbHeight = 17
HorizontalScrollBarThumbWidth = 17
IconSize = {Width=32, Height=32}
CursorSize = {Width=32, Height=32}
MenuFont = [Font: Name=Segoe UI, Size=12, Units=0, GdiCharSet=1, GdiVerticalFont=False]
MenuHeight = 20
PowerStatus = System.Windows.Forms.PowerStatus
WorkingArea = {X=0,Y=0,Width=1920,Height=1080}
KanjiWindowHeight = 0
MousePresent = True
VerticalScrollBarArrowHeight = 17
HorizontalScrollBarArrowWidth = 17
DebugOS = False
MouseButtonsSwapped = False
MinimumWindowSize = {Width=136, Height=39}
CaptionButtonSize = {Width=36, Height=22}
FrameBorderSize = {Width=4, Height=4}
MinWindowTrackSize = {Width=136, Height=39}
DoubleClickSize = {Width=4, Height=4}
DoubleClickTime = 500
IconSpacingSize = {Width=75, Height=75}
RightAlignedMenus = False
PenWindows = False
DbcsEnabled = False
MouseButtons = 8
Secure = False
Border3DSize = {Width=2, Height=2}
MinimizedWindowSpacingSize = {Width=160, Height=28}
SmallIconSize = {Width=16, Height=16}
ToolWindowCaptionHeight = 23
ToolWindowCaptionButtonSize = {Width=22, Height=22}
MenuButtonSize = {Width=19, Height=19}
ArrangeStartingPosition = Hide
ArrangeDirection = Left
MinimizedWindowSize = {Width=160, Height=28}
MaxWindowTrackSize = {Width=1940, Height=1100}
PrimaryMonitorMaximizedWindowSize = {Width=1936, Height=1096}
Network = True
TerminalServerSession = False
BootMode = Normal
DragSize = {Width=4, Height=4}
ShowSounds = False
MenuCheckSize = {Width=15, Height=15}
MidEastEnabled = False
NativeMouseWheelSupport = True
MouseWheelPresent = True
VirtualScreen = {X=0,Y=0,Width=1920,Height=1080}
MonitorCount = 1
MonitorsSameDisplayFormat = True
ComputerName = WZ1G89XBX
UserDomainName = LYZ
UserInteractive = True
UserName = pirklj
IsDropShadowEnabled = True
IsFlatMenuEnabled = True
IsFontSmoothingEnabled = True
FontSmoothingContrast = 1200
FontSmoothingType = 2
IconHorizontalSpacing = 75
IconVerticalSpacing = 75
IsIconTitleWrappingEnabled = True
MenuAccessKeysUnderlined = False
KeyboardDelay = 1
IsKeyboardPreferred = False
KeyboardSpeed = 31
MouseHoverSize = {Width=4, Height=4}
MouseHoverTime = 400
MouseSpeed = 10
IsSnapToDefaultEnabled = False
PopupMenuAlignment = Right
IsMenuFadeEnabled = True
MenuShowDelay = 400
IsComboBoxAnimationEnabled = True
IsTitleBarGradientEnabled = True
IsHotTrackingEnabled = True
IsListBoxSmoothScrollingEnabled = True
IsMenuAnimationEnabled = True
IsSelectionFadeEnabled = True
IsToolTipAnimationEnabled = True
UIEffectsEnabled = True
IsActiveWindowTrackingEnabled = False
ActiveWindowTrackingDelay = 0
IsMinimizeRestoreAnimationEnabled = False
BorderMultiplierFactor = 1
CaretBlinkTime = 530
CaretWidth = 1
MouseWheelScrollDelta = 120
VerticalFocusThickness = 1
HorizontalFocusThickness = 1
VerticalResizeBorderThickness = 4
HorizontalResizeBorderThickness = 4
ScreenOrientation = Angle0
SizingBorderWidth = 1
SmallCaptionButtonSize = {Width=22, Height=22}
MenuBarButtonSize = {Width=19, Height=19}

Thursday, June 9, 2022

c# - How to format interpolated strings

This example writes double value with two decimal places.
double zoom = this.ZoomFactor * 100.0;
LStatusZoom.Text = $"Zoom: {zoom:0.##} %";
Output:
Zoom: 80.25 %