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 %

Monday, June 6, 2022

win os - How to copy all files defined by mask in all subdirectories into one directory

Copy all *.mobi files in current directory and all subdirectories into c:\temp\mobi directory. 
The destination directory must exists.
find . -name \*.mobi -exec cp {} c:/temp/mobi/ \;

Tuesday, May 10, 2022

c# - How to make DOWN button (in group of buttons)

The goal: Only one button from group can be down.
Every button link through Click event to this method:
private void downclick( object sender, EventArgs e ) {
  Button b = (Button)sender;

  /* if is down -> do nothing */
  if ( b.BackColor == Color.IndianRed ) return;

  /* set as down */
  b.BackColor = Color.IndianRed;

  /* deselect others */
  b.Parent.Controls
    .Cast<Control>()
    .Where( x => x is Button )
    .Cast<Button>()
    .Where( x => x != b )
    .ToList()
    .ForEach( x => x.BackColor = Color.WhiteSmoke );
}
So - pushed button = Color.IndianRed. If you want to know which button is down pushed:
  /* get down button */
  Button b = groupBox1.Controls
    .Cast<Control>()
    .Where( x => x is Button )
    .Cast<Button>()
    .Where( x => x.BackColor == Color.IndianRed )
    .ToList()
    .FirstOrDefault();
        
  MessageBox.Show( b.Text );
}

Tuesday, April 19, 2022

c# - How to create instance with string class name

String variable sClass contains for example Box.LayoutItem string. ParentObject and ParentID are optional constructor parameters.
var p = Activator.CreateInstance( Type.GetType( sClass ), parentObject, parentID );
LayoutItem p1 = (LayoutItem)p;
p1.Load( x );

Tuesday, March 29, 2022

c# - How to solve error "Sequence contains no elements" by Max() LINQ

This error occurs when the list is empty - no items are suitable for conditions.
int xCalc = _layoutManager.Items
  .Where( x=> x.ParentObject == this.ParentObject )
  .Where( x=> x.LayoutRelativePosition == LayoutRelativePositionEnum.RIGHT )
  .Where( x=> x.IDOrder < this.IDOrder )              
  .Max( x=> x.xCalc + x.heightCalc );
Above Max() version returns in that situation (no items) error "Sequence contains no elements". For solution you can use this format of the Max() function:
int xCalc = _layoutManager.Items
  .Where( x=> x.ParentObject == this.ParentObject )
  .Where( x=> x.LayoutRelativePosition == LayoutRelativePositionEnum.RIGHT )
  .Where( x=> x.IDOrder < this.IDOrder )
  .Select(x => x.xCalc + x.heightCalc )
  .DefaultIfEmpty()          
  .Max();

Monday, March 21, 2022

c# - How get last x chars from string by LINQ

One possibility (last 6 chars):
string s = "This is a text";
      
MessageBox.Show( s.Substring( s.Length - 6 ) );
Another possibility with LINQ support (last 6 chars):
string s = "This is a text";
      
MessageBox.Show( new string( s.TakeLast(6).ToArray() ) );

Thursday, February 24, 2022

Monday, February 21, 2022

c# - How to download file from the web as string

Useful for example for .xml downloading. 

Old (now obsolete method):
string str = "";
#pragma warning disable SYSLIB0014 // Type or member is obsolete
using( var wc = new WebClient() )
{
  str = wc.DownloadString( this.URL );
}
#pragma warning restore SYSLIB0014 // Type or member is obsolete
New method:
string str = "";
HttpClient client = new HttpClient();
using ( HttpResponseMessage response = client.GetAsync( this.URL ).Result )
{
  using ( HttpContent content = response.Content )
  {
    str = content.ReadAsStringAsync().Result;
  }
}

Wednesday, January 26, 2022

sql server - How to use IFF instead of CASE

Since 2012+ version can be used IFF statement (similar like DECODE() in Oracle):
select todate 
from pricedisctable
where
itemrelation = 'S-331-123-2056';

select IIF( todate='1900-01-01 00:00:00.000', null, todate ) 
from pricedisctable
where
itemrelation = 'S-331-123-2056';
Output:

Wednesday, December 22, 2021

c# - How to quickly get count of the char in string

The fastest way in c# (counts the commas here):
string s = "Added on Monday, December 20, 2021 2:19:21 PM";
int count = note.Location.Count( x => x == ',' );
Output:
2

c# - How to make generic unique list with GroupBy()

This code make unique book name list + ensures sorting of the list.
private List notes = new List();
...
List uniqueBooks = new List();

uniqueBooks = 
  notes.GroupBy( x => x.BookName ).Select( g => new Note { BookName = g.Key } ).ToList();
uniqueBooks.Sort( (x, y ) => x.BookName.CompareTo( y.BookName ) );

c# - How to convert string into datetime with mask

DateTime dt;                      
bool b = DateTime.TryParseExact( "December 20, 2021", "MMMM d, yyyy", 
                                 new System.Globalization.CultureInfo("en-US"), 
                                 DateTimeStyles.None, out dt );
if ( b ) Console.WriteLine( dt.Year );
Output:
2021
if you have some problem with conversion, try reversal order at first for checking (=>compare if your string is same as output here):
Console.WriteLine( 
DateTime.Now.ToString( "MMMM d, yyyy", new System.Globalization.CultureInfo("en-US") ) );

Thursday, December 16, 2021

D365 - How to prevent warning "BPERRORLABELISTEXT"

A very quick way is to change the quotation marks to apostrophes.
info( "xxx" ) -> info( 'xxx' );
The solution for this warning:

Tuesday, December 14, 2021

D365 - How to solve warning "[BPUnusedStrFmtArgument]:The placeholder '%1' to strFmt is not used in the format string."

Old migrated code from AX 2012:
warning( strFmt( "@cieb:cieb4", _sParamName ) );
shows this warning (in label is this value "Attention - parameter %1 not found."): BP Rule: [BPUnusedStrFmtArgument]:The placeholder '%1' to strFmt is not used in the format string.

 For this warning removing add literalStr() for label string validation.
warning( strFmt( literalStr("@cieb:cieb4"), _sParamName ) );

Thursday, November 18, 2021

JAVASCRIPT - How to sort an array

// ancending order
    
var numbers = [ 10, 12, 5, 7.5, 7 ];
numbers.sort( ( a, b ) => a - b );
numbers.forEach( item => {
  document.write( item + "
" ); }); document.write( "
" ); // descending order numbers.sort( ( a, b ) => b - a ); numbers.forEach( item => { document.write( item + "
" ); });
Output:
5
7
7.5
10
12

12
10
7.5
7
5

Tuesday, November 9, 2021

JAVASCRIPT - How to split string into parts

var s = "This;is;a;text";
var vars = s.split( ";" );
vars.forEach( element => {
  document.write( element + "
" ); } );
Output:
This
is
a
text

Friday, November 5, 2021

JAVASCRIPT - How to make an action 5 seconds after page loading

This code in HEAD section:
<script>
setTimeout( LoadingProc, 5000 );
    
function LoadingProc() {
  alert( "5 seconds gone -> loading procedure." );
}
</script>

Thursday, November 4, 2021

JAVASCRIPT - How to work with classes and instances

Base class:
class Shape {
   
  desc = "";

  constructor( _desc ) {
    this.desc = _desc;
  }

  get2Desc() {
    return this.desc + this.desc;
  }

}
Instance of class and calling class method:
b.addEventListener( 'click', function () {    
      
  const myShape = new Shape( "this is a desc" );
  console.log( myShape.get2Desc() );
  
}
Output:
this is a descthis is a desc

Wednesday, November 3, 2021

HTML - How to make a different color for blank textbox

<style>
  .validated:invalid {
    background: #FAC3C9;
  }

  .validated:valid {
    background: #BDF0A8;
   }
</style>

<form action="action.php">
  <input required name="name1" class="validated" type="text" />
</form>

JAVASCRIPT - getElementById() vs querySelector()

Different methods for same task - find the item by its ID.
var progressBar = document.getElementById( "progress" );
var progressBar = document.querySelector( "#progress" );
var progressBar = document.querySelector( "[id=progress]" );

Tuesday, November 2, 2021

HTML - Some new HTML5 input fields

<div class="form" width="100px">
  <input name="e1" type="date" />
  <input name="e2" type="color" />
  <input name="e3" type="datetime-local" />
  <input name="e4" type="email" />
  <input name="e5" type="month" />
  <input name="e6" type="week" />
  <input name="e7" type="file" />
</div>
Output:

Monday, September 6, 2021

.NET - How to install pre-release tool through terminal

Specify --version parameter.
dotnet tool install -g dotnet-ef --version 6.0.0-preview.7.21378.4
Output: